use std::path::PathBuf;
use crate::layers::Layer;
use crate::tiles_error::TilesError;
pub const DEFAULT_MAX_GEOMETRY_FAILURES: u64 = 100;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Reuse {
pub node_cache: bool,
pub resume: bool,
}
impl Reuse {
#[must_use]
pub const fn new(node_cache: bool, resume: bool) -> Self {
Self { node_cache, resume }
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct TilesConfig {
pub data: PathBuf,
pub osm_pbf: Option<PathBuf>,
pub natural_earth: PathBuf,
pub water_polygons: PathBuf,
pub land_polygons: PathBuf,
pub india_boundary: Option<PathBuf>,
pub output: PathBuf,
pub bbox: Option<String>,
pub max_zoom: u8,
pub threads: Option<usize>,
pub chunk_size_mb: usize,
pub tmpdir: Option<PathBuf>,
pub node_store: Option<PathBuf>,
pub buildings_source: String,
pub divisions_source: String,
pub landcover_source: String,
pub bathymetry_source: String,
pub roads_source: String,
pub pois_source: String,
pub water_source: String,
pub landuse_source: String,
pub reuse: Reuse,
pub tile_format: String,
pub bridge_dir: Option<PathBuf>,
pub no_conflate: bool,
pub bridge_files: Vec<PathBuf>,
pub reclaim_source_after_read: bool,
pub allow_missing_types: bool,
pub reclaim_chunks: bool,
pub disk_check: bool,
pub max_geometry_failures: u64,
}
impl TilesConfig {
#[must_use]
pub fn new(
data: impl Into<PathBuf>,
natural_earth: impl Into<PathBuf>,
water_polygons: impl Into<PathBuf>,
land_polygons: impl Into<PathBuf>,
output: impl Into<PathBuf>,
) -> Self {
Self {
data: data.into(),
osm_pbf: None,
natural_earth: natural_earth.into(),
water_polygons: water_polygons.into(),
land_polygons: land_polygons.into(),
india_boundary: None,
output: output.into(),
bbox: None,
max_zoom: 15,
threads: None,
chunk_size_mb: 0,
tmpdir: None,
node_store: None,
buildings_source: "both".to_owned(),
divisions_source: "overture".to_owned(),
landcover_source: "overture".to_owned(),
bathymetry_source: "overture".to_owned(),
roads_source: "both".to_owned(),
pois_source: "both".to_owned(),
water_source: "both".to_owned(),
landuse_source: "both".to_owned(),
reuse: Reuse::default(),
tile_format: "mvt".to_owned(),
bridge_dir: None,
no_conflate: false,
bridge_files: Vec::new(),
reclaim_source_after_read: false,
allow_missing_types: false,
reclaim_chunks: false,
disk_check: true,
max_geometry_failures: DEFAULT_MAX_GEOMETRY_FAILURES,
}
}
pub const fn has_india_boundary(&self) -> bool {
self.india_boundary.is_some()
}
pub fn uses_osm(&self, source: &str) -> bool {
matches!(source, "osm" | "both")
}
pub fn uses_overture(&self, source: &str) -> bool {
matches!(source, "overture" | "both")
}
pub fn overture_enabled(&self, layer: Layer) -> bool {
use Layer;
match layer {
Layer::Buildings => self.uses_overture(&self.buildings_source),
Layer::Roads => self.uses_overture(&self.roads_source),
Layer::Pois => self.uses_overture(&self.pois_source),
Layer::Places => self.uses_overture(&self.divisions_source),
Layer::Boundaries => self.uses_overture(&self.divisions_source),
Layer::Landcover => self.uses_overture(&self.landcover_source),
Layer::Bathymetry => self.uses_overture(&self.bathymetry_source),
Layer::Water => self.uses_overture(&self.water_source),
Layer::Landuse => self.uses_overture(&self.landuse_source),
Layer::Earth | Layer::Transit => true,
_ => true,
}
}
pub fn osm_enabled(&self, layer: Layer) -> bool {
if self.osm_pbf.is_none() {
return false;
}
use Layer;
match layer {
Layer::Buildings => self.uses_osm(&self.buildings_source),
Layer::Roads => self.uses_osm(&self.roads_source),
Layer::Pois => self.uses_osm(&self.pois_source),
Layer::Water => self.uses_osm(&self.water_source),
Layer::Landuse => self.uses_osm(&self.landuse_source),
Layer::Places => true,
_ => true,
}
}
pub fn effective_chunk_bytes(&self) -> usize {
if self.chunk_size_mb > 0 {
return self.chunk_size_mb * 1024 * 1024;
}
let total_ram = detect_total_memory().unwrap_or(16 * 1024 * 1024 * 1024);
let threads = self.threads.unwrap_or_else(|| {
std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(4)
});
const MAX_CHUNK: usize = 2 * 1024 * 1024 * 1024; const MIN_CHUNK: usize = 64 * 1024 * 1024;
let per_thread = (total_ram as usize) / (3 * threads);
per_thread.clamp(MIN_CHUNK, MAX_CHUNK)
}
#[must_use]
pub fn discover_bridge_files(&self) -> Vec<PathBuf> {
self.try_discover_bridge_files().unwrap_or_else(|e| {
tracing::warn!(error = %e, "failed to read the bridge directory");
self.bridge_files.clone()
})
}
pub fn try_discover_bridge_files(&self) -> Result<Vec<PathBuf>, TilesError> {
let mut files = Vec::new();
files.extend(self.bridge_files.iter().cloned());
let bridge_dir = self.bridge_dir.clone().or_else(|| {
self.data.parent().map(|parent| parent.join("gers-bridge"))
});
if let Some(dir) = bridge_dir
&& dir.is_dir()
{
let mut found = Vec::new();
Self::collect_parquet_files(&dir, &mut found)?;
found.sort();
files.extend(found);
}
Ok(files)
}
fn collect_parquet_files(
dir: &std::path::Path,
out: &mut Vec<PathBuf>,
) -> Result<(), TilesError> {
for entry in std::fs::read_dir(dir)? {
let path = entry?.path();
if path.is_dir() {
Self::collect_parquet_files(&path, out)?;
} else if path.extension().is_some_and(|ext| ext == "parquet") {
out.push(path);
}
}
Ok(())
}
}
#[cfg(target_os = "macos")]
fn detect_total_memory() -> Option<u64> {
let output = std::process::Command::new("sysctl")
.args(["-n", "hw.memsize"])
.output()
.ok()?;
String::from_utf8(output.stdout).ok()?.trim().parse().ok()
}
#[cfg(target_os = "linux")]
fn detect_total_memory() -> Option<u64> {
let contents = std::fs::read_to_string("/proc/meminfo").ok()?;
for line in contents.lines() {
if let Some(rest) = line.strip_prefix("MemTotal:") {
let kb: u64 = rest.trim().trim_end_matches(" kB").trim().parse().ok()?;
return Some(kb * 1024);
}
}
None
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
fn detect_total_memory() -> Option<u64> {
None
}