maps: seat buildings on terrain datum under tilt
- Commit
a6c075ceaf250ca5f0a1a14f97a06ce7ad28425f- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-16 04:54 UTC (2 months ago)
- Parents
21608c0
Diff
library/map/src/main/rust/src/tess/roof/cap.rs
diff --git a/library/map/src/main/rust/src/tess/roof/cap.rs b/library/map/src/main/rust/src/tess/roof/cap.rsindex f71f1e7e46..932d0faa1e 100644--- a/library/map/src/main/rust/src/tess/roof/cap.rs+++ b/library/map/src/main/rust/src/tess/roof/cap.rs@@ -11,6 +11,12 @@ const DOME_STEPS: usize = 8; /// The roof cap: a flat lid for a flat/unknown shape (the true footprint, holes and all), or a /// pitched surface over the footprint's oriented box for the five modelled shapes.+///+/// Every emitted `z` is its structural height plus the ground offset sampled at that vertex's+/// `(x, y)`, so the whole roof translates with — never through — the slope beneath: eaves sit+/// above the walls they cap on both the uphill and downhill sides, and the ridge/apex keeps its+/// height over the ground. Corners shared between two faces (a ridge endpoint, a hip corner)+/// sample the same `(x, y)` on both, so they agree bit-for-bit and no crack opens. #[allow(clippy::too_many_arguments)] pub(crate) fn emit_roof( rings: &[Vec<(i32, i32)>],@@ -23,6 +29,7 @@ pub(crate) fn emit_roof( roof_dir_rad: f32, roof_orientation: u8, rgba: u32,+ ground: &dyn Fn(f32, f32) -> f32, out_v: &mut Vec<f32>, out_i: &mut Vec<u32>, ) {@@ -30,21 +37,24 @@ pub(crate) fn emit_roof( let pitched = matches!(roof_shape, ROOF_GABLED | ROOF_HIPPED | ROOF_PYRAMIDAL | ROOF_SKILLION | ROOF_DOME); if !pitched || rise <= 0.0 {- flat_cap(rings, extent, validated, apex, rgba, out_v, out_i);+ flat_cap(rings, extent, validated, apex, rgba, ground, out_v, out_i); return; } let obb = OrientedBox::of(exterior, roof_dir_rad, roof_orientation);- // The roof's own centroid, at mid-roof height, used to orient every face outward.+ // The roof's own centroid, at mid-roof height, used to orient every face outward. Sampled on+ // the ground beneath it (heights cancel out of the orientation test either way), so the+ // facing decision stays the level-footprint one. let (ccx, ccy) = obb.point(0.5, 0.5);- let centre = [ccx, ccy, (wall_top + apex) * 0.5];- let e = wall_top;- let a = apex;- // `(cu, av)` in the oriented box (`cu` across the slopes, `av` along the ridge) to a 3D point.+ let centre = [ccx, ccy, (wall_top + apex) * 0.5 + ground(ccx, ccy)];+ // `(cu, av)` in the oriented box (`cu` across the slopes, `av` along the ridge) to a 3D+ // point at structural height `z` draped over the ground beneath it. let p = |cu: f32, av: f32, z: f32| -> [f32; 3] { let (x, y) = obb.point(cu, av);- [x, y, z]+ [x, y, z + ground(x, y)] };+ let e = wall_top;+ let a = apex; match roof_shape { ROOF_SKILLION => {@@ -101,12 +111,18 @@ pub(crate) fn emit_roof( } /// A flat roof lid: the footprint tessellated at the apex, every face pointing straight up.+///+/// Each corner is lifted by the ground offset beneath it, so the lid follows the slope like the+/// walls below it — a level lid at one height would bury its uphill edge in the hill. The faces+/// keep their straight-up normal: the lid is thin relative to the slope, and flat-shaded from+/// above it reads as one tone either way. pub(crate) fn flat_cap( rings: &[Vec<(i32, i32)>], extent: u32, validated: bool, apex: f32, rgba: u32,+ ground: &dyn Fn(f32, f32) -> f32, out_v: &mut Vec<f32>, out_i: &mut Vec<u32>, ) {@@ -117,7 +133,8 @@ pub(crate) fn flat_cap( let mut pts = [[0.0f32; 3]; 3]; for (corner, &vi) in tri.iter().enumerate() { let at = vi as usize * fill::FLOATS_PER_VERTEX;- pts[corner] = [cap_xy[at], cap_xy[at + 1], apex];+ let (x, y) = (cap_xy[at], cap_xy[at + 1]);+ pts[corner] = [x, y, apex + ground(x, y)]; } push_tri(out_v, out_i, pts[0], pts[1], pts[2], [0.0, 0.0, 1.0], rgba); }
library/map/src/main/rust/src/tess/roof/mod.rs
diff --git a/library/map/src/main/rust/src/tess/roof/mod.rs b/library/map/src/main/rust/src/tess/roof/mod.rsindex 05f0e0a41e..073372fbbf 100644--- a/library/map/src/main/rust/src/tess/roof/mod.rs+++ b/library/map/src/main/rust/src/tess/roof/mod.rs@@ -74,6 +74,15 @@ pub fn pack_argb(argb: u32) -> u32 { /// (`min_height`), `wall_top` where they meet the eaves (`height - roof_height`), and `apex` the /// roof's own top (`height`). A flat roof has `wall_top == apex`. ///+/// `ground` is the tile-normalised ground offset at a tile-local `(u, v)`: every emitted `z`+/// is its structural height *plus* `ground(u, v)`, so walls keep their height while following+/// the slope and the roof drapes over the hill (a skillion's rise, a gable's ridge, a dome's+/// crown all ride parallel to the ground beneath). A flat roof samples the ground at each of+/// its tessellated vertices and follows the slope too — the alternative, a level lid at one+/// corner's height, would clip through the uphill ground. The closure comes from+/// [`crate::tile::geometry`] sampling the tile's heightmap; where the tile carries none it+/// returns 0.0, and the mesh is bit-identical to the un-lifted one.+/// /// `roof_dir_rad` is the roof direction in radians and `roof_orientation` selects which axis the /// ridge runs along. An unrecognised `roof_shape` falls back to flat, never panics. #[allow(clippy::too_many_arguments)]@@ -89,6 +98,7 @@ pub fn extrude( roof_orientation: u8, wall_colour: u32, roof_colour: u32,+ ground: &dyn Fn(f32, f32) -> f32, out_v: &mut Vec<f32>, out_i: &mut Vec<u32>, ) {@@ -115,6 +125,6 @@ pub fn extrude( let wall_rgba = pack_argb(wall_colour); let roof_rgba = pack_argb(roof_colour); - emit_walls(&local, base, wall_top, wall_rgba, out_v, out_i);- emit_roof(rings, extent, validated, &local[0], wall_top, apex, roof_shape, roof_dir_rad, roof_orientation, roof_rgba, out_v, out_i);+ emit_walls(&local, base, wall_top, wall_rgba, ground, out_v, out_i);+ emit_roof(rings, extent, validated, &local[0], wall_top, apex, roof_shape, roof_dir_rad, roof_orientation, roof_rgba, ground, out_v, out_i); }
library/map/src/main/rust/src/tess/roof/tests.rs
diff --git a/library/map/src/main/rust/src/tess/roof/tests.rs b/library/map/src/main/rust/src/tess/roof/tests.rsindex bc394dbc02..c119fa234d 100644--- a/library/map/src/main/rust/src/tess/roof/tests.rs+++ b/library/map/src/main/rust/src/tess/roof/tests.rs@@ -28,12 +28,19 @@ fn extrude_square(shape: u8, base: f32, wall_top: f32, apex: f32) -> (Vec<f32>, ROOF_ORIENT_ALONG, 0xFF_00_80_C0, 0xFF_C0_40_20,+ &flat_ground, &mut v, &mut i, ); (v, i) } +/// Level ground: every existing test extrudes over a flat datum, so the offsets are 0.0 and+/// the meshes are the un-lifted ones.+fn flat_ground(_u: f32, _v: f32) -> f32 {+ 0.0+}+ /// The raw f32 vertex buffer read as bits — so two meshes can be compared for equality without /// a NaN colour pattern making a vertex differ from itself. fn bits(v: &[f32]) -> Vec<u32> {@@ -170,6 +177,81 @@ fn a_skillion_roof_slopes_from_one_edge_to_the_other() { fn empty_rings_emit_nothing() { let mut v = Vec::new(); let mut i = Vec::new();- extrude(&[], 100, false, 0.0, 0.2, 0.4, ROOF_FLAT, 0.0, ROOF_ORIENT_ALONG, 0xFFFFFFFF, 0xFFFFFFFF, &mut v, &mut i);+ extrude(&[], 100, false, 0.0, 0.2, 0.4, ROOF_FLAT, 0.0, ROOF_ORIENT_ALONG, 0xFFFFFFFF, 0xFFFFFFFF, &flat_ground, &mut v, &mut i); assert!(v.is_empty() && i.is_empty()); }++#[test]+fn a_tilted_ground_drapes_walls_and_roof_without_changing_height() {+ // A ground plane rising 0.1 tile-norm per unit u: the wall's uphill corners sit 0.1 higher+ // than its downhill ones, the flat cap rides the same slope (its uphill edge above its+ // downhill edge), and the wall height itself is unchanged — the building translates with+ // the hill, it does not stretch.+ let slope = |u: f32, _v: f32| -> f32 { u * 0.1 };+ let mut v = Vec::new();+ let mut i = Vec::new();+ extrude(+ &unit_square(),+ 100,+ false,+ 0.0,+ 0.2,+ 0.2,+ ROOF_FLAT,+ 0.0,+ ROOF_ORIENT_ALONG,+ 0xFFFFFFFF,+ 0xFFFFFFFF,+ &slope,+ &mut v,+ &mut i,+ );+ let count = v.len() / FLOATS_PER_VERTEX;+ assert!(count > 0);+ let (mut wall_lo, mut wall_hi) = (f32::MAX, f32::MIN);+ let (mut cap_lo, mut cap_hi) = (f32::MAX, f32::MIN);+ for k in 0..count {+ let (p, n, _) = vertex(&v, k);+ if n[2] > 0.9 {+ cap_lo = cap_lo.min(p[2]);+ cap_hi = cap_hi.max(p[2]);+ } else {+ wall_lo = wall_lo.min(p[2]);+ wall_hi = wall_hi.max(p[2]);+ }+ }+ assert!((cap_hi - cap_lo - 0.1).abs() < 1e-5, "the cap follows the slope, got {cap_lo}..{cap_hi}");+ assert!(+ (wall_hi - wall_lo - 0.3).abs() < 1e-5,+ "the wall spans its 0.2 height plus the 0.1 slope, got {wall_lo}..{wall_hi}",+ );+}++#[test]+fn a_zero_ground_leaves_every_structural_height_exact() {+ // The pitch-0 guarantee at the unit level: with a 0.0 ground closure the wall base, eaves+ // and ridge must sit at exactly the structural heights passed in — no offset may leak in.+ // Compared by bits so a float rounding slip cannot hide.+ for shape in [ROOF_FLAT, ROOF_GABLED, ROOF_SKILLION, ROOF_PYRAMIDAL] {+ let (v, _) = extrude_square(shape, 0.05, 0.2, 0.35);+ let count = v.len() / FLOATS_PER_VERTEX;+ assert!(count > 0);+ let mut saw_base = false;+ let mut saw_eaves = false;+ let mut saw_ridge = false;+ for k in 0..count {+ let (p, _, _) = vertex(&v, k);+ saw_base |= p[2].to_bits() == 0.05f32.to_bits();+ saw_eaves |= p[2].to_bits() == 0.2f32.to_bits();+ saw_ridge |= p[2].to_bits() == 0.35f32.to_bits();+ assert!(+ p[2] >= 0.05 && p[2] <= 0.35,+ "shape {shape}: vertex z {z} escapes the 0.05..0.35 structural band",+ z = p[2],+ );+ }+ assert!(saw_base, "shape {shape}: no vertex sits at the exact base height");+ assert!(saw_eaves, "shape {shape}: no vertex sits at the exact eaves height");+ assert!(saw_ridge, "shape {shape}: no vertex sits at the exact ridge height");+ }+}
library/map/src/main/rust/src/tess/roof/walls.rs
diff --git a/library/map/src/main/rust/src/tess/roof/walls.rs b/library/map/src/main/rust/src/tess/roof/walls.rsindex 3a5fc70aa6..22a400e69a 100644--- a/library/map/src/main/rust/src/tess/roof/walls.rs+++ b/library/map/src/main/rust/src/tess/roof/walls.rs@@ -1,11 +1,16 @@ use super::geom::{push_tri, ring_centroid}; /// A wall quad per footprint edge, from `base` to `wall_top`, with an outward-facing normal.+///+/// Both heights are lifted by the tile-normalised ground offset sampled per corner, so each+/// wall spans the full structural height while its bottom edge sits on the slope — on flat+/// ground the two samples agree and the quad is the level rectangle it always was. pub(crate) fn emit_walls( local: &[Vec<(f32, f32)>], base: f32, wall_top: f32, rgba: u32,+ ground: &dyn Fn(f32, f32) -> f32, out_v: &mut Vec<f32>, out_i: &mut Vec<u32>, ) {@@ -35,10 +40,10 @@ pub(crate) fn emit_walls( let inv = 1.0 / (nx * nx + ny * ny).sqrt(); let normal = [nx * inv, ny * inv, 0.0]; - let base0 = [x0, y0, base];- let base1 = [x1, y1, base];- let top1 = [x1, y1, wall_top];- let top0 = [x0, y0, wall_top];+ let base0 = [x0, y0, base + ground(x0, y0)];+ let base1 = [x1, y1, base + ground(x1, y1)];+ let top1 = [x1, y1, wall_top + ground(x1, y1)];+ let top0 = [x0, y0, wall_top + ground(x0, y0)]; push_tri(out_v, out_i, base0, base1, top1, normal, rgba); push_tri(out_v, out_i, base0, top1, top0, normal, rgba); }
library/map/src/main/rust/src/tile/geometry/buildings.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/buildings.rs b/library/map/src/main/rust/src/tile/geometry/buildings.rsindex f8e977da3e..b321d032a4 100644--- a/library/map/src/main/rust/src/tile/geometry/buildings.rs+++ b/library/map/src/main/rust/src/tile/geometry/buildings.rs@@ -1,5 +1,12 @@ //! Extrude building footprints into the tile-local 3D building mesh.+//!+//! Flat 2D layers (fills, strokes) deliberately stay at z=0 over relief: draping every road+//! and boundary over the DEM would cost a heightmap sample per vertex for geometry the pitch-0+//! map draws identically, so only buildings — the one layer with real height — close the datum+//! gap against the terrain. Route and puck overlays are unaffected: they draw above the+//! basemap in their own passes, not from this mesh. use super::mesh::DEFAULT_BUILDING_HEIGHT_M;+use super::terrain::sample_ground_metres; use crate::tess::roof; use tilecodec::mamaps::body::Body; use tilecodec::mamaps::dict::LAYER_BUILDINGS;@@ -8,9 +15,17 @@ use tilecodec::mamaps::dict::LAYER_BUILDINGS; /// /// The metric heights in the side table are normalised against `ground_width_m` — the tile's own /// ground width — so the extruded height rides in the same tile-local unit the footprint does and-/// the mesh stays zoom-independent (see [`crate::tess::roof`]). A feature with no attrs (or a layer-/// with no building table) reads back a default [`BuildingAttrs`], which extrudes as a flat box at-/// [`DEFAULT_BUILDING_HEIGHT_M`].+/// A feature with no attrs (or a layer with no building table) reads back a default+/// [`BuildingAttrs`], which extrudes as a flat box at [`DEFAULT_BUILDING_HEIGHT_M`].+///+/// The walls and roof ride the tile's heightmap where it has one: every emitted `z` is its+/// structural height plus the ground offset sampled under that vertex, so a building on a+/// hillside sits on the slope instead of sinking into it or floating over the valley. The+/// offset is tile-normalised with the same `factor` as the heights (metres over this tile's+/// `ground_width_m`), and an overzoomed ancestor reuses the shared width unchanged — the two+/// stay in the same unit by construction. With no heightmap the offset is 0.0 everywhere and+/// the mesh is bit-identical to the un-lifted one; below-sea ground stays negative, so a+/// building in a depression sits below z=0 rather than clamped to it. /// /// A wall or roof the archive gives no colour keeps **0** — a transparent black that no real colour /// can collide with, since the side table already spells "absent" that way. `building.frag` reads@@ -49,6 +64,13 @@ pub(crate) fn extrude_building( let wall_colour = attrs.building_colour; let roof_colour = if attrs.roof_colour != 0 { attrs.roof_colour } else { attrs.building_colour };+ // The ground under each footprint corner, tile-normalised with the same factor as the+ // heights. Sampled per vertex inside the extruder so walls follow the slope; `None` is a+ // flat 0.0, which keeps the pitch-0 output byte-identical where the tile has no DEM.+ let heightmap = &tile.heightmap;+ let ground = |u: f32, v: f32| -> f32 {+ sample_ground_metres(heightmap, u, v).map_or(0.0, |m| (m as f64 * factor) as f32)+ }; roof::extrude( rings, extent,@@ -61,6 +83,7 @@ pub(crate) fn extrude_building( attrs.roof_orientation, wall_colour, roof_colour,+ &ground, out_v, out_i, );
library/map/src/main/rust/src/tile/geometry/terrain.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/terrain.rs b/library/map/src/main/rust/src/tile/geometry/terrain.rsindex 2a19fd7d15..f9173db72d 100644--- a/library/map/src/main/rust/src/tile/geometry/terrain.rs+++ b/library/map/src/main/rust/src/tile/geometry/terrain.rs@@ -1,7 +1,7 @@ //! The DEM-displaced ground grid for one tile. use super::mesh::{EARTH_CIRCUMFERENCE_M, TerrainMesh}; use crate::tess::terrain;-use tilecodec::mamaps::body::Body;+use tilecodec::mamaps::body::{Body, Heightmap}; /// The DEM-displaced ground grid for this tile, or an empty mesh when the tile carries no /// heightmap.@@ -19,6 +19,38 @@ pub(crate) fn terrain_mesh(tile: &Body, ground_width_m: f64) -> TerrainMesh { TerrainMesh { vertices, indices } } +/// Bilinearly sample a tile's ground elevation at tile-local `(u, v)` in 0..1, in metres+/// above sea level.+///+/// Reads [`Heightmap::metres`] (the stored sample minus the 32768 bias) at the four grid+/// samples around the point and blends them, so a building corner between DEM posts sits on+/// the slope between them rather than stepping to the nearest post. `u`/`v` are clamped to+/// `[0, 1]` and the grid edges replicate outward — the border terrain verts sit exactly on+/// the edge samples, so a building touching the tile edge meets the same ground its half of+/// the tile edge shows. Returns `None` when the tile carries no heightmap, or the map is a+/// degenerate (`dim < 2`) grid with no cell to interpolate inside.+pub(crate) fn sample_ground_metres(heightmap: &Option<Heightmap>, u: f32, v: f32) -> Option<f32> {+ let hm = heightmap.as_ref()?;+ let dim = hm.dim as usize;+ if dim < 2 {+ return None;+ }+ let u = u.clamp(0.0, 1.0);+ let v = v.clamp(0.0, 1.0);+ // Grid position in sample units: the `dim` samples sit at 0, 1/(dim-1), ..., 1.+ let gx = u * (dim as f32 - 1.0);+ let gy = v * (dim as f32 - 1.0);+ let x0 = (gx.floor() as usize).min(dim - 2);+ let y0 = (gy.floor() as usize).min(dim - 2);+ let (fx, fy) = (gx - x0 as f32, gy - y0 as f32);+ let at = |col: usize, row: usize| -> f32 {+ hm.sample(col as u16, row as u16).map_or(0.0, |s| Heightmap::metres(s) as f32)+ };+ let top = at(x0, y0) * (1.0 - fx) + at(x0 + 1, y0) * fx;+ let bottom = at(x0, y0 + 1) * (1.0 - fx) + at(x0 + 1, y0 + 1) * fx;+ Some(top * (1.0 - fy) + bottom * fy)+}+ /// Metres of ground the tile spans east–west at its centre latitude — the horizontal unit the /// building heights are normalised against, so a metre up reads the same on screen as a metre /// across. Web Mercator, matching the projection the archive was cut with.
library/map/src/main/rust/src/tile/geometry/tests_extra4.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/tests_extra4.rs b/library/map/src/main/rust/src/tile/geometry/tests_extra4.rsindex a5a3a7c270..f5b69e69ea 100644--- a/library/map/src/main/rust/src/tile/geometry/tests_extra4.rs+++ b/library/map/src/main/rust/src/tile/geometry/tests_extra4.rs@@ -1,7 +1,9 @@ use super::build::build;+use super::terrain::{sample_ground_metres, tile_ground_width_m}; use crate::style::paint::Ramp; use crate::style::{Layer, LayerKind};-use tilecodec::mamaps::body::{Body, GEOM_LINE};+use crate::tess::roof;+use tilecodec::mamaps::body::{Body, GEOM_LINE, GEOM_POLYGON, Heightmap}; // --- curved labels along roads / rivers (WS-E) ------------------------- @@ -118,3 +120,169 @@ fn an_unnamed_road_line_shapes_no_label() { let mesh = build(&body, &vec![roads_label_layer()], 14, 0, 8192, false); assert!(mesh.labels.is_empty(), "an unnamed road line shapes nothing"); }++// --- buildings sit on hills (Phase B: the datum gap) -----------------------++/// A `buildings` body with one square footprint (tile-local 0..~0.244) and the given attrs,+/// over an optional heightmap. Mirrors the `building_body` fixture in `tests_extra3`.+fn hill_building_body(+ attrs: Option<tilecodec::mamaps::body::BuildingAttrs>,+ heightmap: Option<Heightmap>,+) -> Body {+ use tilecodec::mamaps::body::{+ Feature, Layer as BodyLayer, Part, DEFAULT_EXTENT, NAME_NONE, WINDING_OUTER,+ };+ use tilecodec::mamaps::dict;+ let mut source = BodyLayer::new(dict::LAYER_BUILDINGS);+ source.parts.push(Part { coord_start: 0, point_count: 5, winding: WINDING_OUTER });+ source.coords.extend_from_slice(&[(0, 0), (1000, 0), (1000, 1000), (0, 1000), (0, 0)]);+ source.features.push(Feature {+ kind: crate::style::kind_id_for_test("building"),+ kind_detail: 0,+ geom_type: GEOM_POLYGON,+ flags: 0,+ name_idx: NAME_NONE,+ parts_offset: 0,+ part_count: 1,+ transit_color: 0,+ transit_ordinal: 0,+ transit_lanes: 0,+ transit_taper: 0,+ lane_count: 0,+ });+ Body {+ extent: DEFAULT_EXTENT,+ layers: vec![source],+ names: Vec::new(),+ ids: Vec::new(),+ turn_lanes: Vec::new(),+ buildings: match attrs {+ Some(a) => vec![(dict::LAYER_BUILDINGS, vec![a])],+ None => Vec::new(),+ },+ heightmap,+ carriageways: Vec::new(),+ convention: None,+ }+}++/// A `dim x dim` heightmap from a metres-above-sea closure, applying the +32768 bias the+/// format stores.+fn hill_heightmap(dim: u16, metres: impl Fn(u16, u16) -> i32) -> Heightmap {+ let mut samples = Vec::with_capacity((dim as usize).pow(2));+ for row in 0..dim {+ for col in 0..dim {+ samples.push((metres(col, row) + 32768) as u16);+ }+ }+ Heightmap { dim, samples }+}++/// The lowest building-vertex z in the mesh, in tile-normalised units.+fn min_building_z(mesh: &super::mesh::TileMesh) -> f32 {+ mesh.buildings+ .vertices+ .chunks(roof::FLOATS_PER_VERTEX)+ .map(|c| c[2])+ .fold(f32::MAX, f32::min)+}++#[test]+fn a_building_over_a_hill_gets_its_base_lifted() {+ use tilecodec::mamaps::body::BuildingAttrs;+ // A 400 m plateau under the whole footprint (samples 0..3 in both axes cover the+ // tile-local 0..0.244 square on a 9x9 grid), so every corner samples exactly 400 m and the+ // lowest wall vertex sits at base + 400 / ground_width — the same tile-normalised unit the+ // terrain grid uses.+ let (z, y) = (14u8, 8192u32);+ let ground = tile_ground_width_m(z, y);+ let mut body = hill_building_body(+ Some(BuildingAttrs { height: 300, ..Default::default() }),+ Some(hill_heightmap(9, |c, r| if c < 3 && r < 3 { 400 } else { 0 })),+ );+ // The footprint's far corner (1000/4096 ≈ 0.244) lands at grid 1.95, inside the plateau;+ // widen the plateau check by asserting the lift rather than the corner math.+ let mesh = build(&body, &crate::style::layers(), z, 0, y, false);+ assert!(!mesh.buildings.indices.is_empty(), "the building must still extrude");+ let want = 400.0 / ground as f32;+ let got = min_building_z(&mesh);+ assert!(+ (got - want).abs() < 1e-4,+ "the wall base rides the hill at metres/ground_width: {got} vs {want}",+ );+ body.heightmap = None;+ let flat = build(&body, &crate::style::layers(), z, 0, y, false);+ assert!(+ min_building_z(&flat).abs() < 1e-6,+ "without the hill the same building starts at z 0",+ );+}++#[test]+fn no_heightmap_leaves_structural_heights_bit_exact() {+ use tilecodec::mamaps::body::BuildingAttrs;+ // With no DEM the ground closure is 0.0, so every z must be exactly one of the structural+ // heights — base, eaves, ridge — with no offset leaking in. This is the pitch-0+ // byte-identical property as a direct assertion: any ground sample added to a vertex would+ // move its z off the structural set and fail the bit-exact compare.+ let (z, y) = (14u8, 8192u32);+ let ground = tile_ground_width_m(z, y);+ let factor = 1.0 / ground;+ let body = hill_building_body(+ Some(BuildingAttrs { height: 300, roof_height: 100, ..Default::default() }),+ None,+ );+ let mesh = build(&body, &crate::style::layers(), z, 0, y, false);+ assert!(!mesh.buildings.indices.is_empty());+ // 30 m total, 10 m of roof: base 0, eaves 20 m, ridge 30 m, tile-normalised.+ let structural =+ [0.0f32, (20.0 * factor) as f32, (30.0 * factor) as f32].map(f32::to_bits);+ for c in mesh.buildings.vertices.chunks(roof::FLOATS_PER_VERTEX) {+ assert!(+ structural.contains(&c[2].to_bits()),+ "a no-DEM vertex z {} is off the structural set — an offset leaked in",+ c[2],+ );+ }+ // And rebuilding is deterministic, so the mesh is a pure function of tile + style.+ let again = build(&body, &crate::style::layers(), z, 0, y, false);+ assert_eq!(mesh.buildings.vertices, again.buildings.vertices);+ assert_eq!(mesh.buildings.indices, again.buildings.indices);+}++#[test]+fn a_building_in_a_depression_sits_below_zero() {+ use tilecodec::mamaps::body::BuildingAttrs;+ // A -100 m basin under the footprint (the Dead Sea case): the base must come out negative+ // rather than clamped to z=0, or the building would float above the terrain grid there.+ let (z, y) = (14u8, 8192u32);+ let ground = tile_ground_width_m(z, y);+ let body = hill_building_body(+ Some(BuildingAttrs { height: 300, ..Default::default() }),+ Some(hill_heightmap(9, |c, r| if c < 3 && r < 3 { -100 } else { 0 })),+ );+ let mesh = build(&body, &crate::style::layers(), z, 0, y, false);+ assert!(!mesh.buildings.indices.is_empty());+ let got = min_building_z(&mesh);+ assert!(got < 0.0, "a below-sea base dips below z 0, got {got}");+ let want = -100.0 / ground as f32;+ assert!((got - want).abs() < 1e-4, "the base sits at metres/ground_width: {got} vs {want}");+}++#[test]+fn the_ground_sampler_bilinearly_interpolates_and_clamps() {+ // A 2x2 ramp (0, 100, 200, 300 m): the centre averages all four, a corner reads its sample+ // exactly, and out-of-range u/v clamp to the edge rather than reading past the grid.+ let hm = Some(hill_heightmap(2, |c, r| (r as i32 * 2 + c as i32) * 100));+ assert_eq!(sample_ground_metres(&hm, 0.5, 0.5), Some(150.0));+ assert_eq!(sample_ground_metres(&hm, 0.0, 0.0), Some(0.0));+ assert_eq!(sample_ground_metres(&hm, 1.0, 1.0), Some(300.0));+ assert_eq!(sample_ground_metres(&hm, -1.0, 0.0), sample_ground_metres(&hm, 0.0, 0.0));+ assert_eq!(sample_ground_metres(&hm, 2.0, 1.0), sample_ground_metres(&hm, 1.0, 1.0));+ assert_eq!(sample_ground_metres(&None, 0.5, 0.5), None);+ assert_eq!(+ sample_ground_metres(&Some(Heightmap { dim: 1, samples: vec![32768] }), 0.5, 0.5),+ None,+ "a degenerate grid has no cell to interpolate inside",+ );+}