Skip to main content

oxigeo_proj/
lib.rs

1//! Pure Rust coordinate transformation and projection support for OxiGeo.
2//!
3//! This crate provides comprehensive coordinate reference system (CRS) and projection
4//! capabilities for the OxiGeo library. It includes support for:
5//!
6//! - EPSG code database with common coordinate reference systems
7//! - WKT (Well-Known Text) parsing
8//! - PROJ string support
9//! - Coordinate transformations between different CRS
10//! - Pure Rust implementation by default using OxiProj (COOLJAPAN cartographic engine)
11//! - proj4rs retained as optional fallback via the `proj4rs-compat` feature
12//!
13//! # Features
14//!
15//! - `std` (default): Enable standard library support and OxiProj EPSG/ProjJSON features
16//! - `proj-db`: Enable SQLite PROJ.db reader for ~7500 EPSG codes. Implies `std`:
17//!   the reader opens a file-system database (`std::path`, `std::env`) through
18//!   `oxisql-sqlite-compat`'s blocking API, which drives a tokio runtime.
19//! - `proj4rs-compat`: Add `From<proj4rs::errors::Error> for Error` for
20//!   backward compatibility. Does *not* imply `std` — the conversion needs only
21//!   `alloc`, so it is usable from `no_std` builds of this crate.
22//!
23//! # Examples
24//!
25// The following three examples use `Transformer` / `transform_epsg`, which are
26// only compiled with the `std` feature, so the doc block itself is gated: on a
27// `no_std` build these APIs do not exist and the examples must not be documented
28// (nor compiled as doctests).
29#![cfg_attr(
30    feature = "std",
31    doc = r##"## Transform coordinates from WGS84 to Web Mercator
32
33```
34use oxigeo_proj::{Crs, Coordinate, Transformer};
35
36# fn main() -> Result<(), Box<dyn std::error::Error>> {
37// Create CRS from EPSG codes
38let wgs84 = Crs::from_epsg(4326)?;
39let web_mercator = Crs::from_epsg(3857)?;
40
41// Create transformer
42let transformer = Transformer::new(wgs84, web_mercator)?;
43
44// Transform a coordinate (London: 0°, 51.5°N)
45let london = Coordinate::from_lon_lat(0.0, 51.5);
46let transformed = transformer.transform(&london)?;
47
48println!("Transformed: {}", transformed);
49# Ok(())
50# }
51```
52
53## Use convenience functions
54
55```
56use oxigeo_proj::{Coordinate, transform_epsg};
57
58# fn main() -> Result<(), Box<dyn std::error::Error>> {
59let coord = Coordinate::from_lon_lat(-122.4194, 37.7749); // San Francisco
60let transformed = transform_epsg(&coord, 4326, 3857)?;
61println!("Transformed: {}", transformed);
62# Ok(())
63# }
64```
65
66## Work with bounding boxes
67
68```
69use oxigeo_proj::{BoundingBox, Coordinate, Transformer, Crs};
70
71# fn main() -> Result<(), Box<dyn std::error::Error>> {
72let bbox = BoundingBox::new(-10.0, -10.0, 10.0, 10.0)?;
73
74let transformer = Transformer::from_epsg(4326, 3857)?;
75let transformed_bbox = transformer.transform_bbox(&bbox)?;
76
77println!("Original: {:?}", bbox);
78println!("Transformed: {:?}", transformed_bbox);
79# Ok(())
80# }
81```
82"##
83)]
84//!
85//! ## Use common CRS constants
86//!
87//! ```
88//! use oxigeo_proj::Crs;
89//!
90//! let wgs84 = Crs::wgs84();
91//! let web_mercator = Crs::web_mercator();
92//! let nad83 = Crs::nad83();
93//! let etrs89 = Crs::etrs89();
94//! ```
95//!
96//! # EPSG Database
97//!
98//! The crate includes an embedded database of ~140 common EPSG codes, including:
99//!
100//! - WGS84 (EPSG:4326)
101//! - Web Mercator (EPSG:3857)
102//! - All WGS84 UTM zones (EPSG:32601-32660 North, 32701-32760 South)
103//! - Common national datums (NAD83, ETRS89, GDA94, JGD2000, etc.)
104//! - Common projected systems (British National Grid, US National Atlas, etc.)
105//!
106//! # Pure Rust Implementation
107//!
108//! By default, this crate uses the pure Rust `OxiProj` library for coordinate transformations.
109//! This ensures:
110//!
111//! - No C/C++ dependencies
112//! - Cross-platform compatibility
113//! - Memory safety guarantees
114//! - Easy integration with Rust projects
115//!
116//! # Accuracy and Limitations
117//!
118//! The pure Rust implementation using OxiProj provides accurate transformations for most
119//! common use cases. However, it may have limitations compared to the full PROJ library:
120//!
121//! - Limited support for some exotic projections
122//! - No dynamic datum grid shift support
123//! - Simplified datum transformations
124//!
125//! For higher-fidelity CRS coverage, enable the `proj-db` feature: it adds the pure-Rust
126//! oxisql PROJ.db reader (~7500 EPSG codes) on top of the embedded registry.
127//!
128//! `proj-db` is *additive only*. The process-wide registry behind
129//! `lookup_epsg` / `Crs::from_epsg` is unchanged by it — population from a
130//! system PROJ.db is explicit, via
131//! `EpsgDatabase::populate_from_system_proj_db` on a database you own — and
132//! coordinate transforms resolve every CRS through this crate's own PROJ
133//! strings in all feature configurations, so enabling `proj-db` never changes
134//! a number the default build already produces.
135
136#![cfg_attr(not(feature = "std"), no_std)]
137#![warn(missing_docs)]
138#![deny(unsafe_code)]
139
140// `alloc` is linked unconditionally: it is always available, including when `std`
141// is present (`std` re-exports it), and `alloc::string::String` *is*
142// `std::string::String`. Linking it here lets every module write a plain
143// `use alloc::…;` instead of a `#[cfg(not(feature = "std"))]`-gated import that
144// silently rots whenever a module forgets one — which is exactly how the
145// `no_std` build previously broke.
146extern crate alloc;
147
148use alloc::format;
149use alloc::string::String;
150
151pub mod area_of_use;
152#[cfg(feature = "std")]
153pub mod cache;
154pub mod crs;
155#[cfg(feature = "std")]
156pub mod crs_identify;
157#[cfg(feature = "std")]
158pub mod crs_registry;
159pub mod datum_transform;
160pub mod epsg;
161pub mod error;
162#[cfg(feature = "std")]
163pub mod geocentric;
164pub mod geodesic;
165pub mod geoid;
166#[cfg(feature = "std")]
167pub mod geoid_formats;
168#[cfg(feature = "std")]
169pub mod grid_shift;
170// Internal: `libm`-backed stand-ins for the `f64` methods that live in `std`
171// and are therefore absent from `no_std` builds (see the module docs).
172mod math;
173pub mod operation_selection;
174#[cfg(feature = "std")]
175pub mod pipeline;
176#[cfg(feature = "std")]
177pub mod pipeline_grid;
178#[cfg(feature = "std")]
179pub mod proj_string;
180#[cfg(feature = "std")]
181pub mod projections;
182pub mod transform;
183pub mod ups_projection;
184pub mod wkt;
185#[cfg(feature = "std")]
186pub mod wkt_to_proj;
187
188// Re-export commonly used types
189pub use area_of_use::{AreaOfUse, area_of_use_for_epsg};
190#[cfg(feature = "std")]
191pub use cache::{TransformerCache, TransformerKey};
192pub use crs::{Crs, CrsSource};
193#[cfg(feature = "std")]
194pub use crs_identify::{
195    CrsFingerprint, fingerprint_from_proj, fingerprint_from_wkt, identify_epsg_from_proj,
196    identify_epsg_from_wkt,
197};
198pub use epsg::{CrsType, EpsgDefinition};
199#[cfg(feature = "proj-db")]
200pub use epsg::{ProjDb, ProjDbEntry, default_proj_db_paths, populate_from_proj_db};
201#[cfg(feature = "std")]
202pub use epsg::{available_epsg_codes, contains_epsg, lookup_epsg};
203pub use error::{Error, Result};
204#[cfg(feature = "std")]
205pub use geocentric::{
206    EcefCoordinate, EcefTransformer, GeocentricCrs, GeocentricEllipsoid, ecef_to_geographic,
207    ecef_to_geographic_iterative, geographic_to_ecef, geographic_to_geographic_via_ecef,
208};
209pub use geodesic::{
210    GeodesicError, GeodesicParams, VincentyDirectResult, VincentyResult, haversine_distance_m,
211    vincenty_direct, vincenty_inverse, wgs84_direct, wgs84_haversine_m, wgs84_inverse,
212};
213#[cfg(feature = "std")]
214pub use geoid::load_egm_grid;
215pub use geoid::{
216    GeoidGrid, GeoidModel, VerticalDatumKind, classify_vertical_datum, synthetic_grid,
217    synthetic_height_m,
218};
219#[cfg(feature = "std")]
220pub use geoid_formats::{
221    Egm96AsciiHeader, Egm2008BinaryHeader, load_geoid_auto, parse_egm96_ascii_file,
222    parse_egm96_ascii_header, parse_egm96_ascii_str, parse_egm2008_binary_25,
223    parse_egm2008_binary_25_file, parse_egm2008_binary_25_header,
224};
225#[cfg(feature = "std")]
226pub use grid_shift::{
227    DHDN_TO_ETRS89, Helmert7Params, NAD27_TO_NAD83, NTF_TO_RGF93, NtV2Grid, OSGB36_TO_ETRS89,
228    dhdn_etrs89_helmert, helmert_3d, helmert_7param, nad27_nad83_poly, ostn15_approx, rgf93_approx,
229};
230pub use operation_selection::{
231    CandidateOperation, OperationRanking, area_coverage_fraction, operation_score, rank_operations,
232    select_best_operation,
233};
234#[cfg(feature = "std")]
235pub use pipeline::{
236    EllipsoidParams, GridRegistry, HelmertConvention, HelmertParams, HelmertRateParams, ParsedStep,
237    Pipeline, PipelineStep, ShiftDirection, StepKind, Unit, parse_pipeline,
238};
239#[cfg(feature = "std")]
240pub use transform::{
241    AreaOfUseCheck, AreaOfUseWarning, AzimuthalEquidistant, CassineSoldner, EckertIV, EckertVI,
242    EquidistantConic, GaussKruger, Gnomonic, LambertAzimuthalEqualArea, LambertConformalConic,
243    Mollweide, Robinson, Sinusoidal, Transformer, TransverseMercator, VerticalDatumWarning,
244    transform_coordinate, transform_epsg,
245};
246// Unambiguous aliases for the two Transverse Mercator models, re-exported at the crate
247// root next to the types they alias. `TransverseMercator` is sphere-based and must not
248// be used for UTM or national grids; `GaussKruger` is the ellipsoidal one that must.
249#[cfg(feature = "std")]
250pub use transform::cylindrical::{EllipsoidalTransverseMercator, SphericalTransverseMercator};
251pub use transform::{BoundingBox, Coordinate, Coordinate3D};
252pub use ups_projection::{
253    PolarStereographicParams, UpsCoordinate, UpsHemisphere, polar_stereo_w,
254    polar_stereographic_forward, polar_stereographic_inverse, ups_from_geographic,
255    ups_to_geographic, ups_zone_letter,
256};
257pub use wkt::{WktNode, WktParser, parse_wkt};
258
259/// Library version
260pub const VERSION: &str = env!("CARGO_PKG_VERSION");
261
262/// Library name
263pub const NAME: &str = env!("CARGO_PKG_NAME");
264
265/// Returns library information.
266pub fn info() -> String {
267    format!("{} v{}", NAME, VERSION)
268}
269
270// These unit tests exercise std-only API (`Transformer`, `Crs::compound`,
271// `lookup_epsg`, …), so they are gated with the `std` feature.
272#[cfg(all(test, feature = "std"))]
273#[allow(clippy::expect_used)]
274mod tests {
275    use super::*;
276
277    #[test]
278    fn test_version_info() {
279        let info = info();
280        assert!(info.contains("oxigeo-proj"));
281        assert!(info.contains(env!("CARGO_PKG_VERSION")));
282    }
283
284    #[test]
285    fn test_basic_workflow() {
286        // Create CRS
287        let wgs84 = Crs::wgs84();
288        let web_mercator = Crs::web_mercator();
289
290        // Create transformer
291        let transformer = Transformer::new(wgs84, web_mercator);
292        assert!(transformer.is_ok());
293
294        // Transform coordinate
295        let coord = Coordinate::from_lon_lat(0.0, 0.0);
296        let result = transformer.expect("should create").transform(&coord);
297        assert!(result.is_ok());
298    }
299
300    #[test]
301    fn test_epsg_lookup() {
302        let wgs84 = lookup_epsg(4326);
303        assert!(wgs84.is_ok());
304
305        assert!(contains_epsg(4326));
306        assert!(contains_epsg(3857));
307        assert!(!contains_epsg(99999));
308
309        let codes = available_epsg_codes();
310        assert!(!codes.is_empty());
311    }
312
313    #[test]
314    fn test_convenience_functions() {
315        let coord = Coordinate::from_lon_lat(0.0, 0.0);
316        let result = transform_epsg(&coord, 4326, 4326);
317        assert!(result.is_ok());
318    }
319
320    #[test]
321    fn test_bounding_box_workflow() {
322        let bbox = BoundingBox::new(0.0, 0.0, 10.0, 10.0);
323        assert!(bbox.is_ok());
324
325        let bbox = bbox.expect("valid bbox");
326        let transformer = Transformer::from_epsg(4326, 4326);
327        assert!(transformer.is_ok());
328
329        let result = transformer.expect("should create").transform_bbox(&bbox);
330        assert!(result.is_ok());
331    }
332
333    #[test]
334    fn test_wkt_parsing() {
335        let wkt = r#"GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]]]"#;
336        let result = parse_wkt(wkt);
337        assert!(result.is_ok());
338
339        let node = result.expect("should parse");
340        assert_eq!(node.node_type, "GEOGCS");
341    }
342
343    #[test]
344    fn test_crs_creation_methods() {
345        // From EPSG
346        let crs1 = Crs::from_epsg(4326);
347        assert!(crs1.is_ok());
348
349        // From PROJ string
350        let crs2 = Crs::from_proj("+proj=longlat +datum=WGS84 +no_defs");
351        assert!(crs2.is_ok());
352
353        // From WKT
354        let wkt = r#"GEOGCS["WGS 84"]"#;
355        let crs3 = Crs::from_wkt(wkt);
356        assert!(crs3.is_ok());
357
358        // Custom CRS
359        let crs4 = Crs::custom("My CRS", "+proj=longlat +datum=WGS84 +no_defs");
360        assert!(matches!(crs4.source(), CrsSource::Custom { .. }));
361    }
362
363    #[test]
364    fn test_coordinate_types() {
365        // 2D coordinate
366        let coord_2d = Coordinate::new(10.0, 20.0);
367        assert_eq!(coord_2d.x, 10.0);
368        assert_eq!(coord_2d.y, 20.0);
369
370        // 3D coordinate
371        let coord_3d = Coordinate3D::new(10.0, 20.0, 30.0);
372        assert_eq!(coord_3d.x, 10.0);
373        assert_eq!(coord_3d.y, 20.0);
374        assert_eq!(coord_3d.z, 30.0);
375
376        // Conversion
377        let coord_2d_from_3d = coord_3d.to_2d();
378        assert_eq!(coord_2d_from_3d.x, 10.0);
379        assert_eq!(coord_2d_from_3d.y, 20.0);
380    }
381}
382
383// OxiProj is an optional dependency activated by the `std` feature, so this
384// linkage check only applies to `std` builds.
385#[cfg(all(test, feature = "std"))]
386mod oxiproj_linkage_tests {
387    #[test]
388    fn test_oxiproj_linkage() {
389        // Verify OxiProj is reachable from this crate
390        let info = oxiproj::proj_info();
391        assert!(!info.version.is_empty());
392    }
393}