#![allow(clippy::unwrap_used)]
use std::io::{Seek, Write};
use std::path::Path;
use geolith_cli::cli::TerrainArgs;
use geolith_cli::terrain::{CogMosaic, Crs, Dem, ElevationSource};
use tiff::encoder::{DirectoryEncoder, TiffEncoder, TiffKind, colortype};
use tiff::tags::Tag;
const TAG_MODEL_PIXEL_SCALE: u16 = 33550;
const TAG_MODEL_TIEPOINT: u16 = 33922;
const TAG_MODEL_TRANSFORMATION: u16 = 34264;
const TAG_GEO_KEY_DIRECTORY: u16 = 34735;
const TAG_GDAL_NODATA: u16 = 42113;
#[derive(Clone, Copy)]
enum Georeferencing {
ScaleAndTiepoint,
TransformationMatrix,
None,
MalformedScale,
ScaleWithoutTiepoint,
}
#[derive(Clone, Copy)]
enum GeoKeys {
Absent,
Projected(u32),
WithoutCrsKey,
}
struct DemFixture {
width: u32,
height: u32,
values: Vec<f32>,
origin_x: f64,
origin_y: f64,
pixel_size: f64,
georeferencing: Georeferencing,
geo_keys: GeoKeys,
nodata: Option<String>,
bands: u8,
}
impl Default for DemFixture {
fn default() -> Self {
Self {
width: 4,
height: 4,
values: (0..16).map(|i| 1000.0 + i as f32).collect(),
origin_x: 400_000.0,
origin_y: 5_100_000.0,
pixel_size: 10.0,
georeferencing: Georeferencing::ScaleAndTiepoint,
geo_keys: GeoKeys::Projected(32_632),
nodata: None,
bands: 1,
}
}
}
impl DemFixture {
fn write(&self) -> tempfile::NamedTempFile {
let mut file = tempfile::Builder::new()
.suffix(".tif")
.tempfile()
.expect("temp file");
file.write_all(&self.to_bytes()).expect("write tiff");
file.flush().expect("flush");
file
}
fn to_bytes(&self) -> Vec<u8> {
let mut buffer = std::io::Cursor::new(Vec::new());
{
let mut encoder = TiffEncoder::new(&mut buffer).expect("tiff encoder");
if self.bands == 3 {
let mut image = encoder
.new_image::<colortype::RGB32Float>(self.width, self.height)
.expect("image encoder");
self.write_tags(image.encoder());
let banded: Vec<f32> = self
.values
.iter()
.flat_map(|value| [*value, *value, *value])
.collect();
image.write_data(&banded).expect("write samples");
} else {
let mut image = encoder
.new_image::<colortype::Gray32Float>(self.width, self.height)
.expect("image encoder");
self.write_tags(image.encoder());
image.write_data(&self.values).expect("write samples");
}
}
buffer.rewind().expect("rewind");
buffer.into_inner()
}
fn write_tags<W, K>(&self, directory: &mut DirectoryEncoder<'_, W, K>)
where
W: Write + Seek,
K: TiffKind,
{
match self.georeferencing {
Georeferencing::ScaleAndTiepoint => {
directory
.write_tag(
Tag::Unknown(TAG_MODEL_PIXEL_SCALE),
&[self.pixel_size, self.pixel_size, 0.0][..],
)
.expect("pixel scale");
directory
.write_tag(
Tag::Unknown(TAG_MODEL_TIEPOINT),
&[0.0, 0.0, 0.0, self.origin_x, self.origin_y, 0.0][..],
)
.expect("tiepoint");
}
Georeferencing::TransformationMatrix => {
directory
.write_tag(
Tag::Unknown(TAG_MODEL_TRANSFORMATION),
&[
self.pixel_size,
0.0,
0.0,
self.origin_x,
0.0,
-self.pixel_size,
0.0,
self.origin_y,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
1.0,
][..],
)
.expect("transformation");
}
Georeferencing::MalformedScale => {
directory
.write_tag(Tag::Unknown(TAG_MODEL_PIXEL_SCALE), &[self.pixel_size][..])
.expect("short scale");
directory
.write_tag(Tag::Unknown(TAG_MODEL_TIEPOINT), &[0.0, 0.0][..])
.expect("short tiepoint");
}
Georeferencing::ScaleWithoutTiepoint => {
directory
.write_tag(
Tag::Unknown(TAG_MODEL_PIXEL_SCALE),
&[self.pixel_size, self.pixel_size, 0.0][..],
)
.expect("pixel scale");
}
Georeferencing::None => {}
}
match self.geo_keys {
GeoKeys::Projected(epsg) => {
directory
.write_tag(
Tag::Unknown(TAG_GEO_KEY_DIRECTORY),
&[1_u32, 1, 0, 1, 3072, 0, 1, epsg][..],
)
.expect("geokeys");
}
GeoKeys::WithoutCrsKey => {
directory
.write_tag(
Tag::Unknown(TAG_GEO_KEY_DIRECTORY),
&[1_u32, 1, 0, 1, 1024, 0, 1, 1][..],
)
.expect("geokeys without a CRS entry");
}
GeoKeys::Absent => {}
}
if let Some(nodata) = &self.nodata {
directory
.write_tag(Tag::Unknown(TAG_GDAL_NODATA), nodata.as_str())
.expect("nodata");
}
}
}
fn terrain_args(dem: &Path, output: &Path) -> TerrainArgs {
TerrainArgs {
dem: vec![dem.to_path_buf()],
clip: None,
output: output.to_path_buf(),
encoding: "mapbox".to_owned(),
min_zoom: 12,
max_zoom: 13,
tile_size: 256,
dem_crs: None,
name: "terrain".to_owned(),
}
}
#[test]
fn open_reads_scale_and_tiepoint_georeferencing() {
let file = DemFixture::default().write();
let dem = Dem::open(file.path(), None).expect("fixture decodes");
assert_eq!(dem.width, 4);
assert_eq!(dem.height, 4);
assert_eq!(dem.values.len(), 16);
assert_eq!(
dem.crs.epsg(),
32_632,
"EPSG comes from the GeoKeyDirectory"
);
assert!((dem.transform.origin_x - 400_000.0).abs() < 1e-6);
assert!((dem.transform.origin_y - 5_100_000.0).abs() < 1e-6);
assert!((dem.transform.pixel_width - 10.0).abs() < 1e-9);
assert!((dem.transform.pixel_height - 10.0).abs() < 1e-9);
assert_eq!(dem.value_at(0, 0), Some(1000.0));
assert_eq!(dem.value_at(3, 3), Some(1015.0));
}
#[test]
fn open_reads_transformation_matrix_georeferencing() {
let file = DemFixture {
georeferencing: Georeferencing::TransformationMatrix,
..DemFixture::default()
}
.write();
let dem = Dem::open(file.path(), None).expect("matrix fixture decodes");
assert!((dem.transform.origin_x - 400_000.0).abs() < 1e-6);
assert!((dem.transform.origin_y - 5_100_000.0).abs() < 1e-6);
assert!(
(dem.transform.pixel_height - 10.0).abs() < 1e-9,
"matrix[5] is negated into a downward-positive row step"
);
}
#[test]
fn open_applies_the_crs_override_over_the_geokeys() {
let file = DemFixture::default().write();
let dem = Dem::open(file.path(), Some(Crs::Wgs84)).expect("override wins");
assert_eq!(dem.crs, Crs::Wgs84);
}
#[test]
fn open_maps_the_gdal_nodata_sentinel_to_nan() {
let mut values: Vec<f32> = (0..16).map(|i| 1000.0 + i as f32).collect();
values[5] = -9999.0;
let file = DemFixture {
values,
nodata: Some("-9999".to_owned()),
..DemFixture::default()
}
.write();
let dem = Dem::open(file.path(), None).expect("nodata fixture decodes");
assert_eq!(dem.value_at(1, 1), None, "sentinel pixel reads as nodata");
assert_eq!(dem.value_at(0, 0), Some(1000.0));
let (min, max) = dem.elevation_range().expect("valid samples remain");
assert!((min - 1000.0).abs() < 1e-6, "sentinel excluded from min");
assert!((max - 1015.0).abs() < 1e-6);
}
#[test]
fn open_keeps_every_sample_when_the_nodata_tag_is_absent() {
let file = DemFixture::default().write();
let dem = Dem::open(file.path(), None).expect("fixture decodes");
assert!(
dem.values.iter().all(|v| v.is_finite()),
"without a sentinel no sample becomes nodata"
);
}
#[test]
fn open_ignores_an_unparseable_nodata_sentinel() {
let file = DemFixture {
nodata: Some("nan-ish".to_owned()),
..DemFixture::default()
}
.write();
let dem = Dem::open(file.path(), None).expect("fixture decodes");
assert!(
dem.values.iter().all(|v| v.is_finite()),
"an unparseable sentinel is ignored rather than voiding the raster"
);
}
#[test]
fn open_without_geokeys_requires_a_crs_override() {
let file = DemFixture {
geo_keys: GeoKeys::Absent,
..DemFixture::default()
}
.write();
let err = Dem::open(file.path(), None).expect_err("no geokeys, no override");
assert!(
format!("{err}").contains("--dem-crs"),
"the error tells the operator how to recover: {err}"
);
let dem = Dem::open(
file.path(),
Some(Crs::Utm {
zone: 32,
north: true,
}),
)
.expect("override supplies the missing CRS");
assert_eq!(dem.crs.epsg(), 32_632);
}
#[test]
fn open_rejects_geokeys_without_a_crs_entry() {
let file = DemFixture {
geo_keys: GeoKeys::WithoutCrsKey,
..DemFixture::default()
}
.write();
let err = Dem::open(file.path(), None).expect_err("no CRS key present");
assert!(
format!("{err}").contains("no ProjectedCSType or GeographicType"),
"{err}"
);
let dem = Dem::open(file.path(), Some(Crs::Wgs84)).expect("override rescues the read");
assert_eq!(dem.crs, Crs::Wgs84);
}
#[test]
fn open_rejects_a_raster_without_georeferencing() {
let file = DemFixture {
georeferencing: Georeferencing::None,
..DemFixture::default()
}
.write();
let err = Dem::open(file.path(), None).expect_err("ungeoreferenced raster");
assert!(
format!("{err}").contains("ModelPixelScale"),
"the error names the missing tag: {err}"
);
}
#[test]
fn open_rejects_malformed_georeferencing_tags() {
let file = DemFixture {
georeferencing: Georeferencing::MalformedScale,
..DemFixture::default()
}
.write();
let err = Dem::open(file.path(), None).expect_err("short tags");
assert!(
format!("{err}").contains("malformed georeferencing"),
"{err}"
);
}
#[test]
fn open_rejects_a_scale_without_a_tiepoint() {
let file = DemFixture {
georeferencing: Georeferencing::ScaleWithoutTiepoint,
..DemFixture::default()
}
.write();
let err = Dem::open(file.path(), None).expect_err("scale alone cannot place the raster");
assert!(
format!("{err}").contains("missing ModelTiepoint"),
"the error names the absent companion tag: {err}"
);
}
#[test]
fn open_rejects_an_unsupported_epsg() {
let file = DemFixture {
geo_keys: GeoKeys::Projected(27_700),
..DemFixture::default()
}
.write();
assert!(
Dem::open(file.path(), None).is_err(),
"British National Grid is not a supported projection"
);
}
#[test]
fn open_rejects_a_multi_band_raster() {
let file = DemFixture {
bands: 3,
..DemFixture::default()
}
.write();
let err = Dem::open(file.path(), None).expect_err("an RGB orthophoto is not a DEM");
assert!(
format!("{err}").contains("expected 16 samples"),
"the error reports the sample-count mismatch: {err}"
);
}
#[test]
fn open_reports_a_missing_file() {
assert!(
Dem::open(Path::new("/nonexistent/dem.tif"), None).is_err(),
"a missing DEM surfaces as an error"
);
}
#[test]
fn open_reports_a_non_tiff_file() {
let mut file = tempfile::NamedTempFile::new().expect("temp");
file.write_all(b"this is not a tiff").expect("write");
file.flush().expect("flush");
assert!(
Dem::open(file.path(), None).is_err(),
"a non-TIFF payload is rejected"
);
}
#[test]
fn open_projects_wgs84_bounds_from_a_utm_raster() {
let file = DemFixture::default().write();
let dem = Dem::open(file.path(), None).expect("fixture decodes");
let (min_lon, min_lat, max_lon, max_lat) = dem.wgs84_bounds();
assert!(
(0.0..12.0).contains(&min_lon),
"UTM 32N easting 400km lands in central Europe: {min_lon}"
);
assert!(
(40.0..50.0).contains(&min_lat),
"northing 5100km is mid-latitude: {min_lat}"
);
assert!(min_lon < max_lon && min_lat < max_lat);
}
#[test]
fn run_terrain_writes_a_pmtiles_archive() {
let file = DemFixture::default().write();
let dir = tempfile::tempdir().expect("tempdir");
let output = dir.path().join("terrain.pmtiles");
geolith_cli::run_terrain(&terrain_args(file.path(), &output)).expect("terrain pipeline runs");
let bytes = std::fs::read(&output).expect("archive exists");
assert_eq!(&bytes[..7], b"PMTiles", "archive carries the PMTiles magic");
assert_eq!(bytes[7], 3, "spec version 3");
}
#[test]
fn run_terrain_honours_the_terrarium_encoding() {
let file = DemFixture::default().write();
let dir = tempfile::tempdir().expect("tempdir");
let output = dir.path().join("terrarium.pmtiles");
let mut args = terrain_args(file.path(), &output);
args.encoding = "terrarium".to_owned();
geolith_cli::run_terrain(&args).expect("terrarium encoding runs");
assert!(
std::fs::metadata(&output).expect("archive exists").len() > 0,
"archive is non-empty"
);
}
#[test]
fn run_terrain_applies_the_dem_crs_override() {
let file = DemFixture {
geo_keys: GeoKeys::Absent,
..DemFixture::default()
}
.write();
let dir = tempfile::tempdir().expect("tempdir");
let output = dir.path().join("override.pmtiles");
let mut args = terrain_args(file.path(), &output);
assert!(
geolith_cli::run_terrain(&args).is_err(),
"a DEM without geokeys cannot be placed without an override"
);
args.dem_crs = Some(32_632);
geolith_cli::run_terrain(&args).expect("the override supplies the CRS");
assert!(output.exists());
}
#[test]
fn run_terrain_rejects_an_unknown_encoding_before_reading_the_dem() {
let dir = tempfile::tempdir().expect("tempdir");
let mut args = terrain_args(
Path::new("/nonexistent/dem.tif"),
&dir.path().join("out.pmtiles"),
);
args.encoding = "rainbow".to_owned();
let err = geolith_cli::run_terrain(&args).expect_err("unknown encoding");
assert!(
format!("{err}").contains("rainbow"),
"encoding is validated before the DEM is opened: {err}"
);
}
#[test]
fn run_terrain_rejects_an_unsupported_dem_crs_flag() {
let dir = tempfile::tempdir().expect("tempdir");
let mut args = terrain_args(
Path::new("/nonexistent/dem.tif"),
&dir.path().join("out.pmtiles"),
);
args.dem_crs = Some(27_700);
assert!(
geolith_cli::run_terrain(&args).is_err(),
"an unsupported EPSG fails before the DEM is read"
);
}
#[test]
fn run_terrain_propagates_a_dem_read_failure() {
let dir = tempfile::tempdir().expect("tempdir");
let args = terrain_args(
Path::new("/nonexistent/dem.tif"),
&dir.path().join("out.pmtiles"),
);
assert!(
geolith_cli::run_terrain(&args).is_err(),
"missing DEM surfaces as an error"
);
}
#[test]
fn run_terrain_accepts_a_fully_nodata_dem() {
let file = DemFixture {
values: vec![-9999.0; 16],
nodata: Some("-9999".to_owned()),
..DemFixture::default()
}
.write();
let dir = tempfile::tempdir().expect("tempdir");
let output = dir.path().join("nodata.pmtiles");
geolith_cli::run_terrain(&terrain_args(file.path(), &output))
.expect("an all-nodata DEM still produces a valid archive");
assert!(output.exists());
}
const MANY_SOURCES: usize = 96;
const MAX_HELD_DESCRIPTORS: usize = 48;
fn open_files() -> usize {
for dir in ["/dev/fd", "/proc/self/fd"] {
if let Ok(entries) = std::fs::read_dir(dir) {
return entries.count();
}
}
panic!("neither /dev/fd nor /proc/self/fd lists this process's descriptors");
}
#[test]
fn opening_a_mosaic_holds_no_reader_per_source() {
let dir = tempfile::tempdir().expect("tempdir");
let mut paths = Vec::with_capacity(MANY_SOURCES);
for i in 0..MANY_SOURCES {
let fixture = DemFixture {
geo_keys: GeoKeys::Projected(4326),
origin_x: 70.0 + i as f64 * 0.01,
origin_y: 30.0,
pixel_size: 1.0 / 1200.0,
..DemFixture::default()
};
let path = dir.path().join(format!("dem-{i:03}.tif"));
std::fs::write(&path, fixture.to_bytes()).expect("write fixture");
paths.push(path);
}
let before = open_files();
let mosaic = CogMosaic::open(&paths, None).expect("a mosaic of many sources");
assert_eq!(mosaic.len(), MANY_SOURCES, "every source is in the mosaic");
let opened = open_files().saturating_sub(before);
assert!(
opened <= MAX_HELD_DESCRIPTORS,
"opening {MANY_SOURCES} sources held {opened} descriptors"
);
let patches = mosaic
.patches((70.0, 30.0, 71.0, 31.0), 90.0)
.expect("patches over the sources");
assert!(
!patches.is_empty(),
"the mosaic reads the sources its bounds cover"
);
let held = open_files().saturating_sub(before);
assert!(
held <= MAX_HELD_DESCRIPTORS,
"reading {MANY_SOURCES} sources held {held} descriptors"
);
}
#[test]
fn run_command_dispatches_the_terrain_verb() {
let file = DemFixture::default().write();
let dir = tempfile::tempdir().expect("tempdir");
let output = dir.path().join("dispatched.pmtiles");
let command = geolith_cli::cli::parse_from([
"geolith",
"terrain",
"--dem",
file.path().to_str().expect("utf-8 path"),
"--output",
output.to_str().expect("utf-8 path"),
"--min-zoom",
"12",
"--max-zoom",
"13",
"--tile-size",
"256",
])
.expect("terrain parses");
geolith_cli::run_command(command).expect("the verb reaches run_terrain");
assert!(output.exists(), "dispatch produced the archive");
}