Skip to main content

vibe/capability_schema/
geo_gis_io_entries.rs

1//! GIS vector, raster, LiDAR, and container capability schemas (GEO-S4 / R4-V).
2//!
3//! Provides machine schema definitions for all 20 `GisIo.*` host capability invocations
4//! covering LiDAR point clouds (LAS/LAZ/COPC, CSF classification, m64 Mode 0x00, DTM/DSM/CHM),
5//! vector spatial formats (GeoPackage, FlatGeobuf, FileGDB, Shapefile, GeoParquet, GeoJSON,
6//! KML/GPX/GML, DXF CAD, TopoJSON/OSM), and tiled vector publishing (PMTiles, MVT).
7
8use super::{EffectClass, HonestyLabel, SchemaArg, SchemaEntry};
9
10/// Effect classification for VibeScript 0.2 capability operations.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12pub enum Effect {
13    Pure, Compute, Cold, Async, External,
14}
15
16impl Effect {
17    pub const fn as_str(&self) -> &'static str {
18        match self {
19            Self::Pure => "pure", Self::Compute => "compute", Self::Cold => "cold",
20            Self::Async => "async", Self::External => "external",
21        }
22    }
23}
24
25/// Parameter type for GIS I/O and LiDAR operations.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
27pub enum ParamType {
28    F64, I64, U64, Bool, Str, Record, List, FieldRef, GeometryRef,
29}
30
31impl ParamType {
32    pub const fn as_str(&self) -> &'static str {
33        match self {
34            Self::F64 => "f64", Self::I64 => "i64", Self::U64 => "u64",
35            Self::Bool => "bool", Self::Str => "string", Self::Record => "Record",
36            Self::List => "List", Self::FieldRef => "FieldRef", Self::GeometryRef => "GeometryRef",
37        }
38    }
39}
40
41/// Parameter schema descriptor.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub struct ParamSchema {
44    pub name: &'static str,
45    pub param_type: ParamType,
46    pub required: bool,
47    pub description: &'static str,
48}
49
50const fn p(name: &'static str, ty: ParamType, req: bool, desc: &'static str) -> ParamSchema {
51    ParamSchema { name, param_type: ty, required: req, description: desc }
52}
53
54/// Operation schema descriptor for GIS I/O and LiDAR operations.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub struct OperationSchema {
57    pub invoke_id: &'static str,
58    pub effect: Effect,
59    pub params: &'static [ParamSchema],
60    pub returns: &'static str,
61    pub description: &'static str,
62}
63
64const fn op(id: &'static str, eff: Effect, ret: &'static str, desc: &'static str, params: &'static [ParamSchema]) -> OperationSchema {
65    OperationSchema { invoke_id: id, effect: eff, params, returns: ret, description: desc }
66}
67
68/// Canonical ASPRS LAS 1.4 point classification standard codes (0..=18).
69pub const ASPRS_CLASSIFICATION_NAMES: [&str; 19] = [
70    "CreatedNeverClassified", "Unclassified", "Ground", "LowVegetation",
71    "MediumVegetation", "HighVegetation", "Building", "LowPointNoise",
72    "ModelKeyPoint", "Water", "Rail", "RoadSurface", "Reserved12",
73    "WireGuard", "WireConductor", "TransmissionTower", "WireConnector",
74    "BridgeDeck", "HighNoise",
75];
76
77/// Validator and container helper for `LidarPointComplex` (.m64 Mode 0x00).
78#[derive(Debug, Clone, PartialEq)]
79pub struct LidarPointComplexDecl {
80    pub name: String,
81    pub m64_submagic: u8,
82    pub crs: String,
83    pub byte_budget: u64,
84    pub classification_codes: Vec<u8>,
85    pub point_count: u64,
86}
87
88impl LidarPointComplexDecl {
89    pub const EXPECTED_SUBMAGIC: u8 = 0x00;
90    pub const MAX_ASPRS_CODE: u8 = 18;
91
92    pub fn new(
93        name: impl Into<String>, m64_submagic: u8, crs: impl Into<String>,
94        byte_budget: u64, classification_codes: Vec<u8>, point_count: u64,
95    ) -> Self {
96        Self {
97            name: name.into(), m64_submagic, crs: crs.into(),
98            byte_budget, classification_codes, point_count,
99        }
100    }
101
102    pub fn is_valid_asprs_code(code: u8) -> bool {
103        code <= Self::MAX_ASPRS_CODE
104    }
105
106    pub fn asprs_code_name(code: u8) -> Option<&'static str> {
107        ASPRS_CLASSIFICATION_NAMES.get(code as usize).copied()
108    }
109
110    pub fn validate(&self) -> Result<(), &'static str> {
111        if self.m64_submagic != Self::EXPECTED_SUBMAGIC {
112            return Err("m64_submagic must equal 0x00 for LidarPointComplex");
113        }
114        if self.byte_budget == 0 {
115            return Err("byte_budget must be strictly positive");
116        }
117        if self.crs.is_empty() {
118            return Err("crs coordinate reference system must not be empty");
119        }
120        for &code in &self.classification_codes {
121            if !Self::is_valid_asprs_code(code) {
122                return Err("classification code exceeds ASPRS 1.4 range 0..=18");
123            }
124        }
125        Ok(())
126    }
127}
128
129/// Canonical sequence of all 20 GIS I/O and LiDAR capability invoke IDs.
130pub const GEO_GIS_IO_INVOKE_IDS: &[&str] = &[
131    "GisIo.read_lidar_copc", "GisIo.classify_lidar_csf", "GisIo.pack_lidar_m64",
132    "GisIo.rasterize_dtm_dsm_chm", "GisIo.read_geopackage", "GisIo.write_geopackage",
133    "GisIo.read_flatgeobuf", "GisIo.write_flatgeobuf", "GisIo.read_filegdb",
134    "GisIo.read_shapefile", "GisIo.write_shapefile", "GisIo.read_geoparquet",
135    "GisIo.write_geoparquet", "GisIo.read_geojson", "GisIo.write_geojson",
136    "GisIo.read_kml_gpx_gml", "GisIo.read_dxf_cad", "GisIo.read_topojson_osm",
137    "GisIo.read_pmtiles_mvt", "GisIo.encode_mvt_tile",
138];
139
140/// Canonical sequence of all 20 GIS I/O and LiDAR operations.
141pub const GEO_GIS_IO_OPERATIONS: &[OperationSchema] = &[
142    op("GisIo.read_lidar_copc", Effect::Cold, "Record", "Parse LAS 1.2-1.4 / COPC octree hierarchy and point cloud.", &[
143        p("path", ParamType::Str, true, "File path or URL to .copc.laz / .laz / .las"),
144        p("bounds", ParamType::Record, false, "Spatial bounding box filter record"),
145        p("byte_budget", ParamType::U64, false, "Maximum byte budget for point allocation"),
146        p("classification_filter", ParamType::List, false, "ASPRS classification code filter list"),
147    ]),
148    op("GisIo.classify_lidar_csf", Effect::Cold, "Record", "Cloth Simulation Filter ground/canopy separation and HAG computation.", &[
149        p("points", ParamType::Record, true, "Input LiDAR point cloud record"),
150        p("cloth_resolution_m", ParamType::F64, true, "Cloth grid resolution in meters"),
151        p("rigidness", ParamType::U64, true, "Cloth rigidity parameter (1=flat, 2=relief, 3=steep)"),
152        p("time_step", ParamType::F64, true, "Simulation time step"),
153        p("class_threshold_m", ParamType::F64, true, "Ground/canopy height threshold in meters"),
154    ]),
155    op("GisIo.pack_lidar_m64", Effect::Compute, "Record", "Pack LiDAR points into 64B .m64 Mode 0x00 records with CRC-32C.", &[
156        p("points", ParamType::Record, true, "Classified LiDAR point cloud record"),
157        p("crs", ParamType::Str, true, "Coordinate reference system (e.g. EPSG:7855)"),
158        p("quantization_step_m", ParamType::F64, true, "Coordinate quantization precision step in meters"),
159    ]),
160    op("GisIo.rasterize_dtm_dsm_chm", Effect::Cold, "Record", "Rasterize bare-earth DTM, first-return DSM, and Canopy Height Model CHM.", &[
161        p("points", ParamType::Record, true, "Classified LiDAR point cloud record"),
162        p("resolution_m", ParamType::F64, true, "Raster grid resolution in meters"),
163        p("interpolation", ParamType::Str, true, "Interpolation method (idw, tin_linear, nearest)"),
164    ]),
165    op("GisIo.read_geopackage", Effect::Cold, "Record", "Read vector layer features and metadata from OGC GeoPackage.", &[
166        p("path", ParamType::Str, true, "File path to .gpkg database"),
167        p("layer", ParamType::Str, false, "Vector layer name"),
168        p("bbox", ParamType::Record, false, "Spatial bounding box filter record"),
169    ]),
170    op("GisIo.write_geopackage", Effect::External, "Record", "Write vector features and geometries into OGC GeoPackage layer.", &[
171        p("path", ParamType::Str, true, "File path to target .gpkg database"),
172        p("layer", ParamType::Str, true, "Target layer name"),
173        p("features", ParamType::Record, true, "Vector feature collection record"),
174        p("crs", ParamType::Str, true, "Layer coordinate reference system"),
175    ]),
176    op("GisIo.read_flatgeobuf", Effect::Cold, "Record", "Zero-copy Hilbert R-tree spatial bbox filter reader for FlatGeobuf.", &[
177        p("path", ParamType::Str, true, "File path or URL to .fgb dataset"),
178        p("bbox", ParamType::Record, false, "Spatial bounding box filter [min_x, min_y, max_x, max_y]"),
179        p("byte_budget", ParamType::U64, false, "Maximum byte budget"),
180    ]),
181    op("GisIo.write_flatgeobuf", Effect::External, "Record", "Write vector features to FlatGeobuf with indexed Hilbert R-tree.", &[
182        p("path", ParamType::Str, true, "Output file path for .fgb"),
183        p("features", ParamType::Record, true, "Vector feature collection record"),
184        p("crs", ParamType::Str, true, "Coordinate reference system"),
185    ]),
186    op("GisIo.read_filegdb", Effect::Cold, "Record", "Read Esri File Geodatabase .gdbtable and .gdbtablx binary tables.", &[
187        p("path", ParamType::Str, true, "Path to .gdb directory"),
188        p("table_name", ParamType::Str, true, "Table or feature class name"),
189        p("bbox", ParamType::Record, false, "Spatial bounding box filter record"),
190    ]),
191    op("GisIo.read_shapefile", Effect::Cold, "Record", "Read ESRI Shapefile geometries and dBASE III+ attributes.", &[
192        p("path", ParamType::Str, true, "File path to .shp file"),
193        p("encoding", ParamType::Str, false, "Character encoding for DBF strings"),
194    ]),
195    op("GisIo.write_shapefile", Effect::External, "Record", "Write ESRI Shapefile (.shp, .shx, .dbf) feature dataset.", &[
196        p("path", ParamType::Str, true, "Base file path for shapefile"),
197        p("features", ParamType::Record, true, "Vector feature collection record"),
198        p("crs", ParamType::Str, true, "Coordinate reference system"),
199    ]),
200    op("GisIo.read_geoparquet", Effect::Cold, "Record", "Read GeoParquet dataset with PAR1 magic, geo metadata, and WKB batch.", &[
201        p("path", ParamType::Str, true, "File path to .parquet file"),
202        p("columns", ParamType::List, false, "Column projection list"),
203        p("bbox", ParamType::Record, false, "Spatial bounding box filter record"),
204    ]),
205    op("GisIo.write_geoparquet", Effect::External, "Record", "Write GeoParquet with PAR1 header, geo metadata, and WKB geometries.", &[
206        p("path", ParamType::Str, true, "Target .parquet file path"),
207        p("features", ParamType::Record, true, "Vector feature collection record"),
208        p("crs", ParamType::Str, true, "Coordinate reference system"),
209    ]),
210    op("GisIo.read_geojson", Effect::Pure, "Record", "Parse RFC 7946 GeoJSON FeatureCollection or Geometry.", &[
211        p("input", ParamType::Str, true, "GeoJSON string or file path"),
212        p("crs", ParamType::Str, false, "Override coordinate reference system"),
213    ]),
214    op("GisIo.write_geojson", Effect::Pure, "Record", "Serialize vector features to RFC 7946 GeoJSON string.", &[
215        p("features", ParamType::Record, true, "Feature collection record"),
216        p("pretty", ParamType::Bool, false, "Format with indentation"),
217        p("precision", ParamType::U64, false, "Coordinate decimal precision"),
218    ]),
219    op("GisIo.read_kml_gpx_gml", Effect::Cold, "Record", "Parse OGC XML vector formats (KML 2.2, GPX 1.1, and GML 3.2).", &[
220        p("input", ParamType::Str, true, "XML content string or file path"),
221        p("format", ParamType::Str, true, "Format selector (kml, gpx, gml)"),
222    ]),
223    op("GisIo.read_dxf_cad", Effect::Cold, "Record", "Read AutoCAD DXF CAD drawing vector entities and layers.", &[
224        p("path", ParamType::Str, true, "File path to .dxf drawing"),
225        p("layers", ParamType::List, false, "Filter list of layer names"),
226    ]),
227    op("GisIo.read_topojson_osm", Effect::Cold, "Record", "Parse TopoJSON arc topology or OpenStreetMap XML/PBF data.", &[
228        p("input", ParamType::Str, true, "Data string or file path"),
229        p("format", ParamType::Str, true, "Format selector (topojson, osm_pbf, osm_xml)"),
230    ]),
231    op("GisIo.read_pmtiles_mvt", Effect::Cold, "Record", "Read PMTiles v3 archive header and extract MVT vector tile.", &[
232        p("path", ParamType::Str, true, "File path or URL to .pmtiles archive"),
233        p("z", ParamType::U64, true, "Zoom level"),
234        p("x", ParamType::U64, true, "Tile column X"),
235        p("y", ParamType::U64, true, "Tile row Y"),
236    ]),
237    op("GisIo.encode_mvt_tile", Effect::Compute, "Record", "Encode vector feature geometries into Mapbox Vector Tile (MVT) protobuf.", &[
238        p("layers", ParamType::Record, true, "Tile layer feature records"),
239        p("extent", ParamType::U64, false, "Vector tile extent (default 4096)"),
240        p("version", ParamType::U64, false, "MVT specification version"),
241    ]),
242];
243
244/// Looks up a GIS I/O or LiDAR operation schema by its canonical invoke ID.
245pub fn lookup_geo_gis_io_operation(invoke_id: &str) -> Option<&'static OperationSchema> {
246    GEO_GIS_IO_OPERATIONS.iter().find(|op| op.invoke_id == invoke_id)
247}
248
249/// Returns the 20 `GisIo.*` GIS I/O and LiDAR capability schema entries for the catalog.
250pub fn entries() -> Vec<SchemaEntry> {
251    GEO_GIS_IO_OPERATIONS.iter().map(|op| {
252        let effect_class = match op.effect {
253            Effect::Pure => EffectClass::Pure,
254            Effect::Compute | Effect::Cold => EffectClass::Read,
255            Effect::Async | Effect::External => EffectClass::External,
256        };
257        let mut entry = SchemaEntry::new(op.invoke_id, effect_class, HonestyLabel::Always, op.returns)
258            .with_description(op.description);
259        for p in op.params {
260            entry = entry.with_arg(SchemaArg::new(p.name, p.param_type.as_str(), p.required).with_description(p.description));
261        }
262        entry
263    }).collect()
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    #[test]
271    fn test_gis_io_operations_count_and_uniqueness() {
272        assert_eq!(GEO_GIS_IO_OPERATIONS.len(), 20);
273        assert_eq!(GEO_GIS_IO_INVOKE_IDS.len(), 20);
274        for (i, op) in GEO_GIS_IO_OPERATIONS.iter().enumerate() {
275            assert_eq!(op.invoke_id, GEO_GIS_IO_INVOKE_IDS[i]);
276            assert!(op.invoke_id.starts_with("GisIo."));
277            assert!(!op.returns.is_empty());
278            assert!(!op.description.is_empty());
279        }
280        let mut ids: Vec<&str> = GEO_GIS_IO_INVOKE_IDS.to_vec();
281        ids.sort();
282        ids.dedup();
283        assert_eq!(ids.len(), 20, "All 20 GisIo invoke IDs must be unique");
284    }
285
286    #[test]
287    fn test_entries_conversion_and_lookup() {
288        assert!(lookup_geo_gis_io_operation("GisIo.read_lidar_copc").is_some());
289        assert!(lookup_geo_gis_io_operation("GisIo.classify_lidar_csf").is_some());
290        assert!(lookup_geo_gis_io_operation("GisIo.pack_lidar_m64").is_some());
291        assert!(lookup_geo_gis_io_operation("GisIo.rasterize_dtm_dsm_chm").is_some());
292        assert!(lookup_geo_gis_io_operation("GisIo.read_flatgeobuf").is_some());
293        assert!(lookup_geo_gis_io_operation("GisIo.encode_mvt_tile").is_some());
294        assert!(lookup_geo_gis_io_operation("GisIo.unknown_op").is_none());
295
296        let converted = entries();
297        assert_eq!(converted.len(), 20);
298        for (i, entry) in converted.iter().enumerate() {
299            assert_eq!(entry.id, GEO_GIS_IO_INVOKE_IDS[i]);
300            assert_eq!(entry.honesty, HonestyLabel::Always);
301        }
302    }
303
304    #[test]
305    fn test_lidar_point_complex_decl_validation() {
306        let valid = LidarPointComplexDecl::new(
307            "snowy_lidar_cloud", 0x00, "EPSG:7855", 67_108_864, vec![2, 3, 4, 5], 1_250_000,
308        );
309        assert!(valid.validate().is_ok());
310        assert_eq!(valid.m64_submagic, 0x00);
311        assert_eq!(valid.byte_budget, 67_108_864);
312        assert_eq!(valid.classification_codes.len(), 4);
313
314        for code in 0..=18 {
315            assert!(LidarPointComplexDecl::is_valid_asprs_code(code));
316            assert!(LidarPointComplexDecl::asprs_code_name(code).is_some());
317        }
318        assert!(!LidarPointComplexDecl::is_valid_asprs_code(19));
319        assert!(LidarPointComplexDecl::asprs_code_name(19).is_none());
320
321        let bad_magic = LidarPointComplexDecl::new("test", 0x01, "EPSG:7855", 1024, vec![2], 100);
322        assert!(bad_magic.validate().is_err());
323
324        let zero_budget = LidarPointComplexDecl::new("test", 0x00, "EPSG:7855", 0, vec![2], 100);
325        assert!(zero_budget.validate().is_err());
326
327        let bad_code = LidarPointComplexDecl::new("test", 0x00, "EPSG:7855", 1024, vec![2, 19], 100);
328        assert!(bad_code.validate().is_err());
329
330        let empty_crs = LidarPointComplexDecl::new("test", 0x00, "", 1024, vec![2], 100);
331        assert!(empty_crs.validate().is_err());
332    }
333
334    #[test]
335    fn test_lidar_vector_ingest_fixture_exists() {
336        let manifest_dir = env!("CARGO_MANIFEST_DIR");
337        let fixture_path = std::path::Path::new(manifest_dir)
338            .join("fixtures")
339            .join("geography")
340            .join("lidar_vector_ingest.vibe");
341        assert!(
342            fixture_path.exists(),
343            "Fixture lidar_vector_ingest.vibe must exist at {:?}",
344            fixture_path
345        );
346    }
347}