Skip to main content

qualia_core_db/domains/geospatial/
vector_scene.rs

1//! Bounded OSM vector geometry to local render meshes.
2//!
3//! This is a per-render-tile compiler, not a national GIS store. It projects
4//! source WGS84 coordinates into a local ENU frame, preserves source identity
5//! beside the resulting mesh, and lets callers drape geometry against a
6//! separately sourced elevation field. A larger Australian place is compiled
7//! as many independently streamed tiles.
8
9use crate::domains::geospatial::adapters::osm_adapter::OsmVectorFeature;
10use crate::render::assets::Mesh;
11
12mod geometry;
13
14const MAX_COORDINATES: usize = 250_000;
15const MAX_TILE_RADIUS_M: f64 = 250_000.0;
16
17/// Local WGS84 tangent frame and cold-build limits for one render tile.
18#[derive(Debug, Clone, Copy, PartialEq)]
19pub struct VectorSceneFrame {
20    pub origin_lat: f64,
21    pub origin_lon: f64,
22    pub origin_alt_m: f64,
23    /// Maximum horizontal distance from the origin for any source vertex.
24    pub max_radius_m: f64,
25    /// Optional `[min_east, min_north, max_east, max_north]` clip rectangle
26    /// in metres relative to this origin. Adjacent tiles should share exact
27    /// edge coordinates so independently compiled meshes meet without gaps.
28    pub tile_bounds_enu: Option<[f64; 4]>,
29    /// Maximum input vertices accepted for one feature.
30    pub max_coordinates: usize,
31}
32
33impl VectorSceneFrame {
34    /// Creates `VectorSceneFrame` with the given state.
35    pub fn new(origin_lat: f64, origin_lon: f64, origin_alt_m: f64) -> Self {
36        Self {
37            origin_lat,
38            origin_lon,
39            origin_alt_m,
40            max_radius_m: 50_000.0,
41            tile_bounds_enu: None,
42            max_coordinates: 50_000,
43        }
44    }
45
46    /// Clip emitted geometry to a tile rectangle in the frame's local ENU plane.
47    pub fn with_tile_bounds(mut self, bounds_enu: [f64; 4]) -> Self {
48        self.tile_bounds_enu = Some(bounds_enu);
49        self
50    }
51
52    fn validate(self) -> Result<(), String> {
53        if !self.origin_lat.is_finite()
54            || !(-90.0..=90.0).contains(&self.origin_lat)
55            || !self.origin_lon.is_finite()
56            || !(-180.0..=180.0).contains(&self.origin_lon)
57            || !self.origin_alt_m.is_finite()
58        {
59            return Err("vector scene origin is not a finite WGS84 location".into());
60        }
61        if !self.max_radius_m.is_finite()
62            || self.max_radius_m <= 0.0
63            || self.max_radius_m > MAX_TILE_RADIUS_M
64        {
65            return Err(format!(
66                "vector scene radius must be greater than zero and at most {MAX_TILE_RADIUS_M} m"
67            ));
68        }
69        if let Some([min_east, min_north, max_east, max_north]) = self.tile_bounds_enu {
70            if ![min_east, min_north, max_east, max_north]
71                .iter()
72                .all(|value| value.is_finite())
73                || min_east >= max_east
74                || min_north >= max_north
75            {
76                return Err("vector tile bounds must be finite and have positive area".into());
77            }
78            if [
79                (min_east, min_north),
80                (min_east, max_north),
81                (max_east, min_north),
82                (max_east, max_north),
83            ]
84            .iter()
85            .any(|(east, north)| east.hypot(*north) > self.max_radius_m)
86            {
87                return Err("vector tile bounds exceed the configured local radius".into());
88            }
89        }
90        if self.max_coordinates == 0 || self.max_coordinates > MAX_COORDINATES {
91            return Err(format!(
92                "vector scene coordinate budget must be from 1 to {MAX_COORDINATES}"
93            ));
94        }
95        Ok(())
96    }
97}
98
99/// Game-authored presentation intent for one OSM geometry.
100///
101/// OSM facts and tags remain source data; these dimensions and offsets are
102/// renderer policy and must not be written back as geographic facts.
103#[derive(Debug, Clone, Copy, PartialEq)]
104pub enum OsmVectorStyle {
105    /// A flat circular marker centred on a mapped point.
106    Marker {
107        radius_m: f32,
108        vertical_offset_m: f32,
109    },
110    /// A camera-facing-free ground ribbon for roads, streams, paths or borders.
111    Line {
112        width_m: f32,
113        vertical_offset_m: f32,
114    },
115    /// A simple polygon fill. Polygons with interior rings are rejected until
116    /// a hole-preserving triangulator is selected by the caller's profile.
117    Area { vertical_offset_m: f32 },
118}
119
120impl OsmVectorStyle {
121    fn validate(self) -> Result<(), String> {
122        match self {
123            Self::Marker {
124                radius_m,
125                vertical_offset_m,
126            } if !radius_m.is_finite()
127                || radius_m <= 0.0
128                || radius_m > 1_000.0
129                || !vertical_offset_m.is_finite() =>
130            {
131                Err("marker radius/offset is outside the supported finite range".into())
132            }
133            Self::Line {
134                width_m,
135                vertical_offset_m,
136            } if !width_m.is_finite()
137                || width_m <= 0.0
138                || width_m > 2_000.0
139                || !vertical_offset_m.is_finite() =>
140            {
141                Err("line width/offset is outside the supported finite range".into())
142            }
143            Self::Area { vertical_offset_m } if !vertical_offset_m.is_finite() => {
144                Err("area vertical offset must be finite".into())
145            }
146            _ => Ok(()),
147        }
148    }
149
150    fn vertical_offset_m(self) -> f32 {
151        match self {
152            Self::Marker {
153                vertical_offset_m, ..
154            }
155            | Self::Line {
156                vertical_offset_m, ..
157            }
158            | Self::Area { vertical_offset_m } => vertical_offset_m,
159        }
160    }
161}
162
163/// A per-feature render mesh with its OSM source facts retained alongside it.
164#[derive(Debug, Clone, PartialEq)]
165pub struct OsmRenderedFeature {
166    pub source_iri: String,
167    pub source_version: Option<u64>,
168    pub source_timestamp: Option<String>,
169    pub tags: std::collections::BTreeMap<String, String>,
170    pub style: OsmVectorStyle,
171    pub mesh: Mesh,
172}
173
174/// Compile one validated feature in a local ENU frame, using its WGS84
175/// elevations as the fallback surface. Geometry with parser diagnostics is
176/// refused so incomplete ways or relations cannot silently become art.
177pub fn compile_osm_feature_mesh(
178    feature: &OsmVectorFeature,
179    frame: VectorSceneFrame,
180    style: OsmVectorStyle,
181) -> Result<OsmRenderedFeature, String> {
182    compile_osm_feature_mesh_draped(feature, frame, style, None)
183}
184
185/// Compile one feature and sample a caller-owned local terrain surface at
186/// every emitted vertex. The sampler returns metres above `frame.origin_alt_m`;
187/// returning `None` rejects the feature instead of leaving an undraped gap.
188///
189/// The sampler is borrowed only during cold mesh construction. Terrain tile
190/// ownership, CRS, datum, caching and source provenance remain with the caller.
191pub fn compile_osm_feature_mesh_draped(
192    feature: &OsmVectorFeature,
193    frame: VectorSceneFrame,
194    style: OsmVectorStyle,
195    ground_height: Option<&dyn Fn(f64, f64) -> Option<f32>>,
196) -> Result<OsmRenderedFeature, String> {
197    frame.validate()?;
198    style.validate()?;
199    if let Some(issue) = feature.issues.first() {
200        return Err(format!(
201            "OSM feature {}/{} has geometry diagnostics: {issue}",
202            feature.element_type, feature.id
203        ));
204    }
205    let geometry = feature.geometry.as_ref().ok_or_else(|| {
206        format!(
207            "OSM feature {}/{} has no geometry",
208            feature.element_type, feature.id
209        )
210    })?;
211    let mesh = geometry::compile(geometry, frame, style, ground_height).map_err(|error| {
212        format!(
213            "OSM feature {}/{}: {error}",
214            feature.element_type, feature.id
215        )
216    })?;
217    Ok(OsmRenderedFeature {
218        source_iri: feature.source_iri(),
219        source_version: feature.version,
220        source_timestamp: feature.timestamp.clone(),
221        tags: feature.tags.clone(),
222        style,
223        mesh,
224    })
225}