use std::fs::File;
use std::io::BufReader;
use std::path::Path;
use crate::error::{GeolithError, Result};
use tiff::decoder::{Decoder, DecodingResult};
use tiff::tags::Tag;
use crate::terrain::crs::Crs;
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;
const GEO_KEY_PROJECTED_CS_TYPE: u16 = 3072;
const GEO_KEY_GEOGRAPHIC_TYPE: u16 = 2048;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GeoTransform {
pub origin_x: f64,
pub origin_y: f64,
pub pixel_width: f64,
pub pixel_height: f64,
}
impl GeoTransform {
#[must_use]
pub fn pixel_center(&self, col: f64, row: f64) -> (f64, f64) {
(
self.origin_x + (col + 0.5) * self.pixel_width,
self.origin_y - (row + 0.5) * self.pixel_height,
)
}
#[must_use]
pub fn to_pixel(&self, x: f64, y: f64) -> (f64, f64) {
(
(x - self.origin_x) / self.pixel_width - 0.5,
(self.origin_y - y) / self.pixel_height - 0.5,
)
}
}
#[derive(Debug, Clone)]
pub struct Dem {
pub width: u32,
pub height: u32,
pub values: Vec<f32>,
pub transform: GeoTransform,
pub crs: Crs,
}
impl Dem {
pub fn open(path: &Path, crs_override: Option<Crs>) -> Result<Self> {
let file = File::open(path)?;
let mut decoder = Decoder::new(BufReader::new(file))
.map_err(|e| GeolithError::GeoTiff(format!("{}: {e}", path.display())))?
.with_limits(tiff::decoder::Limits::unlimited());
let (width, height) = decoder
.dimensions()
.map_err(|e| GeolithError::GeoTiff(format!("{}: dimensions: {e}", path.display())))?;
let transform = read_geo_transform(&mut decoder, path)?;
let crs = match crs_override {
Some(crs) => crs,
None => read_crs(&mut decoder, path)?,
};
let nodata = read_nodata(&mut decoder);
let image = decoder
.read_image()
.map_err(|e| GeolithError::GeoTiff(format!("{}: read_image: {e}", path.display())))?;
let values = to_f32_samples(image, nodata, path)?;
let expected = width as usize * height as usize;
if values.len() != expected {
return Err(GeolithError::GeoTiff(format!(
"{}: expected {expected} samples for {width}x{height}, got {}",
path.display(),
values.len()
)));
}
Ok(Self {
width,
height,
values,
transform,
crs,
})
}
#[must_use]
pub fn value_at(&self, col: i64, row: i64) -> Option<f32> {
if col < 0 || row < 0 || col >= i64::from(self.width) || row >= i64::from(self.height) {
return None;
}
let index = row as usize * self.width as usize + col as usize;
let value = self.values[index];
if value.is_nan() { None } else { Some(value) }
}
#[must_use]
pub fn sample(&self, x: f64, y: f64) -> Option<f32> {
let (fx, fy) = self.transform.to_pixel(x, y);
let col0 = fx.floor();
let row0 = fy.floor();
let tx = fx - col0;
let ty = fy - row0;
let (col0, row0) = (col0 as i64, row0 as i64);
let corners = [
(col0, row0, (1.0 - tx) * (1.0 - ty)),
(col0 + 1, row0, tx * (1.0 - ty)),
(col0, row0 + 1, (1.0 - tx) * ty),
(col0 + 1, row0 + 1, tx * ty),
];
let mut total = 0.0_f64;
let mut weight_sum = 0.0_f64;
for (col, row, weight) in corners {
if weight <= 0.0 {
continue;
}
if let Some(value) = self.value_at(col, row) {
total += f64::from(value) * weight;
weight_sum += weight;
}
}
if weight_sum <= 0.0 {
return None;
}
Some((total / weight_sum) as f32)
}
#[must_use]
pub fn wgs84_bounds(&self) -> (f64, f64, f64, f64) {
let (w, h) = (f64::from(self.width), f64::from(self.height));
let corners = [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)];
let mut min_lon = f64::INFINITY;
let mut min_lat = f64::INFINITY;
let mut max_lon = f64::NEG_INFINITY;
let mut max_lat = f64::NEG_INFINITY;
for (col, row) in corners {
let x = self.transform.origin_x + col * self.transform.pixel_width;
let y = self.transform.origin_y - row * self.transform.pixel_height;
let (lon, lat) = self.crs.to_wgs84(x, y);
min_lon = min_lon.min(lon);
min_lat = min_lat.min(lat);
max_lon = max_lon.max(lon);
max_lat = max_lat.max(lat);
}
(min_lon, min_lat, max_lon, max_lat)
}
#[must_use]
pub fn elevation_range(&self) -> Option<(f32, f32)> {
let mut min = f32::INFINITY;
let mut max = f32::NEG_INFINITY;
let mut seen = false;
for value in &self.values {
if value.is_nan() {
continue;
}
seen = true;
min = min.min(*value);
max = max.max(*value);
}
seen.then_some((min, max))
}
}
pub fn read_geo_transform<R>(decoder: &mut Decoder<R>, path: &Path) -> Result<GeoTransform>
where
R: std::io::Read + std::io::Seek,
{
if let Ok(matrix) = decoder.get_tag_f64_vec(Tag::Unknown(TAG_MODEL_TRANSFORMATION))
&& matrix.len() >= 16
{
return Ok(GeoTransform {
origin_x: matrix[3],
origin_y: matrix[7],
pixel_width: matrix[0],
pixel_height: -matrix[5],
});
}
let scale = decoder
.get_tag_f64_vec(Tag::Unknown(TAG_MODEL_PIXEL_SCALE))
.map_err(|e| {
GeolithError::GeoTiff(format!(
"{}: missing ModelPixelScale and ModelTransformation: {e}",
path.display()
))
})?;
let tiepoint = decoder
.get_tag_f64_vec(Tag::Unknown(TAG_MODEL_TIEPOINT))
.map_err(|e| {
GeolithError::GeoTiff(format!("{}: missing ModelTiepoint: {e}", path.display()))
})?;
if scale.len() < 2 || tiepoint.len() < 6 {
return Err(GeolithError::GeoTiff(format!(
"{}: malformed georeferencing tags (scale={}, tiepoint={})",
path.display(),
scale.len(),
tiepoint.len()
)));
}
Ok(GeoTransform {
origin_x: tiepoint[3] - tiepoint[0] * scale[0],
origin_y: tiepoint[4] + tiepoint[1] * scale[1],
pixel_width: scale[0],
pixel_height: scale[1],
})
}
pub fn read_crs<R>(decoder: &mut Decoder<R>, path: &Path) -> Result<Crs>
where
R: std::io::Read + std::io::Seek,
{
let keys = decoder
.get_tag_u32_vec(Tag::Unknown(TAG_GEO_KEY_DIRECTORY))
.map_err(|e| {
GeolithError::GeoTiff(format!(
"{}: missing GeoKeyDirectory (pass --dem-crs to override): {e}",
path.display()
))
})?;
let epsg = epsg_from_geo_keys(&keys).ok_or_else(|| {
GeolithError::GeoTiff(format!(
"{}: GeoKeyDirectory has no ProjectedCSType or GeographicType key \
(pass --dem-crs to override)",
path.display()
))
})?;
Crs::from_epsg(epsg)
}
#[must_use]
fn epsg_from_geo_keys(keys: &[u32]) -> Option<u32> {
if keys.len() < 4 {
return None;
}
let count = keys[3] as usize;
let mut geographic = None;
for entry in 0..count {
let base = 4 + entry * 4;
if base + 3 >= keys.len() {
break;
}
let (key_id, tag_location, value) = (keys[base], keys[base + 1], keys[base + 3]);
if tag_location != 0 {
continue;
}
match u16::try_from(key_id) {
Ok(GEO_KEY_PROJECTED_CS_TYPE) => return Some(value),
Ok(GEO_KEY_GEOGRAPHIC_TYPE) => geographic = Some(value),
_ => {}
}
}
geographic
}
pub fn read_nodata<R>(decoder: &mut Decoder<R>) -> Option<f64>
where
R: std::io::Read + std::io::Seek,
{
let raw = decoder
.get_tag_ascii_string(Tag::Unknown(TAG_GDAL_NODATA))
.ok()?;
raw.trim().trim_end_matches('\0').parse::<f64>().ok()
}
pub fn to_f32_samples(image: DecodingResult, nodata: Option<f64>, path: &Path) -> Result<Vec<f32>> {
let mut values: Vec<f32> = match image {
DecodingResult::F32(v) => v,
DecodingResult::F64(v) => v.into_iter().map(|x| x as f32).collect(),
DecodingResult::I8(v) => v.into_iter().map(f32::from).collect(),
DecodingResult::U8(v) => v.into_iter().map(f32::from).collect(),
DecodingResult::I16(v) => v.into_iter().map(f32::from).collect(),
DecodingResult::U16(v) => v.into_iter().map(f32::from).collect(),
DecodingResult::I32(v) => v.into_iter().map(|x| x as f32).collect(),
DecodingResult::U32(v) => v.into_iter().map(|x| x as f32).collect(),
DecodingResult::I64(v) => v.into_iter().map(|x| x as f32).collect(),
DecodingResult::U64(v) => v.into_iter().map(|x| x as f32).collect(),
other => {
return Err(GeolithError::GeoTiff(format!(
"{}: unsupported sample format {other:?}",
path.display()
)));
}
};
if let Some(sentinel) = nodata {
let sentinel = sentinel as f32;
for value in &mut values {
if *value == sentinel {
*value = f32::NAN;
}
}
}
Ok(values)
}
#[cfg(test)]
mod tests {
use super::*;
fn test_dem() -> Dem {
Dem {
width: 2,
height: 2,
values: vec![0.0, 100.0, 200.0, 300.0],
transform: GeoTransform {
origin_x: 1000.0,
origin_y: 2000.0,
pixel_width: 10.0,
pixel_height: 10.0,
},
crs: Crs::Wgs84,
}
}
#[test]
fn pixel_center_and_to_pixel_are_inverse() {
let t = test_dem().transform;
let (x, y) = t.pixel_center(3.0, 7.0);
let (col, row) = t.to_pixel(x, y);
assert!((col - 3.0).abs() < 1e-9, "col: {col}");
assert!((row - 7.0).abs() < 1e-9, "row: {row}");
}
#[test]
fn value_at_returns_none_outside_raster() {
let dem = test_dem();
assert_eq!(dem.value_at(0, 0), Some(0.0));
assert_eq!(dem.value_at(1, 1), Some(300.0));
assert_eq!(dem.value_at(-1, 0), None);
assert_eq!(dem.value_at(0, -1), None);
assert_eq!(dem.value_at(2, 0), None);
assert_eq!(dem.value_at(0, 2), None);
}
#[test]
fn value_at_treats_nan_as_nodata() {
let mut dem = test_dem();
dem.values[0] = f32::NAN;
assert_eq!(dem.value_at(0, 0), None);
}
#[test]
fn sample_at_pixel_center_returns_exact_value() {
let dem = test_dem();
let (x, y) = dem.transform.pixel_center(0.0, 0.0);
let sampled = dem.sample(x, y).expect("inside raster");
assert!((sampled - 0.0).abs() < 1e-4, "got {sampled}");
let (x, y) = dem.transform.pixel_center(1.0, 1.0);
let sampled = dem.sample(x, y).expect("inside raster");
assert!((sampled - 300.0).abs() < 1e-4, "got {sampled}");
}
#[test]
fn sample_midpoint_interpolates_all_four_corners() {
let dem = test_dem();
let (x0, y0) = dem.transform.pixel_center(0.0, 0.0);
let (x1, y1) = dem.transform.pixel_center(1.0, 1.0);
let sampled = dem
.sample((x0 + x1) / 2.0, (y0 + y1) / 2.0)
.expect("inside raster");
assert!((sampled - 150.0).abs() < 1e-3, "got {sampled}");
}
#[test]
fn sample_renormalises_over_partial_nodata() {
let mut dem = test_dem();
dem.values[3] = f32::NAN;
let (x0, y0) = dem.transform.pixel_center(0.0, 0.0);
let (x1, y1) = dem.transform.pixel_center(1.0, 1.0);
let sampled = dem
.sample((x0 + x1) / 2.0, (y0 + y1) / 2.0)
.expect("three valid corners remain");
assert!((sampled - 100.0).abs() < 1e-3, "got {sampled}");
}
#[test]
fn sample_returns_none_when_fully_nodata() {
let mut dem = test_dem();
dem.values = vec![f32::NAN; 4];
let (x, y) = dem.transform.pixel_center(0.0, 0.0);
assert_eq!(dem.sample(x, y), None);
}
#[test]
fn sample_outside_raster_is_none() {
let dem = test_dem();
assert_eq!(dem.sample(0.0, 0.0), None);
assert_eq!(dem.sample(100_000.0, 100_000.0), None);
}
#[test]
fn elevation_range_skips_nodata() {
let mut dem = test_dem();
dem.values[1] = f32::NAN;
let (min, max) = dem.elevation_range().expect("valid samples remain");
assert!((min - 0.0).abs() < 1e-6);
assert!((max - 300.0).abs() < 1e-6);
}
#[test]
fn elevation_range_is_none_when_fully_nodata() {
let mut dem = test_dem();
dem.values = vec![f32::NAN; 4];
assert_eq!(dem.elevation_range(), None);
}
#[test]
fn wgs84_bounds_cover_all_corners() {
let dem = test_dem();
let (min_lon, min_lat, max_lon, max_lat) = dem.wgs84_bounds();
assert!(min_lon < max_lon, "{min_lon} < {max_lon}");
assert!(min_lat < max_lat, "{min_lat} < {max_lat}");
}
#[test]
fn epsg_from_geo_keys_falls_back_to_geographic() {
let keys = vec![1, 1, 0, 1, u32::from(GEO_KEY_GEOGRAPHIC_TYPE), 0, 1, 4326];
assert_eq!(epsg_from_geo_keys(&keys), Some(4326));
}
#[test]
fn epsg_from_geo_keys_prefers_projected_over_geographic() {
let keys = vec![
1,
1,
0,
2,
u32::from(GEO_KEY_GEOGRAPHIC_TYPE),
0,
1,
4326,
u32::from(GEO_KEY_PROJECTED_CS_TYPE),
0,
1,
32_632,
];
assert_eq!(epsg_from_geo_keys(&keys), Some(32_632));
let projected_only = vec![
1,
1,
0,
1,
u32::from(GEO_KEY_PROJECTED_CS_TYPE),
0,
1,
32_633,
];
assert_eq!(epsg_from_geo_keys(&projected_only), Some(32_633));
}
#[test]
fn epsg_from_geo_keys_ignores_indirect_values() {
let keys = vec![
1,
1,
0,
1,
u32::from(GEO_KEY_PROJECTED_CS_TYPE),
34_737,
1,
0,
];
assert_eq!(epsg_from_geo_keys(&keys), None);
}
#[test]
fn epsg_from_geo_keys_handles_truncated_input() {
assert_eq!(epsg_from_geo_keys(&[]), None);
assert_eq!(epsg_from_geo_keys(&[1, 1, 0]), None);
assert_eq!(epsg_from_geo_keys(&[1, 1, 0, 5, 3072]), None);
}
#[test]
fn to_f32_samples_maps_nodata_to_nan() {
let decoded = DecodingResult::I16(vec![10, -32_768, 30]);
let values = to_f32_samples(decoded, Some(-32_768.0), Path::new("t.tif")).expect("convert");
assert!((values[0] - 10.0).abs() < 1e-6);
assert!(values[1].is_nan(), "sentinel becomes nodata");
assert!((values[2] - 30.0).abs() < 1e-6);
}
#[test]
fn to_f32_samples_without_nodata_keeps_all_values() {
let decoded = DecodingResult::F32(vec![1.5, 2.5]);
let values = to_f32_samples(decoded, None, Path::new("t.tif")).expect("convert");
assert_eq!(values, vec![1.5, 2.5]);
}
#[test]
fn geo_transform_from_transformation_matrix_negates_row_step() {
let t = GeoTransform {
origin_x: 10.0,
origin_y: 20.0,
pixel_width: 2.0,
pixel_height: 2.0,
};
let (x, y) = t.pixel_center(0.0, 1.0);
assert!((x - 11.0).abs() < 1e-9, "x: {x}");
assert!((y - 17.0).abs() < 1e-9, "northing decreases downward: {y}");
}
#[test]
fn to_f32_samples_converts_every_integer_width() {
let cases: Vec<(DecodingResult, f32)> = vec![
(DecodingResult::I8(vec![-5]), -5.0),
(DecodingResult::U8(vec![250]), 250.0),
(DecodingResult::I16(vec![-3000]), -3000.0),
(DecodingResult::U16(vec![60_000]), 60_000.0),
(DecodingResult::I32(vec![-100_000]), -100_000.0),
(DecodingResult::U32(vec![100_000]), 100_000.0),
(DecodingResult::I64(vec![-1_000_000]), -1_000_000.0),
(DecodingResult::U64(vec![1_000_000]), 1_000_000.0),
(DecodingResult::F64(vec![1234.5]), 1234.5),
];
for (decoded, expected) in cases {
let label = format!("{decoded:?}");
let values = to_f32_samples(decoded, None, Path::new("t.tif")).expect("convert");
assert!(
(values[0] - expected).abs() < 1e-3,
"{label}: got {}",
values[0]
);
}
}
#[test]
fn epsg_from_geo_keys_skips_unrelated_keys() {
let keys = vec![
1,
1,
0,
2,
1024,
0,
1,
1,
u32::from(GEO_KEY_PROJECTED_CS_TYPE),
0,
1,
32_633,
];
assert_eq!(
epsg_from_geo_keys(&keys),
Some(32_633),
"a leading non-CRS key must not stop the scan"
);
}
#[test]
fn to_f32_samples_rejects_an_unsupported_sample_format() {
let decoded = DecodingResult::F16(vec![half::f16::from_f32(1.0)]);
let err = to_f32_samples(decoded, None, Path::new("t.tif"))
.expect_err("f16 has no conversion arm");
assert!(
format!("{err}").contains("unsupported sample format"),
"{err}"
);
}
}