oxiproj-engine 0.1.2

Proj-string parser, operation dispatch, and transformation pipelines for OxiProj.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
//! End-to-end differential integration tests validating `oxiproj-engine`
//! output against system PROJ 9.7.0 (numerically identical to 9.8 for these
//! projections).
//!
//! All reference constants are HARDCODED below so this test runs WITHOUT proj
//! installed (CI-safe). The forward checks compare against the hardcoded PROJ
//! reference outputs; the inverse and round-trip checks are self-consistency
//! checks (project forward, then inverse, and confirm we recover the original
//! geographic radians).
//!
//! Each reference constant was regenerated with the exact proj command shown
//! for its case, reproduced verbatim below:
//!
//! 1. `printf '9 0\n12 55\n' | proj -f '%.10f' +proj=utm +zone=32 +ellps=WGS84`
//! 2. `printf '0 0\n12 55\n' | proj -f '%.10f' +proj=merc +ellps=WGS84`
//! 3. `printf '9 50\n' | proj -f '%.10f' +proj=etmerc +lon_0=9 +ellps=WGS84`
//! 4. `printf '10 40\n' | proj -f '%.10f' +proj=merc +lat_ts=45 +ellps=WGS84`
//! 5. `printf '10 41\n' | proj -f '%.10f' +proj=tmerc +lat_0=40 +k_0=0.9996 +lon_0=9 +ellps=WGS84`
//!
//! PROJ version: Rel. 9.7.0, September 1st 2025. The regenerated originally
//! used a Homebrew install at `/opt/homebrew/bin/proj`; the `#[ignore]`d
//! `regenerate_fixtures_via_proj` test below now locates the `proj` binary
//! via `resolve_proj_bin` (the `PROJ_BIN` env var, or a `PATH` search) so it
//! works on any machine/OS rather than only Apple-silicon Homebrew.

use oxiproj_core::{Coord, Direction, DEG_TO_RAD};
use oxiproj_engine::{create, trans};

/// Locate a `proj` binary to regenerate fixtures against.
///
/// Resolution order:
/// 1. `PROJ_BIN` — if set, used verbatim (no existence check skipped: an
///    explicit override that doesn't exist is reported, not silently
///    ignored in favor of a `PATH` binary the caller didn't ask for).
/// 2. A `PATH` lookup for `proj` (`proj.exe` on Windows).
///
/// Returns `None` if neither resolves to an existing file. Never hardcodes
/// an absolute, platform-specific install location.
fn resolve_proj_bin() -> Option<std::path::PathBuf> {
    if let Some(v) = std::env::var_os("PROJ_BIN") {
        let p = std::path::PathBuf::from(v);
        return if p.is_file() { Some(p) } else { None };
    }
    let path_var = std::env::var_os("PATH")?;
    for dir in std::env::split_paths(&path_var) {
        let candidate = dir.join("proj");
        if candidate.is_file() {
            return Some(candidate);
        }
        let candidate_exe = dir.join("proj.exe");
        if candidate_exe.is_file() {
            return Some(candidate_exe);
        }
    }
    None
}

/// Assert that `got` is within `tol` of `expected`, with a descriptive panic
/// message identifying `what` along with the actual values and absolute diff.
fn assert_close(got: f64, expected: f64, tol: f64, what: &str) {
    let diff = (got - expected).abs();
    assert!(
        diff < tol,
        "{what}: got {got}, expected {expected}, abs diff {diff} >= tol {tol}",
    );
}

#[test]
fn utm_zone32_forward_and_inverse() {
    let pj = create("+proj=utm +zone=32 +ellps=WGS84").expect("create utm zone 32");

    // (lon_deg, lat_deg, expected_x, expected_y)
    let rows = [
        (9.0, 0.0, 500000.0000000000, 0.0000000000),
        (12.0, 55.0, 691_875.632_137_542, 6_098_907.825_129_169),
    ];

    for (lon_deg, lat_deg, expected_x, expected_y) in rows {
        let lon_rad = lon_deg * DEG_TO_RAD;
        let lat_rad = lat_deg * DEG_TO_RAD;

        let fwd = trans(&pj, Direction::Fwd, Coord::new(lon_rad, lat_rad, 0.0, 0.0))
            .expect("utm forward");
        println!(
            "[case 1] dx={:e} dy={:e}",
            (fwd.v()[0] - expected_x).abs(),
            (fwd.v()[1] - expected_y).abs()
        );
        assert_close(fwd.v()[0], expected_x, 1e-6, "case 1 forward x");
        assert_close(fwd.v()[1], expected_y, 1e-6, "case 1 forward y");

        let inv = trans(&pj, Direction::Inv, fwd).expect("utm inverse");
        assert_close(inv.v()[0], lon_rad, 1e-9, "case 1 inverse lon");
        assert_close(inv.v()[1], lat_rad, 1e-9, "case 1 inverse lat");
    }
}

#[test]
fn merc_wgs84_forward_and_inverse() {
    let pj = create("+proj=merc +ellps=WGS84").expect("create merc");

    let rows = [
        (0.0, 0.0, 0.0000000000, 0.0000000000),
        (12.0, 55.0, 1335833.8895192828, 7_326_837.715_045_549),
    ];

    for (lon_deg, lat_deg, expected_x, expected_y) in rows {
        let lon_rad = lon_deg * DEG_TO_RAD;
        let lat_rad = lat_deg * DEG_TO_RAD;

        let fwd = trans(&pj, Direction::Fwd, Coord::new(lon_rad, lat_rad, 0.0, 0.0))
            .expect("merc forward");
        println!(
            "[case 2] dx={:e} dy={:e}",
            (fwd.v()[0] - expected_x).abs(),
            (fwd.v()[1] - expected_y).abs()
        );
        assert_close(fwd.v()[0], expected_x, 1e-6, "case 2 forward x");
        assert_close(fwd.v()[1], expected_y, 1e-6, "case 2 forward y");

        let inv = trans(&pj, Direction::Inv, fwd).expect("merc inverse");
        assert_close(inv.v()[0], lon_rad, 1e-9, "case 2 inverse lon");
        assert_close(inv.v()[1], lat_rad, 1e-9, "case 2 inverse lat");
    }
}

#[test]
fn etmerc_lon0_9_forward_and_inverse() {
    let pj = create("+proj=etmerc +lon_0=9 +ellps=WGS84").expect("create etmerc");

    let lon_deg = 9.0;
    let lat_deg = 50.0;
    let expected_x = 0.0000000000;
    let expected_y = 5_540_847.041_684_148;

    let lon_rad = lon_deg * DEG_TO_RAD;
    let lat_rad = lat_deg * DEG_TO_RAD;

    let fwd =
        trans(&pj, Direction::Fwd, Coord::new(lon_rad, lat_rad, 0.0, 0.0)).expect("etmerc forward");
    println!(
        "[case 3] dx={:e} dy={:e}",
        (fwd.v()[0] - expected_x).abs(),
        (fwd.v()[1] - expected_y).abs()
    );
    assert_close(fwd.v()[0], expected_x, 1e-6, "case 3 forward x");
    assert_close(fwd.v()[1], expected_y, 1e-6, "case 3 forward y");

    let inv = trans(&pj, Direction::Inv, fwd).expect("etmerc inverse");
    assert_close(inv.v()[0], lon_rad, 1e-9, "case 3 inverse lon");
    assert_close(inv.v()[1], lat_rad, 1e-9, "case 3 inverse lat");
}

#[test]
fn merc_lat_ts_45_forward_and_inverse() {
    let pj = create("+proj=merc +lat_ts=45 +ellps=WGS84").expect("create merc lat_ts");

    let lon_deg = 10.0;
    let lat_deg = 40.0;
    let expected_x = 788468.3509397812;
    let expected_y = 3427056.2478435994;

    let lon_rad = lon_deg * DEG_TO_RAD;
    let lat_rad = lat_deg * DEG_TO_RAD;

    let fwd = trans(&pj, Direction::Fwd, Coord::new(lon_rad, lat_rad, 0.0, 0.0))
        .expect("merc lat_ts forward");
    println!(
        "[case 4] dx={:e} dy={:e}",
        (fwd.v()[0] - expected_x).abs(),
        (fwd.v()[1] - expected_y).abs()
    );
    assert_close(fwd.v()[0], expected_x, 1e-6, "case 4 forward x");
    assert_close(fwd.v()[1], expected_y, 1e-6, "case 4 forward y");

    let inv = trans(&pj, Direction::Inv, fwd).expect("merc lat_ts inverse");
    assert_close(inv.v()[0], lon_rad, 1e-9, "case 4 inverse lon");
    assert_close(inv.v()[1], lat_rad, 1e-9, "case 4 inverse lat");
}

#[test]
fn tmerc_lat0_40_forward_and_inverse() {
    let pj =
        create("+proj=tmerc +lat_0=40 +k_0=0.9996 +lon_0=9 +ellps=WGS84").expect("create tmerc");

    let lon_deg = 10.0;
    let lat_deg = 41.0;
    let expected_x = 84102.1344451089;
    let expected_y = 111481.3706361904;

    let lon_rad = lon_deg * DEG_TO_RAD;
    let lat_rad = lat_deg * DEG_TO_RAD;

    let fwd =
        trans(&pj, Direction::Fwd, Coord::new(lon_rad, lat_rad, 0.0, 0.0)).expect("tmerc forward");
    println!(
        "[case 5] dx={:e} dy={:e}",
        (fwd.v()[0] - expected_x).abs(),
        (fwd.v()[1] - expected_y).abs()
    );
    assert_close(fwd.v()[0], expected_x, 1e-6, "case 5 forward x");
    assert_close(fwd.v()[1], expected_y, 1e-6, "case 5 forward y");

    let inv = trans(&pj, Direction::Inv, fwd).expect("tmerc inverse");
    assert_close(inv.v()[0], lon_rad, 1e-9, "case 5 inverse lon");
    assert_close(inv.v()[1], lat_rad, 1e-9, "case 5 inverse lat");
}

#[test]
fn latlong_identity_round_trip() {
    let pj = create("+proj=latlong +ellps=WGS84").expect("create latlong");

    let pairs = [(0.2, 0.9), (0.0, 0.0), (-0.5, 1.0)];

    for (lon_rad, lat_rad) in pairs {
        let fwd = trans(&pj, Direction::Fwd, Coord::new(lon_rad, lat_rad, 0.0, 0.0))
            .expect("latlong forward");
        assert_close(fwd.v()[0], lon_rad, 1e-12, "latlong forward lon");
        assert_close(fwd.v()[1], lat_rad, 1e-12, "latlong forward lat");

        let inv = trans(&pj, Direction::Inv, fwd).expect("latlong inverse");
        assert_close(inv.v()[0], lon_rad, 1e-12, "latlong inverse lon");
        assert_close(inv.v()[1], lat_rad, 1e-12, "latlong inverse lat");
    }
}

#[test]
fn pipeline_utm_inv_round_trip() {
    let pj = create(
        "+proj=pipeline +step +proj=utm +zone=32 +ellps=WGS84 +step +proj=utm +zone=32 +ellps=WGS84 +inv",
    )
    .expect("create pipeline");

    let lon_rad = 12.0 * DEG_TO_RAD;
    let lat_rad = 55.0 * DEG_TO_RAD;

    let out = trans(&pj, Direction::Fwd, Coord::new(lon_rad, lat_rad, 0.0, 0.0))
        .expect("pipeline forward");
    assert_close(out.v()[0], lon_rad, 1e-9, "pipeline round-trip lon");
    assert_close(out.v()[1], lat_rad, 1e-9, "pipeline round-trip lat");
}

#[test]
#[ignore]
fn regenerate_fixtures_via_proj() {
    use std::io::Write as _;

    let proj_bin = match resolve_proj_bin() {
        Some(p) => p,
        None => {
            println!(
                "proj binary not found (set PROJ_BIN or add `proj` to PATH); \
                 skipping fixture regeneration"
            );
            return;
        }
    };

    let cases: [(&[&str], &str); 5] = [
        (
            &["-f", "%.10f", "+proj=utm", "+zone=32", "+ellps=WGS84"],
            "9 0\n12 55\n",
        ),
        (
            &["-f", "%.10f", "+proj=merc", "+ellps=WGS84"],
            "0 0\n12 55\n",
        ),
        (
            &["-f", "%.10f", "+proj=etmerc", "+lon_0=9", "+ellps=WGS84"],
            "9 50\n",
        ),
        (
            &["-f", "%.10f", "+proj=merc", "+lat_ts=45", "+ellps=WGS84"],
            "10 40\n",
        ),
        (
            &[
                "-f",
                "%.10f",
                "+proj=tmerc",
                "+lat_0=40",
                "+k_0=0.9996",
                "+lon_0=9",
                "+ellps=WGS84",
            ],
            "10 41\n",
        ),
    ];

    for (args, stdin_str) in cases {
        let mut child = std::process::Command::new(&proj_bin)
            .args(args)
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
            .expect("spawn proj");

        {
            let mut stdin = child.stdin.take().expect("open proj stdin");
            stdin
                .write_all(stdin_str.as_bytes())
                .expect("write proj stdin");
        }

        let output = child.wait_with_output().expect("wait for proj");
        println!(
            "proj {}:\n{}",
            args.join(" "),
            String::from_utf8_lossy(&output.stdout)
        );
    }
}

// ── `resolve_proj_bin` regression tests ─────────────────────────────────
//
// `cargo nextest` runs every `#[test]` fn in its own process, so mutating
// process-global env vars (`PROJ_BIN`, `PATH`) here cannot race with other
// tests in this file or crate.

/// Create an executable file named `proj` inside a fresh temp directory and
/// return `(temp_dir, proj_path)`. Marking it executable is a no-op on
/// platforms without Unix permission bits.
fn make_fake_proj_binary(tag: &str) -> (std::path::PathBuf, std::path::PathBuf) {
    let dir = std::env::temp_dir().join(format!(
        "oxiproj-differential-{tag}-{}-{:?}",
        std::process::id(),
        std::thread::current().id()
    ));
    std::fs::create_dir_all(&dir).expect("create temp dir for fake proj binary");
    let fake = dir.join("proj");
    std::fs::write(&fake, b"#!/bin/sh\necho fake-proj\n").expect("write fake proj binary");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = std::fs::metadata(&fake)
            .expect("stat fake proj binary")
            .permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&fake, perms).expect("chmod fake proj binary");
    }
    (dir, fake)
}

#[test]
fn resolve_proj_bin_prefers_proj_bin_env_override() {
    let (dir, fake) = make_fake_proj_binary("env-override");

    let saved = std::env::var_os("PROJ_BIN");
    std::env::set_var("PROJ_BIN", &fake);
    let resolved = resolve_proj_bin();
    match saved {
        Some(v) => std::env::set_var("PROJ_BIN", v),
        None => std::env::remove_var("PROJ_BIN"),
    }
    let _ = std::fs::remove_dir_all(&dir);

    assert_eq!(resolved, Some(fake));
}

#[test]
fn resolve_proj_bin_rejects_nonexistent_env_override_rather_than_falling_back_to_path() {
    // Regression: an explicit but wrong `PROJ_BIN` must be reported (via
    // `None`, which the caller turns into a skip message), never silently
    // ignored in favor of whatever `proj` happens to be on PATH -- that
    // would hide the user's misconfiguration.
    let (dir, fake) = make_fake_proj_binary("path-fallback-guard");

    let saved_proj_bin = std::env::var_os("PROJ_BIN");
    let saved_path = std::env::var_os("PATH");
    let bogus = dir.join("does-not-exist-proj-binary");
    std::env::set_var("PROJ_BIN", &bogus);
    // Put a *valid* proj binary on PATH to prove it is NOT used as a
    // fallback when PROJ_BIN is set but wrong.
    std::env::set_var("PATH", &dir);

    let resolved = resolve_proj_bin();

    match saved_proj_bin {
        Some(v) => std::env::set_var("PROJ_BIN", v),
        None => std::env::remove_var("PROJ_BIN"),
    }
    match saved_path {
        Some(v) => std::env::set_var("PATH", v),
        None => std::env::remove_var("PATH"),
    }
    let _ = std::fs::remove_dir_all(&dir);
    let _ = fake; // only needed to populate PATH above

    assert_eq!(resolved, None);
}

#[test]
fn resolve_proj_bin_falls_back_to_path_lookup_when_env_unset() {
    let (dir, fake) = make_fake_proj_binary("path-lookup");

    let saved_proj_bin = std::env::var_os("PROJ_BIN");
    let saved_path = std::env::var_os("PATH");
    std::env::remove_var("PROJ_BIN");
    std::env::set_var("PATH", &dir);

    let resolved = resolve_proj_bin();

    match saved_proj_bin {
        Some(v) => std::env::set_var("PROJ_BIN", v),
        None => std::env::remove_var("PROJ_BIN"),
    }
    match saved_path {
        Some(v) => std::env::set_var("PATH", v),
        None => std::env::remove_var("PATH"),
    }
    let _ = std::fs::remove_dir_all(&dir);

    assert_eq!(resolved, Some(fake));
}

#[test]
fn resolve_proj_bin_returns_none_when_nothing_resolves() {
    let dir = std::env::temp_dir().join(format!(
        "oxiproj-differential-empty-path-{}-{:?}",
        std::process::id(),
        std::thread::current().id()
    ));
    std::fs::create_dir_all(&dir).expect("create empty temp dir");

    let saved_proj_bin = std::env::var_os("PROJ_BIN");
    let saved_path = std::env::var_os("PATH");
    std::env::remove_var("PROJ_BIN");
    // An existing-but-empty directory on PATH: no `proj`/`proj.exe` in it.
    std::env::set_var("PATH", &dir);

    let resolved = resolve_proj_bin();

    match saved_proj_bin {
        Some(v) => std::env::set_var("PROJ_BIN", v),
        None => std::env::remove_var("PROJ_BIN"),
    }
    match saved_path {
        Some(v) => std::env::set_var("PATH", v),
        None => std::env::remove_var("PATH"),
    }
    let _ = std::fs::remove_dir_all(&dir);

    assert_eq!(resolved, None);
}

/// Locate a `cs2cs` binary next to the resolved `proj` (via `PROJ_BIN`'s
/// directory) or on `PATH`. Returns `None` when none is available so the
/// live-differential test below skips cleanly on machines without PROJ.
fn resolve_cs2cs_bin() -> Option<std::path::PathBuf> {
    let exe = if cfg!(windows) { "cs2cs.exe" } else { "cs2cs" };
    if let Some(v) = std::env::var_os("PROJ_BIN") {
        let proj = std::path::PathBuf::from(v);
        if let Some(dir) = proj.parent() {
            let candidate = dir.join(exe);
            if candidate.is_file() {
                return Some(candidate);
            }
        }
    }
    let path_var = std::env::var_os("PATH")?;
    for dir in std::env::split_paths(&path_var) {
        let candidate = dir.join(exe);
        if candidate.is_file() {
            return Some(candidate);
        }
    }
    None
}

/// Drive system `cs2cs src +to dst` on a single `lon lat` (degrees) point and
/// parse the first two whitespace-separated output fields.
fn run_cs2cs(
    cs2cs: &std::path::Path,
    src: &str,
    dst: &str,
    lon_deg: f64,
    lat_deg: f64,
) -> Option<(f64, f64)> {
    use std::io::Write;
    use std::process::{Command, Stdio};

    let mut args: Vec<String> = vec!["-f".into(), "%.10f".into()];
    args.extend(src.split_whitespace().map(str::to_string));
    args.push("+to".into());
    args.extend(dst.split_whitespace().map(str::to_string));

    let mut child = Command::new(cs2cs)
        .args(&args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .ok()?;
    child
        .stdin
        .as_mut()?
        .write_all(format!("{lon_deg} {lat_deg}\n").as_bytes())
        .ok()?;
    let out = child.wait_with_output().ok()?;
    let text = String::from_utf8(out.stdout).ok()?;
    let mut it = text.split_whitespace();
    let x: f64 = it.next()?.parse().ok()?;
    let y: f64 = it.next()?.parse().ok()?;
    Some((x, y))
}

/// Live differential: the engine's `create()` forward for a `+towgs84`-bound
/// projection equals `cs2cs +proj=longlat +datum=WGS84 +to <target>` — i.e.
/// input geographic coordinates are treated as WGS 84 and pushed through the
/// datum shift into the local, projected target. A 3-parameter shift has no
/// rotation, so this is independent of the exact/linearised Helmert rotation
/// and must match PROJ to full precision. Guards on `cs2cs` availability so it
/// is CI-safe without PROJ installed. Protects the MOS datum-shift *direction*
/// fix against regression.
#[test]
fn towgs84_3param_direction_matches_system_cs2cs() {
    let Some(cs2cs) = resolve_cs2cs_bin() else {
        eprintln!("skipping: no cs2cs binary on PROJ_BIN dir or PATH");
        return;
    };
    let target = "+proj=utm +zone=32 +ellps=intl +towgs84=-87,-98,-121";
    let pj = create(target).expect("create towgs84 target");

    for (lon_deg, lat_deg) in [(9.0, 0.0), (12.0, 47.0), (2.0, 48.5)] {
        let fwd = trans(
            &pj,
            Direction::Fwd,
            Coord::new(lon_deg * DEG_TO_RAD, lat_deg * DEG_TO_RAD, 0.0, 0.0),
        )
        .expect("engine forward");
        let Some((rx, ry)) = run_cs2cs(
            &cs2cs,
            "+proj=longlat +datum=WGS84",
            target,
            lon_deg,
            lat_deg,
        ) else {
            eprintln!("skipping point ({lon_deg},{lat_deg}): cs2cs produced no parseable output");
            continue;
        };
        assert_close(fwd.v()[0], rx, 1e-3, "towgs84 3-param x vs cs2cs");
        assert_close(fwd.v()[1], ry, 1e-3, "towgs84 3-param y vs cs2cs");
    }
}