capsule_core/domain/gps_datum.rs
1//! The coordinate datum a GPS fix is stored in, plus the input-edge BD-09 fold
2//! (SSoT: [Metadata — Geolocation] and [Metadata — Closed Enum Value Sets]).
3//!
4//! GPS is stored **verbatim in the datum the source supplied** — never converted at rest
5//! (GCJ-02 → WGS-84 has no exact inverse, so converting on input would destroy the user's
6//! ground truth). The value set is closed: adding a value requires a new, later-dated
7//! `protocol_version`.
8//!
9//! **BD-09 is never a storable datum.** Baidu's BD-09 (a second obfuscation layer over
10//! GCJ-02) exists only at the input edge: it is folded to GCJ-02 on entry and stored as
11//! `datum = gcj02`. Only the **forward** GCJ-02 → BD-09 direction is closed-form, so the
12//! fold is the **error-bounded iterative inverse** of that forward transform, held to a
13//! sub-metre bound (decision 2026-07-12, amending the earlier "closed-form and exact"
14//! claim; implemented in-house per the 2026-08-21 gates decision — no crate is adopted).
15//! See [`fold_bd09_to_gcj02`].
16//!
17//! [Metadata — Geolocation]: https://docs/design/metadata/#geolocation
18//! [Metadata — Closed Enum Value Sets]: https://docs/design/metadata/#closed-enum-value-sets
19
20use serde::{Deserialize, Serialize};
21use tracing::{trace, warn};
22
23/// The coordinate datum a stored GPS fix is expressed in (closed enum per
24/// `protocol_version`; the code mirror of the [Closed Enum Value Sets] catalog).
25///
26/// [`Wgs84`](GpsDatum::Wgs84) is the near-universal camera format and the **wire-absent
27/// default** — a `gps` value with no `datum` key decodes as `Wgs84`, and a `Wgs84` fix
28/// omits the key on encode, so every pre-`datum` sidecar and known-answer vector stays
29/// byte-identical.
30///
31/// [Closed Enum Value Sets]: https://docs/design/metadata/#closed-enum-value-sets
32#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
33pub enum GpsDatum {
34 /// The near-universal camera datum, and the wire-absent default.
35 #[default]
36 #[serde(rename = "wgs84")]
37 Wgs84,
38 /// China's legally mandated obfuscated datum — user-entered coordinates from Chinese
39 /// maps arrive in it. Also the target datum a BD-09 input is folded to on entry.
40 #[serde(rename = "gcj02")]
41 Gcj02,
42}
43
44impl GpsDatum {
45 /// Whether this is the wire-absent default ([`Wgs84`](GpsDatum::Wgs84)). Used as the
46 /// sidecar `skip_serializing_if` predicate so a `Wgs84` fix omits the `datum` key.
47 #[must_use]
48 pub fn is_wgs84(&self) -> bool {
49 matches!(self, GpsDatum::Wgs84)
50 }
51}
52
53/// A raw BD-09 coordinate presented at the **input edge**. BD-09 is never a storable
54/// [`GpsDatum`] (metadata doc, Closed Enum Value Sets): it must be folded to GCJ-02 by
55/// [`fold_bd09_to_gcj02`] before it can enter a sidecar, and is stored as
56/// [`GpsDatum::Gcj02`].
57#[derive(Debug, Clone, Copy, PartialEq)]
58pub struct Bd09Coord {
59 /// Latitude in the BD-09 datum.
60 pub lat: f64,
61 /// Longitude in the BD-09 datum.
62 pub lon: f64,
63}
64
65/// The documented accuracy bound on the BD-09 → GCJ-02 fold, in metres: a successful
66/// [`fold_bd09_to_gcj02`] is **sub-metre**, far below consumer-GPS noise, which is why the
67/// bounded inverse is accepted rather than refusing BD-09 input at the edge.
68///
69/// This is the *contract* ceiling. The tolerance actually enforced
70/// ([`BD09_FOLD_TOLERANCE_DEGREES`]) is roughly four orders of magnitude tighter, so the
71/// bound holds with enormous margin.
72pub const BD09_FOLD_BOUND_METRES: f64 = 1.0;
73
74/// The residual the refinement must reach, in degrees, before a fold is accepted.
75///
76/// `1e-9°` is ≈ 0.11 mm of latitude — five orders of magnitude above the `f64` resolution
77/// floor at geographic magnitudes, so it is always reachable, and four orders below
78/// [`BD09_FOLD_BOUND_METRES`].
79pub const BD09_FOLD_TOLERANCE_DEGREES: f64 = 1e-9;
80
81/// Iteration cap for the refinement. The iteration contracts by ≈ 0.02 per step at
82/// geographic magnitudes (≈ 1.7 decimal digits gained per step, from a ≈ 2e-5° seed error),
83/// so it reaches [`BD09_FOLD_TOLERANCE_DEGREES`] in single-digit steps; the cap exists only
84/// so a pathological input terminates instead of spinning.
85const BD09_FOLD_MAX_REFINEMENTS: usize = 24;
86
87/// Metres per degree of latitude on the WGS-84 mean meridian — used only to express the
88/// fold's residual as a distance for the [`BD09_FOLD_BOUND_METRES`] contract.
89const METRES_PER_DEGREE_LATITUDE: f64 = 111_320.0;
90
91/// Baidu's magic constant: π scaled by 3000/180.
92const BD09_X_PI: f64 = std::f64::consts::PI * 3000.0 / 180.0;
93/// The BD-09 latitude offset applied by the forward transform.
94const BD09_LAT_OFFSET: f64 = 0.006;
95/// The BD-09 longitude offset applied by the forward transform.
96const BD09_LON_OFFSET: f64 = 0.0065;
97/// Amplitude of the forward transform's radial wobble.
98const BD09_RADIAL_AMPLITUDE: f64 = 0.000_02;
99/// Amplitude of the forward transform's angular wobble.
100const BD09_ANGULAR_AMPLITUDE: f64 = 0.000_003;
101
102/// Error folding a BD-09 input coordinate to GCJ-02 at the input edge.
103///
104/// BD-09 is not a storable [`GpsDatum`], so a fold that cannot be certified is a hard
105/// refusal: the coordinate can neither be stored verbatim nor approximated past the bound.
106#[derive(Debug, Clone, Copy, thiserror::Error, PartialEq)]
107pub enum DatumFoldError {
108 /// The input coordinate was not a finite number, so no fold is defined for it.
109 #[error("BD-09 input coordinate is not finite (lat={lat}, lon={lon})")]
110 NonFinite {
111 /// The offending latitude.
112 lat: f64,
113 /// The offending longitude.
114 lon: f64,
115 },
116 /// The refinement did not reach [`BD09_FOLD_TOLERANCE_DEGREES`] within the iteration
117 /// cap, so the result cannot be certified inside [`BD09_FOLD_BOUND_METRES`]. The fold
118 /// refuses rather than returning an uncertified approximation.
119 #[error(
120 "BD-09 → GCJ-02 refinement did not converge: residual {residual_degrees}° exceeds \
121 the fold tolerance after {BD09_FOLD_MAX_REFINEMENTS} steps"
122 )]
123 DidNotConverge {
124 /// The residual left when the iteration cap was hit, in degrees.
125 residual_degrees: f64,
126 },
127}
128
129/// The **closed-form** GCJ-02 → BD-09 transform: Baidu's published forward direction, and
130/// the only direction of this pair that has a closed form.
131///
132/// [`fold_bd09_to_gcj02`] inverts *this* function numerically.
133fn gcj02_to_bd09(lat: f64, lon: f64) -> (f64, f64) {
134 let z = lon.hypot(lat) + BD09_RADIAL_AMPLITUDE * (lat * BD09_X_PI).sin();
135 let theta = lat.atan2(lon) + BD09_ANGULAR_AMPLITUDE * (lon * BD09_X_PI).cos();
136 (
137 z * theta.sin() + BD09_LAT_OFFSET,
138 z * theta.cos() + BD09_LON_OFFSET,
139 )
140}
141
142/// Fold a BD-09 input coordinate to GCJ-02 at the input edge, returning the `(lat, lon)`
143/// to store under [`GpsDatum::Gcj02`].
144///
145/// Only `gcj02_to_bd09` — the *forward* direction — is closed-form, so this is the
146/// **error-bounded iterative inverse** of it: seed with the offset-removed coordinate, then
147/// repeatedly push the estimate forward, measure the residual against the input, and
148/// correct by it. The forward map is the identity plus a small perturbation, so the
149/// iteration contracts sharply and reaches [`BD09_FOLD_TOLERANCE_DEGREES`] in a handful of
150/// steps.
151///
152/// The result is **certified before it is returned**: the accepted estimate is pushed
153/// forward one last time and must land on the input within tolerance, so a successful fold
154/// is always inside [`BD09_FOLD_BOUND_METRES`]. It is **deterministic** — pure `f64`
155/// arithmetic on a fixed schedule, so the same input yields bit-identical output on every
156/// run.
157///
158/// BD-09 **MUST NOT** be stored verbatim — it is not a storable [`GpsDatum`]. Callers store
159/// the result as `datum = gcj02`.
160pub fn fold_bd09_to_gcj02(input: Bd09Coord) -> Result<(f64, f64), DatumFoldError> {
161 if !input.lat.is_finite() || !input.lon.is_finite() {
162 warn!(
163 lat = input.lat,
164 lon = input.lon,
165 "refusing BD-09 fold: input coordinate is not finite"
166 );
167 return Err(DatumFoldError::NonFinite {
168 lat: input.lat,
169 lon: input.lon,
170 });
171 }
172
173 // Seed: strip the forward transform's constant offsets. That leaves only its sinusoidal
174 // wobble as error (~2e-5°), which the refinement below drives down to the tolerance.
175 let mut lat = input.lat - BD09_LAT_OFFSET;
176 let mut lon = input.lon - BD09_LON_OFFSET;
177
178 for step in 0..BD09_FOLD_MAX_REFINEMENTS {
179 let (probe_lat, probe_lon) = gcj02_to_bd09(lat, lon);
180 let delta_lat = input.lat - probe_lat;
181 let delta_lon = input.lon - probe_lon;
182 lat += delta_lat;
183 lon += delta_lon;
184 let residual = delta_lat.abs().max(delta_lon.abs());
185 trace!(
186 step,
187 residual_degrees = residual,
188 "BD-09 fold refinement step"
189 );
190 if residual <= BD09_FOLD_TOLERANCE_DEGREES {
191 break;
192 }
193 }
194
195 // Certify the value we are about to return, not the one before the last correction.
196 let (probe_lat, probe_lon) = gcj02_to_bd09(lat, lon);
197 let residual_degrees = (input.lat - probe_lat)
198 .abs()
199 .max((input.lon - probe_lon).abs());
200 if residual_degrees.is_nan() || residual_degrees > BD09_FOLD_TOLERANCE_DEGREES {
201 warn!(
202 lat = input.lat,
203 lon = input.lon,
204 residual_degrees,
205 "refusing BD-09 fold: refinement did not reach the documented bound"
206 );
207 return Err(DatumFoldError::DidNotConverge { residual_degrees });
208 }
209
210 trace!(
211 bd09_lat = input.lat,
212 bd09_lon = input.lon,
213 gcj02_lat = lat,
214 gcj02_lon = lon,
215 residual_metres = residual_degrees * METRES_PER_DEGREE_LATITUDE,
216 "folded BD-09 input to GCJ-02"
217 );
218 Ok((lat, lon))
219}
220
221#[cfg(test)]
222mod tests;