maps: terrain specular highlight plus smoother normals
- Commit
a06186fb3e103ea6a3731e3cdbf77fce34cb8fc4- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-16 04:54 UTC (2 months ago)
- Parents
a6c075c
Diff
library/map/src/main/rust/shaders/terrain.frag
diff --git a/library/map/src/main/rust/shaders/terrain.frag b/library/map/src/main/rust/shaders/terrain.fragindex fdeeaebf1c..73367ed200 100644--- a/library/map/src/main/rust/shaders/terrain.frag+++ b/library/map/src/main/rust/shaders/terrain.frag@@ -1,19 +1,30 @@ #version 450 -// Terrain fragment: the ground colour, slope-shaded (WS-G, 3D terrain relief).+// Terrain fragment: the ground colour, slope-shaded per fragment (WS-G, 3D terrain relief). // // The base colour is the `earth` style layer's, pushed per draw (linear RGBA, palette- and-// opacity-resolved by the renderer). The vertex stage has already reduced the surface normal to a-// single scalar shade — full (1.0) at pitch 0, so the ground reads as the flat map's one colour,-// and a diffuse term once tilted so hills show relief. Blending is the pipeline's job, so the+// opacity-resolved by the renderer). The vertex stage forwards the surface normal and the+// tile-local position; lighting runs here against the same fixed north-west light as+// building.frag, so ridgelines shade sharply instead of interpolating a per-vertex scalar —+// and relief reads at pitch 0 too, where the old path forced vShade = 1.0.+//+// Over the Lambert term sits a Blinn-Phong specular: the half-vector between the view direction+// (fragment to the pushed tile-local eye in `misc.xyz`) and the light, raised to a shininess of+// 48 and scaled by 0.20. Tilted views gain a soft sun glint off facing slopes; at pitch 0 the+// specular is skipped outright (the ortho fast-path test, same as the vertex stage's), so the+// overhead map is byte-identical to the Lambert-only output. The total is clamped at 1.0 so the+// highlight tints rather than blowing out to white. Blending is the pipeline's job, so the // colour passes through with its own alpha. -layout(location = 0) in float vShade;+layout(location = 0) in vec3 vNormal;+layout(location = 1) in vec3 vTilePos; layout(push_constant) uniform Push { mat4 tileToClip; vec4 color; // the earth layer's colour, linear RGBA vec4 line;+ // xyz: the tile-local eye position (u, v in 0..1, height in tile-norm units), pushed per+ // terrain draw; w: the per-frame clock, unread on this path. vec4 misc; vec4 morph; } push;@@ -21,5 +32,21 @@ layout(push_constant) uniform Push { layout(location = 0) out vec4 outColor; void main() {- outColor = vec4(push.color.rgb * vShade, push.color.a);+ // A fixed light from above and the north-west, in tile-local space (x east, y south, z up),+ // so slopes facing it read brighter and the far sides of hills sit a shade darker.+ vec3 n = normalize(vNormal);+ vec3 lightDir = normalize(vec3(-0.4, -0.4, 1.0));+ float diffuse = max(dot(n, lightDir), 0.0);+ // Generous ambient so a shadowed slope stays legible rather than going black.+ float light = 0.55 + 0.45 * diffuse;+ // Tilted only: the ortho fast-path test (the height column's w term is 0 there). At pitch+ // 0 the eye sits far above the tile and the highlight would be a flat lift, so skip it and+ // keep the overhead map exactly the Lambert output.+ if (abs(push.tileToClip[2][3]) >= 1e-6) {+ vec3 viewDir = normalize(push.misc.xyz - vTilePos);+ vec3 h = normalize(viewDir + lightDir);+ float spec = pow(max(dot(n, h), 0.0), 48.0) * 0.20;+ light = min(light + spec, 1.0);+ }+ outColor = vec4(push.color.rgb * light, push.color.a); }
library/map/src/main/rust/shaders/terrain.vert
diff --git a/library/map/src/main/rust/shaders/terrain.vert b/library/map/src/main/rust/shaders/terrain.vertindex b5821e703f..888681b45d 100644--- a/library/map/src/main/rust/shaders/terrain.vert+++ b/library/map/src/main/rust/shaders/terrain.vert@@ -11,6 +11,11 @@ // world-px span for this frame; multiplying the two recovers the real world-px height the WS0 // perspective matrix expects in its `z` input. At pitch 0 that matrix ignores z for x/y, so the // grid reads as the flat tile footprint.+//+// Lighting runs per fragment: the normal goes out on `vNormal` and the raw tile-local position+// on `vTilePos`, so terrain.frag can shade the Lambert term and the Blinn-Phong specular against+// the tile-local eye `misc.xyz` pushes per draw — no per-vertex scalar, so ridgelines stay sharp+// however the grid is tessellated. layout(location = 0) in vec3 inPosition; // tile-local (u, v, height); u,v in 0..1 layout(location = 1) in vec3 inNormal; // surface normal in the same tile-local space@@ -26,18 +31,27 @@ layout(push_constant) uniform Push { vec4 morph; } push; -layout(location = 0) out float vShade;- // Placed just short of the far plane so, at pitch 0, the ground sits behind every building (which // write depths in [0, 0.99]) rather than in front of them — see the pitch-0 branch below. const float ORTHO_GROUND_DEPTH = 0.9995; +layout(location = 0) out vec3 vNormal;+layout(location = 1) out vec3 vTilePos;+ void main() { float worldHeight = inPosition.z * push.line.x; // The height column's w term (tileToClip[2][3]) is 0 on the ortho fast-path (pitch 0) and // -cos(pitch) once tilted — the same test the building shader uses to tell the two apart. bool ortho = abs(push.tileToClip[2][3]) < 1e-6; + // The normal in tile-local space, forwarded to the fragment stage for per-fragment Lambert+ // (mirroring building.frag). Shared by both branches so relief shades at pitch 0 too —+ // previously the ortho branch forced vShade = 1.0 and hills were invisible top-down.+ vNormal = inNormal;+ // The raw tile-local position, forwarded alongside the normal so the fragment stage can+ // build the view vector against the pushed tile-local eye for the specular term.+ vTilePos = inPosition;+ if (ortho) { // Pitch 0: the ortho matrix never lets height touch x/y, so the grid already reads as the // flat tile footprint. Feed a fixed near-far depth instead of the terrain height so the@@ -45,19 +59,10 @@ void main() { // depths near the front); the flat 2D layers are depth-off and paint over it regardless. gl_Position = push.tileToClip * vec4(inPosition.xy, 0.0, 1.0); gl_Position.z = ORTHO_GROUND_DEPTH * gl_Position.w;- // No directional shading overhead, so the ground reads as the flat map's single colour.- vShade = 1.0; } else { // Tilted: the full perspective maps a real world-px height to both the projected rise and a // depth inside the near/far range, so hills rise, occlude what is behind them, and let // buildings on the far side of a ridge be hidden by it. gl_Position = push.tileToClip * vec4(inPosition.xy, worldHeight, 1.0);- // A fixed light from above and the north-west, in tile-local space (x east, y south, z up),- // so slopes facing it read brighter and the far sides of hills sit a shade darker.- vec3 n = normalize(inNormal);- vec3 lightDir = normalize(vec3(-0.4, -0.4, 1.0));- float diffuse = max(dot(n, lightDir), 0.0);- // Generous ambient so a shadowed slope stays legible rather than going black.- vShade = 0.55 + 0.45 * diffuse; } }
library/map/src/main/rust/src/bridge/lifecycle.rs
diff --git a/library/map/src/main/rust/src/bridge/lifecycle.rs b/library/map/src/main/rust/src/bridge/lifecycle.rsindex 9fa340455e..b7a040e5a8 100644--- a/library/map/src/main/rust/src/bridge/lifecycle.rs+++ b/library/map/src/main/rust/src/bridge/lifecycle.rs@@ -99,6 +99,11 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>( let toggles = Arc::new(SharedToggles::new(LayerToggles::default())); // One `Receiver` shared by every worker, so whichever is free takes the next tile. let queue = Arc::new(Mutex::new(wanted_rx));+ // One cold-start fetch shared by every worker: the header `build_id` (one JNI round trip,+ // not one per worker) and the forced first-read revalidation (one prefix read, not one per+ // worker). See `spawn_worker`.+ let header = Arc::new(std::sync::OnceLock::new());+ let prefix_gate = Arc::new(std::sync::atomic::AtomicBool::new(false)); for index in 0..WORKER_COUNT { spawn_worker( index,@@ -110,6 +115,8 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>( online.clone(), zoom_range.clone(), toggles.clone(),+ header.clone(),+ prefix_gate.clone(), ); }
library/map/src/main/rust/src/bridge/workers.rs
diff --git a/library/map/src/main/rust/src/bridge/workers.rs b/library/map/src/main/rust/src/bridge/workers.rsindex 413033be44..a24b02bfdc 100644--- a/library/map/src/main/rust/src/bridge/workers.rs+++ b/library/map/src/main/rust/src/bridge/workers.rs@@ -20,11 +20,16 @@ use super::log::log; /// A worker: opens its own view of the archive, then serves tile requests until the queue /// closes. ///-/// Each worker holds its **own** [`MamapsArchive`], so its leaf-index cache and range-/// reads need no lock. The cost is one 16 KB header fetch per worker at startup and a-/// duplicated leaf cache; the alternative — one archive behind a mutex — would serialise-/// exactly the round trips this is meant to overlap. The on-disk range cache is shared, and-/// is safe to share because every entry is written temp-then-renamed.+/// Each worker holds its **own** [`MamapsArchive`] (and its own leaf-index cache and prefix+/// parse — small CPU work on an in-memory prefix), so its range reads need no lock. What is+/// shared across the surface's workers is everything that costs a *network round trip*: the+/// header `build_id` fetch (one JNI request per cold start, not one per worker, via `header`)+/// and the forced first-read revalidation (one prefix read, not one per worker, via+/// `prefix_gate`). The on-disk range cache is shared too, and is safe to share because every+/// entry is written temp-then-renamed.+///+/// `header`/`prefix_gate` are built once per surface in `lifecycle::create` and handed to every+/// worker: whichever worker arrives first does the fetch while the rest block on it. #[allow(clippy::too_many_arguments)] pub(crate) fn spawn_worker( index: usize,@@ -36,6 +41,8 @@ pub(crate) fn spawn_worker( online: Arc<OnlineFlag>, zoom_range: Arc<ZoomRange>, toggles: Arc<SharedToggles>,+ header: Arc<std::sync::OnceLock<Option<u64>>>,+ prefix_gate: Arc<std::sync::atomic::AtomicBool>, ) { let started = std::thread::Builder::new() .name(format!("map-tiles-{index}"))@@ -65,34 +72,44 @@ pub(crate) fn spawn_worker( } } - // Single open: the header prefix is fetched *before* the cache opens, the- // `build_id` is read out of it, and the cache opens once with the full- // origin marker — wiping on mismatch up front. No two-step reset.- let build_id = match JniRangeFetcher.fetch(&archive_url, "bytes=0-127") {- Ok(r) if r.status == 206 && r.body.len() == tilecodec::mamaps::header::HEADER_LEN => {- match Header::parse(&r.body) {- Ok(h) => h.build_id,- Err(e) => {- log(&format!("worker {index} cannot parse the mamaps header: {e}"));- return;+ // Single open: the header prefix is fetched *once per surface* (the first worker+ // fetches, the rest block on `header`), then the `build_id` is read out of it and the+ // cache opens once per worker with the full origin marker — wiping on mismatch up+ // front. No two-step reset. A failed fetch poisons the lock for every worker, so one+ // dead network kills the surface's workers once instead of logging four times.+ let build_id = *header.get_or_init(|| {+ match JniRangeFetcher.fetch(&archive_url, "bytes=0-127") {+ Ok(r)+ if r.status == 206+ && r.body.len() == tilecodec::mamaps::header::HEADER_LEN =>+ {+ match Header::parse(&r.body) {+ Ok(h) => Some(h.build_id),+ Err(e) => {+ log(&format!("cannot parse the mamaps header: {e}"));+ None+ } } }+ Ok(r) => {+ log(&format!("cannot fetch the mamaps header: HTTP {}", r.status));+ None+ }+ Err(e) => {+ log(&format!("cannot fetch the mamaps header: {e}"));+ None+ } }- Ok(r) => {- log(&format!(- "worker {index} cannot fetch the mamaps header: HTTP {}",- r.status- ));- return;- }- Err(e) => {- log(&format!("worker {index} cannot fetch the mamaps header: {e}"));- return;- }- };+ });+ let Some(build_id) = build_id else { return }; let cache = RangeCache::open(cache_dir, &basemap_origin(&archive_url, build_id), DEFAULT_MAX_BYTES);- let reader = CachingRangeReader::new(archive_url.clone(), cache, JniRangeFetcher);+ let reader = CachingRangeReader::new_shared(+ archive_url.clone(),+ cache,+ JniRangeFetcher,+ prefix_gate,+ ); reader.set_online(online.get()); let archive = match MamapsArchive::open(reader) {
library/map/src/main/rust/src/camera.rs
diff --git a/library/map/src/main/rust/src/camera.rs b/library/map/src/main/rust/src/camera.rsindex b1648cc76f..c301195baf 100644--- a/library/map/src/main/rust/src/camera.rs+++ b/library/map/src/main/rust/src/camera.rs@@ -29,8 +29,8 @@ pub const TILE_SIZE: f64 = 512.0; /// perspective's far edge is a finite ground distance), so [`Camera::screen_to_world`] /// always meets the ground plane and tile selection never has to cover an infinite /// trapezoid. `fy = d/half_h = 3` and the horizon enters the screen only past-/// `atan(fy) ≈ 71°`, so 60 leaves a margin. See [`Camera::pitch_deg`].-pub const PITCH_MAX_DEG: f64 = 60.0;+/// `atan(fy) ≈ 71°`, so 65 leaves a margin. See [`Camera::pitch_deg`].+pub const PITCH_MAX_DEG: f64 = 65.0; /// The camera as Kotlin measured it. #[derive(Clone, Copy, Debug)]
library/map/src/main/rust/src/tess/terrain.rs
diff --git a/library/map/src/main/rust/src/tess/terrain.rs b/library/map/src/main/rust/src/tess/terrain.rsindex 2a1ba80044..db5ab79179 100644--- a/library/map/src/main/rust/src/tess/terrain.rs+++ b/library/map/src/main/rust/src/tess/terrain.rs@@ -29,7 +29,10 @@ //! One vertex per heightmap sample (`dim * dim`), so the DEM is used at its own resolution with no //! resampling, and `(dim - 1)^2` quads between them. Normals come from central differences of the //! neighbouring heights (a standard heightfield normal), so a slope reads darker than a flat and-//! the relief is legible without any shadow pass. A tile whose samples are all equal (flat DEM, or+//! the relief is legible without any shadow pass. The differences read a 3×3-smoothed copy of the+//! height field — interior texels only, the border ring verbatim — so facet noise softens while+//! the two tiles sharing an edge smooth from the same edge samples and agree exactly. Positions+//! always carry the raw heights untouched. A tile whose samples are all equal (flat DEM, or //! filled sea level) produces a flat sheet with every normal pointing straight up — indistinguishable //! from the old flat ground once shading is disabled at pitch 0. @@ -38,6 +41,34 @@ use tilecodec::mamaps::body::Heightmap; /// Floats per terrain vertex: `x, y, z, nx, ny, nz`. pub const FLOATS_PER_VERTEX: usize = 6; +/// Smooth the height field for normals only: a 3×3 box blur over interior texels, with the+/// border ring copied verbatim.+///+/// The neighbour tile across a shared edge smooths from the same edge samples (it stores its own+/// copy of them, and neither side's blur kernel reaches past its own border), so the two shared+/// edge slopes — and hence the two edge normals — agree bit-for-bit: zero seam risk by+/// construction. Kept on `f32` tile-normalised heights so the test can compare pre/post blur+/// exactly, and so positions — which must stay exact — never pass through it.+fn smooth_heights(raw: &[f32], dim: usize) -> Vec<f32> {+ let mut out = raw.to_vec();+ if dim < 3 {+ // No interior texel exists (a dim-2 grid is all border), so there is nothing to blur.+ return out;+ }+ for row in 1..dim - 1 {+ for col in 1..dim - 1 {+ let mut sum = 0.0f32;+ for dr in -1..=1 {+ for dc in -1..=1 {+ sum += raw[((row as isize + dr) as usize) * dim + (col as isize + dc) as usize];+ }+ }+ out[row * dim + col] = sum / 9.0;+ }+ }+ out+}+ /// Tessellate one tile's heightmap into a relief grid, appending to `out_v`/`out_i`. /// /// `ground_width_m` is the tile's own east–west ground width in metres (see@@ -65,21 +96,35 @@ pub fn tessellate(hm: &Heightmap, ground_width_m: f64, out_v: &mut Vec<f32>, out let step = 1.0 / (dim as f32 - 1.0); let base = (out_v.len() / FLOATS_PER_VERTEX) as u32;+ // The blurred field behind the normals: central differences below read from this, so+ // per-sample DEM noise softens, while positions keep the raw `height(col, row)`. The+ // border ring is verbatim by construction, so the shared-edge slopes — and the edge+ // normals — agree bit-for-bit with the neighbour tile's.+ let smooth = {+ let mut raw = Vec::with_capacity(dim * dim);+ for row in 0..dim {+ for col in 0..dim {+ raw.push(height(col, row));+ }+ }+ smooth_heights(&raw, dim)+ };+ let shed = |col: usize, row: usize| -> f32 { smooth[row * dim + col] }; for row in 0..dim { for col in 0..dim { let u = col as f32 * step; let v = row as f32 * step; let z = height(col, row); - // Central differences, clamped at the tile edge. The spacing is the tile-normalised- // grid step, so the slope is in the same units as `z`, which keeps the normal honest- // against the height the vertex actually carries.+ // Central differences over the *smoothed* field, clamped at the tile edge. The spacing+ // is the tile-normalised grid step, so the slope is in the same units as `z`, which+ // keeps the normal honest against the height the vertex actually carries. let cl = col.saturating_sub(1); let cr = (col + 1).min(dim - 1); let ru = row.saturating_sub(1); let rd = (row + 1).min(dim - 1);- let dzdu = (height(cr, row) - height(cl, row)) / ((cr - cl) as f32 * step);- let dzdv = (height(col, rd) - height(col, ru)) / ((rd - ru) as f32 * step);+ let dzdu = (shed(cr, row) - shed(cl, row)) / ((cr - cl) as f32 * step);+ let dzdv = (shed(col, rd) - shed(col, ru)) / ((rd - ru) as f32 * step); // The upward normal of a heightfield z = f(u, v) is (-dz/du, -dz/dv, 1), normalised. let mut n = [-dzdu, -dzdv, 1.0]; let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();@@ -235,4 +280,139 @@ mod tests { "the second grid must rebase onto its own vertices", ); }++ /// Smoothing over a planar ramp must not tilt the normals: a blur of a plane is the same+ /// plane, so every normal matches the analytic slope normal exactly.+ #[test]+ fn a_planar_field_keeps_identical_normals() {+ // z = 2c + 3r metres over a 7x7 grid: interior central differences recover the slope+ // exactly, blurred or not.+ let hm = heightmap(7, |c, r| 2 * c as i32 + 3 * r as i32);+ let ground = 1000.0;+ let mut v = Vec::new();+ let mut i = Vec::new();+ tessellate(&hm, ground, &mut v, &mut i);+ // dz/du = 2 m per texel = 2 * dim-1 steps over the tile, normalised by ground width.+ let step = 1.0 / 6.0;+ let ex = -2.0 / ground as f32 / step;+ let ey = -3.0 / ground as f32 / step;+ let len = (ex * ex + ey * ey + 1.0).sqrt();+ let want = [ex / len, ey / len, 1.0 / len];+ for k in 0..v.len() / FLOATS_PER_VERTEX {+ let (p, n) = vertex(&v, k);+ // Positions stay on the raw plane.+ let col = k % 7;+ let row = k / 7;+ let z = (2 * col as i32 + 3 * row as i32) as f32 / ground as f32;+ assert!((p[2] - z).abs() < 1e-6, "position {k} must stay exact, got {}", p[2]);+ for a in 0..3 {+ assert!(+ (n[a] - want[a]).abs() < 1e-5,+ "normal {k} must match the analytic slope normal, got {n:?} want {want:?}",+ );+ }+ }+ }++ /// The point of the blur: checkerboard DEM noise must tilt interior normals far less than+ /// the raw central differences would.+ #[test]+ fn a_noisy_field_gets_softer_normals() {+ // ±40 m checkerboard over a 9x9 grid: raw central differences see a ±80 m swing per+ // texel step; the 3×3 blur averages each interior texel with its opposite-phase+ // neighbours, which must shrink the off-vertical tilt.+ let dim = 9usize;+ let amp = 40i32;+ let hm = heightmap(dim as u16, |c, r| if (c + r) % 2 == 0 { amp } else { -amp });+ let ground = 1000.0;+ let mut v = Vec::new();+ let mut i = Vec::new();+ tessellate(&hm, ground, &mut v, &mut i);+ // Raw tilt the unblurred differences would produce, at an interior vertex: dz/du over+ // one step is 2*amp metres, normalised.+ let step = 1.0 / (dim as f32 - 1.0);+ let raw_tilt = 2.0 * amp as f32 / ground as f32 / step;+ // Interior vertex one step in from the corner: its kernel mixes blurred interior with+ // the verbatim border, so the tilt shrinks but stays nonzero — the softening case,+ // rather than a fully-interior vertex whose symmetric kernel would erase it outright.+ let (_, n) = vertex(&v, dim + 1);+ let tilt = (n[0] * n[0] + n[1] * n[1]).sqrt();+ let raw_off_vertical = raw_tilt / (raw_tilt * raw_tilt + 1.0).sqrt();+ assert!(+ tilt < 0.5 * raw_off_vertical,+ "blurred tilt {tilt} must be well under the raw {raw_off_vertical}",+ );+ assert!(n[2] > 0.5, "the normal must stay mostly upright, got {n:?}");+ }++ /// The border ring passes through the blur untouched — edge differences read the raw+ /// samples, so the neighbour tile (which stores its own copy of the shared edge) derives+ /// the same slopes and the seam is invisible by construction.+ #[test]+ fn border_texels_are_bit_identical_pre_post_blur() {+ let dim = 7usize;+ let hm = heightmap(dim as u16, |c, r| (c as i32 * 13 + r as i32 * 29 + 7) % 61 - 30);+ let ground = 800.0;+ let factor = 1.0 / ground;+ let mut raw = Vec::with_capacity(dim * dim);+ for row in 0..dim {+ for col in 0..dim {+ raw.push(+ (Heightmap::metres(hm.sample(col as u16, row as u16).unwrap()) as f64 * factor)+ as f32,+ );+ }+ }+ let blurred = smooth_heights(&raw, dim);+ for k in 0..raw.len() {+ let col = k % dim;+ let row = k / dim;+ let on_border = col == 0 || row == 0 || col == dim - 1 || row == dim - 1;+ if on_border {+ assert_eq!(+ blurred[k].to_bits(),+ raw[k].to_bits(),+ "border texel ({col}, {row}) must pass through the blur untouched",+ );+ }+ }+ // And at least one interior texel must actually change, or the blur is a no-op.+ assert!(+ (1..dim - 1).any(|row| (1..dim - 1)+ .any(|col| blurred[row * dim + col].to_bits() != raw[row * dim + col].to_bits())),+ "the blur must move at least one interior texel",+ );+ }++ /// Positions and indices are the blur's non-goals: the smoothed field must never leak into+ /// either. A spiky field is the sharpest probe — raw spikes stay spiky in z, indices stay+ /// the untouched grid triangulation.+ #[test]+ fn positions_and_indices_are_untouched_by_smoothing() {+ let dim = 5u16;+ let peak_m = 300;+ let ground = 1200.0;+ let centre = dim / 2;+ let hm = heightmap(dim, |c, r| if c == centre && r == centre { peak_m } else { 0 });+ let mut v = Vec::new();+ let mut i = Vec::new();+ tessellate(&hm, ground, &mut v, &mut i);+ // The peak vertex keeps its exact raw height — smoothing the position would sink it.+ let (peak, _) = vertex(&v, centre as usize * dim as usize + centre as usize);+ assert_eq!(+ peak[2].to_bits(),+ (peak_m as f32 / ground as f32).to_bits(),+ "the peak height must be the exact raw sample",+ );+ // The untouched grid indices: two triangles per cell, the same winding as before.+ let dim32 = dim as u32;+ let mut want = Vec::new();+ for row in 0..dim - 1 {+ for col in 0..dim - 1 {+ let a = row as u32 * dim32 + col as u32;+ want.extend_from_slice(&[a, a + 1, a + dim32 + 1, a, a + dim32 + 1, a + dim32]);+ }+ }+ assert_eq!(i, want, "indices must stay the plain grid triangulation");+ } }
library/map/src/main/rust/src/tile/select/coverage.rs
diff --git a/library/map/src/main/rust/src/tile/select/coverage.rs b/library/map/src/main/rust/src/tile/select/coverage.rsindex 8b111fc241..5c0e919da7 100644--- a/library/map/src/main/rust/src/tile/select/coverage.rs+++ b/library/map/src/main/rust/src/tile/select/coverage.rs@@ -2,6 +2,16 @@ use crate::camera::{Camera, TILE_SIZE}; use super::tile_id::TileId; +/// How far past the camera centre the tilt trapezoid may reach, in viewport heights.+///+/// Under tilt the top of the screen recedes toward the horizon — at 65° the far edge is many+/// viewport-heights away — and an uncapped trapezoid enumerates an unbounded tile strip that is+/// fogged to the background colour anyway (see `FAR_FADE`). Capping the far reach keeps the+/// visible set proportional to the viewport instead of the pitch: ground past the cap is still+/// drawn (the far tiles cover it, faded) but no *extra* tiles are fetched for it. In tile units+/// the cap bites only at high pitch + low zoom, exactly where the strip would explode.+const FAR_REACH_VIEWPORTS: f64 = 6.0;+ /// The world-px axis-aligned box the viewport covers on the ground, accounting for **both** /// bearing and tilt. ///@@ -30,6 +40,15 @@ fn coverage(camera: &Camera) -> (crate::camera::WorldPx, crate::camera::WorldPx) max.y = max.y.max(p.y); } }+ // Far-distance cap: clamp the box to a radius around the camera centre so a near-horizon+ // view at high pitch enumerates a bounded strip instead of tiles to the horizon. The+ // `PITCH_MAX_DEG` cap keeps every corner finite; this keeps the *count* bounded.+ let centre = crate::camera::project(camera.center_lon, camera.center_lat, camera.zoom);+ let reach = FAR_REACH_VIEWPORTS * h.max(w);+ min.x = min.x.max(centre.x - reach);+ min.y = min.y.max(centre.y - reach);+ max.x = max.x.min(centre.x + reach);+ max.y = max.y.min(centre.y + reach); (min, max) }
library/map/src/main/rust/src/tile/source/caching.rs
diff --git a/library/map/src/main/rust/src/tile/source/caching.rs b/library/map/src/main/rust/src/tile/source/caching.rsindex e773ee9c42..33aa9d2589 100644--- a/library/map/src/main/rust/src/tile/source/caching.rs+++ b/library/map/src/main/rust/src/tile/source/caching.rs@@ -15,8 +15,11 @@ pub struct CachingRangeReader<F: RangeFetcher> { /// False until the first read of the session has gone to the network. /// /// That read is the archive header, and it is the one entry the cache must not answer from- /// itself — see the note in [`RangeReader::read`].- prefix_checked: std::sync::atomic::AtomicBool,+ /// itself — see the note in [`RangeReader::read`]. Shared across a surface's workers (see+ /// [`new_shared`](Self::new_shared)), so one cold start pays one revalidation, not one per+ /// worker: each reader used to carry its own flag, and four workers meant four forced+ /// network reads of the same prefix before any tile was fetched.+ prefix_checked: std::sync::Arc<std::sync::atomic::AtomicBool>, } impl<F: RangeFetcher> CachingRangeReader<F> {@@ -26,7 +29,25 @@ impl<F: RangeFetcher> CachingRangeReader<F> { cache, fetcher, online: std::sync::atomic::AtomicBool::new(true),- prefix_checked: std::sync::atomic::AtomicBool::new(false),+ prefix_checked: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),+ }+ }++ /// [`new`](Self::new) with a session-wide revalidation gate shared by every worker of one+ /// surface. The first read across *all* readers sharing the gate goes to the network; the+ /// rest serve from cache per the usual freshness policy.+ pub fn new_shared(+ url: impl Into<String>,+ cache: RangeCache,+ fetcher: F,+ prefix_checked: std::sync::Arc<std::sync::atomic::AtomicBool>,+ ) -> Self {+ CachingRangeReader {+ url: url.into(),+ cache,+ fetcher,+ online: std::sync::atomic::AtomicBool::new(true),+ prefix_checked, } }
library/map/src/main/rust/src/vulkan/buffers.rs
diff --git a/library/map/src/main/rust/src/vulkan/buffers.rs b/library/map/src/main/rust/src/vulkan/buffers.rsindex 7030f10b98..5a29d683a6 100644--- a/library/map/src/main/rust/src/vulkan/buffers.rs+++ b/library/map/src/main/rust/src/vulkan/buffers.rs@@ -319,3 +319,74 @@ impl ScratchBlock { fn align_up(size: vk::DeviceSize) -> vk::DeviceSize { (size + SCRATCH_ALIGN - 1) & !(SCRATCH_ALIGN - 1) }++/// Pack several same-format meshes into one vertex buffer + one index buffer.+///+/// Concatenates the vertex floats and rebases each mesh's indices by its vertex base, then+/// uploads the two results as a single pair: 2 `vkAllocateMemory` for the whole group instead+/// of 2 per mesh. A dense tile used to cost ~60-100 allocations on the Choreographer callback+/// and ~6400 live across 64 resident tiles, near the ~4096 driver hard limit; pooled by format+/// a tile costs at most 3 pairs (flat fills, stroked lines, ribbon carriageways) plus the+/// already-single buildings and terrain meshes. Returns the pair plus each mesh's `firstIndex`+/// in input order — indices are rebased to absolute, so every draw binds both buffers at+/// offset 0 and passes its `firstIndex`. `None` when there is nothing to pack, in which case+/// the caller emits no draws, exactly as the per-mesh path did for empty input.+///+/// # Safety+///+/// `device` must outlive the returned buffers, and the caller must destroy them before+/// dropping the device — the same contract as [`Buffer::upload`].+pub unsafe fn upload_packed(+ instance: &ash::Instance,+ physical_device: vk::PhysicalDevice,+ device: &ash::Device,+ stride_floats: usize,+ meshes: &[(&[f32], &[u32])],+) -> Result<Option<(Buffer, Buffer, Vec<u32>)>, String> {+ let mut total_verts = 0usize;+ let mut total_indices = 0usize;+ for (verts, indices) in meshes {+ if indices.is_empty() {+ continue;+ }+ debug_assert_eq!(verts.len() % stride_floats, 0, "vertex count must be whole");+ total_verts += verts.len();+ total_indices += indices.len();+ }+ if total_indices == 0 {+ return Ok(None);+ }+ let mut packed_verts = Vec::with_capacity(total_verts);+ let mut packed_indices = Vec::with_capacity(total_indices);+ let mut first_index = Vec::with_capacity(meshes.len());+ for (verts, indices) in meshes {+ if indices.is_empty() {+ continue;+ }+ let vertex_base = (packed_verts.len() / stride_floats) as u32;+ first_index.push(packed_indices.len() as u32);+ packed_verts.extend_from_slice(verts);+ packed_indices.extend(indices.iter().map(|i| i + vertex_base));+ }+ let vertices = Buffer::upload(+ instance,+ physical_device,+ device,+ vk::BufferUsageFlags::VERTEX_BUFFER,+ &packed_verts,+ )?;+ let indices = match Buffer::upload(+ instance,+ physical_device,+ device,+ vk::BufferUsageFlags::INDEX_BUFFER,+ &packed_indices,+ ) {+ Ok(buffer) => buffer,+ Err(e) => {+ vertices.destroy(device);+ return Err(e);+ }+ };+ Ok(Some((vertices, indices, first_index)))+}
library/map/src/main/rust/src/vulkan/pipeline/push.rs
diff --git a/library/map/src/main/rust/src/vulkan/pipeline/push.rs b/library/map/src/main/rust/src/vulkan/pipeline/push.rsindex e63ea2032e..50ce154951 100644--- a/library/map/src/main/rust/src/vulkan/pipeline/push.rs+++ b/library/map/src/main/rust/src/vulkan/pipeline/push.rs@@ -30,6 +30,11 @@ pub const NO_MARKINGS: f32 = -2.0; /// (1.0 = fully present) reserved for WS-D. Both default to a value that leaves the flat 2D /// output byte-identical (`clock` is ignored by the current shaders, `morph.x` is 1.0). ///+/// The terrain draw reuses `misc.xyz` as the tile-local eye position (`u, v` in 0..1, height in+/// tile-norm units) for its Blinn-Phong specular — those slots are dead on that path, which+/// pushes no tile-px/edge-AA/lateral values, so the reuse costs no new slot and the buildings+/// pipeline keeps the stock meaning untouched.+/// /// # The ribbon draw reads three of these slots differently /// /// [`ribbon`](Pipelines::ribbon) is a road carriageway rather than a stroke, so `gap_half_px`,
library/map/src/main/rust/src/vulkan/renderer/fog.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/fog.rs b/library/map/src/main/rust/src/vulkan/renderer/fog.rsnew file mode 100644index 0000000000..1b27895d4b--- /dev/null+++ b/library/map/src/main/rust/src/vulkan/renderer/fog.rs@@ -0,0 +1,113 @@+//! Distance fog for tilted views: haze far tiles into the background.+//!+//! Split out of `mod.rs` (which owns the colour helpers this builds on) to keep every+//! renderer file under the 500-line lint. Pure functions over the camera + tile id —+//! no GPU state, trivially testable off-device.++use crate::camera::Camera;++/// The tilt distances (in viewport heights from the camera centre) the distance fog ramps over.+///+/// At pitch 0 every drawn tile is within ~1 viewport-height, so nothing ever fogs. Tilted at+/// 65° the far trapezoid reaches the 6-viewport coverage cap in `select::coverage`; the ramp+/// ends there, so the farthest drawn tiles arrive already background-coloured and the ground+/// dissolves into haze instead of ending at a hard edge. Starts past the mid-field so the+/// readable map never hazes — only the far strip does.+const FOG_NEAR_VIEWPORTS: f64 = 2.5;+const FOG_FAR_VIEWPORTS: f64 = 6.0;++/// Distance-fog mix for one tile's draws: 0 near, rising to 1 at the far coverage cap.+///+/// Measured tile-centre to camera-centre in viewport heights, so it is zoom-independent: a+/// z14 tile at 65° and a z10 tile at 65° fog by where they sit on screen, not by their span.+/// Zero at pitch 0 (the `pitch_deg == 0.0` short-circuit keeps the flat map byte-identical)+/// and zero for anything inside the near ramp.+pub(crate) fn fog_factor(camera: &Camera, z: u8, x: u32, y: u32) -> f32 {+ if camera.pitch_deg == 0.0 {+ return 0.0;+ }+ let h = camera.height_dp.max(1.0) as f64;+ let span = camera.tile_span_dp(z);+ let centre = crate::camera::project(camera.center_lon, camera.center_lat, camera.zoom);+ let dx = (f64::from(x) + 0.5) * span - centre.x;+ let dy = (f64::from(y) + 0.5) * span - centre.y;+ ((dx.hypot(dy) / h - FOG_NEAR_VIEWPORTS) / (FOG_FAR_VIEWPORTS - FOG_NEAR_VIEWPORTS))+ .clamp(0.0, 1.0) as f32+}++/// Mix an ARGB colour toward the background by `f`: 0 is unchanged, 1 is the background.+///+/// Applied in packed space like `scale_alpha`, consistent with the renderer's existing+/// non-colour-managed math. Folds into the pushed colour, so fills *and* lines fog together+/// (unlike `morph.x`, which the line path ignores) — roads haze with the land instead of+/// staying crisp over it. Alpha mixes too: full fog is opaque haze, which is what makes the+/// far edge read as sky rather than as translucent ground.+pub(crate) fn apply_fog(argb: u32, background: u32, f: f32) -> u32 {+ if f <= 0.0 {+ return argb;+ }+ let m = |a: u32, b: u32| (a as f32 + (b as f32 - a as f32) * f).round().clamp(0.0, 255.0) as u32;+ (m(argb >> 24, background >> 24) << 24)+ | (m((argb >> 16) & 0xFF, (background >> 16) & 0xFF) << 16)+ | (m((argb >> 8) & 0xFF, (background >> 8) & 0xFF) << 8)+ | m(argb & 0xFF, background & 0xFF)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn camera(pitch: f64) -> Camera {+ Camera {+ center_lon: -122.4194,+ center_lat: 37.7749,+ zoom: 14.0,+ width_dp: 411.0,+ height_dp: 891.0,+ density: 2.0,+ bearing_deg: 0.0,+ pitch_deg: pitch,+ time_seconds: 0.0,+ }+ }++ #[test]+ fn the_flat_map_never_fogs() {+ let c = camera(0.0);+ // Even a tile at the edge of the world: pitch 0 short-circuits to zero.+ assert_eq!(fog_factor(&c, 14, 0, 0), 0.0);+ assert_eq!(fog_factor(&c, 14, 16383, 16383), 0.0);+ }++ #[test]+ fn the_centre_tile_never_fogs_when_tilted() {+ // The tile under the camera centre sits at distance ~0 viewports: inside the near+ // ramp at any pitch, so the readable map never hazes.+ let c = camera(65.0);+ let centre = crate::camera::project(c.center_lon, c.center_lat, c.zoom);+ let span = c.tile_span_dp(14);+ let x = (centre.x / span).floor() as u32;+ let y = (centre.y / span).floor() as u32;+ assert_eq!(fog_factor(&c, 14, x, y), 0.0);+ }++ #[test]+ fn a_far_tile_fogs_fully_at_max_tilt() {+ // Six viewport-heights north of the centre: past the far ramp end, so full fog.+ let c = camera(65.0);+ let centre = crate::camera::project(c.center_lon, c.center_lat, c.zoom);+ let span = c.tile_span_dp(14);+ let far = centre.y - 6.0 * c.height_dp as f64;+ let ty = (far / span).floor().max(0.0) as u32;+ let tx = (centre.x / span).floor().max(0.0) as u32;+ assert_eq!(fog_factor(&c, 14, tx, ty), 1.0);+ }++ #[test]+ fn fog_mixes_toward_the_background() {+ assert_eq!(apply_fog(0xFF00_0000, 0xFFFF_FFFF, 0.0), 0xFF00_0000);+ assert_eq!(apply_fog(0xFF00_0000, 0xFFFF_FFFF, 1.0), 0xFFFF_FFFF);+ // Halfway red-to-white is half-grey, opaque throughout.+ assert_eq!(apply_fog(0xFFFF_0000, 0xFFFF_FFFF, 0.5), 0xFFFF_8080);+ }+}
library/map/src/main/rust/src/vulkan/renderer/mod.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/mod.rs b/library/map/src/main/rust/src/vulkan/renderer/mod.rsindex 6d89481e30..a65b333100 100644--- a/library/map/src/main/rust/src/vulkan/renderer/mod.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/mod.rs@@ -9,6 +9,7 @@ use crate::vulkan::buffers::Buffer; use ash::vk; use std::collections::HashMap; +mod fog; mod frame; mod mod_extra; mod placement;@@ -27,11 +28,15 @@ pub use mod_extra::Renderer; const FRAMES_IN_FLIGHT: usize = 2; /// One layer's geometry, resident on the GPU.+///+/// The mesh lives in its format pool on the tile ([`ResidentTile::flat`] for fills,+/// [`ResidentTile::lines`] for strokes) and this names its slice: indices are rebased to+/// absolute at upload, so every draw binds the pool at offset 0 and passes+/// [`first_index`](Self::first_index). struct LayerBuffers { layer_index: usize, kind: LayerKind,- vertices: Buffer,- indices: Buffer,+ first_index: u32, index_count: u32, /// Set when the mesh carries its own colour — see /// [`geometry::LayerMesh::color_override`].@@ -41,10 +46,24 @@ struct LayerBuffers { } /// One tile's geometry, resident on the GPU.+///+/// Same-format meshes share one vertex + one index buffer (see+/// [`upload_packed`](crate::vulkan::buffers::upload_packed)): 2 `vkAllocateMemory` per pool+/// instead of 2 per mesh. A dense tile used to cost ~60-100 allocations on the Choreographer+/// callback and ~6400 live across 64 resident tiles, near the ~4096 driver hard limit; pooled+/// it costs at most 3 pairs (flat fills, stroked lines, ribbon carriageways) plus the+/// already-single buildings and terrain meshes. struct ResidentTile {+ /// Position-only 2-float fills: every `LayerKind::Fill` mesh plus the region-mask shapes.+ flat: Option<(Buffer, Buffer)>,+ /// 7-float stroked lines: every `LayerKind::Line` mesh plus the live-traffic segments.+ lines: Option<(Buffer, Buffer)>,+ /// 6-float ribbon carriageways, one per distinct road-shape push set.+ ribbons: Option<(Buffer, Buffer)>, layers: Vec<LayerBuffers>, /// The tile's extruded 3D buildings, or `None` below z14 / where the tile has none. Drawn in /// its own depth-tested pass ([`Renderer::record_buildings`]), not the flat layer loop.+ /// One combined mesh per tile, so this keeps its own buffer pair — nothing to pool. buildings: Option<BuildingBuffers>, /// The tile's DEM-displaced ground grid, or `None` where the tile carries no heightmap. Drawn /// in its own depth-tested pass ([`Renderer::record_terrain`]) before the flat layer loop; a@@ -90,29 +109,27 @@ struct ResidentTile { /// One live-traffic component segment, on the GPU. ///-/// The line pipeline's own vertex format, so it draws exactly like a road — the only thing-/// that differs is the colour, which is looked up from [`Renderer::traffic_colors`] by-/// [`id`](Self::id) at draw time rather than coming from a style layer.+/// The geometry lives in the tile's [`lines`](ResidentTile::lines) pool; this names its slice.+/// Drawn exactly like a road — the only thing that differs is the colour, looked up from+/// [`Renderer::traffic_colors`] by [`id`](Self::id) at draw time rather than from a style layer. struct TrafficBuffers { /// The segment's `component_id`, the key into the pushed colour table. id: u64,- vertices: Buffer,- indices: Buffer,+ first_index: u32, index_count: u32, }- /// One tile's carriageway surface for one set of road-shape inputs, on the GPU. ///-/// The three shape fields are push constants rather than vertex attributes, which is why they key-/// the mesh split: every road in the tile that agrees on all three shares this draw.+/// The geometry lives in the tile's [`ribbons`](ResidentTile::ribbons) pool; this names its+/// slice. The three shape fields are push constants rather than vertex attributes, which is why+/// they key the mesh split: every road in the tile that agrees on all three shares this draw. struct CarriagewayBuffers { /// Index into the style's layer list, for the asphalt colour and the lane width ramp. layer_index: usize, lanes: u8, split: f32, oneway: bool,- vertices: Buffer,- indices: Buffer,+ first_index: u32, index_count: u32, } @@ -139,11 +156,13 @@ struct TerrainBuffers { } /// One region's tessellated shape within one tile, on the GPU.+///+/// The geometry lives in the tile's [`flat`](ResidentTile::flat) pool; this names its slice.+/// `rings`/`area`/`level` stay on the CPU for [`Renderer::region_at`]. struct RegionBuffers { /// The OSM relation this piece came from, matched against the selected region. id: u64,- vertices: Buffer,- indices: Buffer,+ first_index: u32, index_count: u32, /// Exterior rings in tile-local 0..1, kept on the CPU for [`Renderer::region_at`]. rings: Vec<Vec<(f32, f32)>>,@@ -174,7 +193,7 @@ type AcceptSet = HashMap<u64, (bool, u32)>; /// Floats are compared as bit patterns rather than by value. This is an identity test — "is this /// the same camera the last accept-set was computed from" — and not a question about numeric /// closeness, so bits are both the correct comparison and the one that needs no epsilon.-#[derive(PartialEq, Eq)]+#[derive(PartialEq, Eq, Clone)] struct PlacementKey { center_lon: u64, center_lat: u64,
library/map/src/main/rust/src/vulkan/renderer/placement.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/placement.rs b/library/map/src/main/rust/src/vulkan/renderer/placement.rsindex 900e4572ba..edfbbb2732 100644--- a/library/map/src/main/rust/src/vulkan/renderer/placement.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/placement.rs@@ -9,6 +9,20 @@ use ash::vk; use std::cmp::Reverse; use std::collections::HashMap; use std::ops::RangeInclusive;+use std::time::Instant;++/// How long a collision answer may be reused while the camera moves.+///+/// The placer is quadratic in accepted boxes plus per-glyph box projection for every curved+/// label — all of it on the Choreographer callback. During a pan a frame lands every ~16 ms+/// with a slightly moved camera, so re-placing every frame is what the panning jank is made+/// of. Within this window a moved camera reuses the last accept-set (labels hold their+/// relative order; boxes are still re-projected per frame in `refresh_placed`, so what draws+/// tracks the camera and only the *collision outcome* lags). Past it — or on any non-center+/// change (zoom, bearing, pitch, tiles, layers, filter) — the pass re-runs. A tap during the+/// window picks against boxes projected for the current frame, so hit-testing never lags.+/// hit-testing never lags.+pub(super) const PLACE_REUSE_MS: u128 = 300; impl Renderer { /// The region whose shape covers this point at the requested administrative level.@@ -100,10 +114,18 @@ impl Renderer { .collect(), layers: layers.len(), };- if let Some((cached, accepted)) = self.placement_cache.borrow().as_ref() {+ if let Some((cached, accepted, at)) = self.placement_cache.borrow().as_ref() { if *cached == key { return accepted.clone(); }+ // Same everything but the centre: a pan in progress. Reuse the last accept-set+ // for a short window rather than re-running the quadratic pass every frame.+ let mut moved = cached.clone();+ moved.center_lon = key.center_lon;+ moved.center_lat = key.center_lat;+ if moved == key && at.elapsed().as_millis() < PLACE_REUSE_MS {+ return accepted.clone();+ } } let mut candidates: Vec<placement::SegmentedCandidate> = Vec::new(); let camera_z = camera.zoom.floor().clamp(0.0, 22.0) as u8;@@ -213,7 +235,7 @@ impl Renderer { .enumerate() .map(|(order, (id, flipped))| (id, (flipped, order as u32))) .collect();- *self.placement_cache.borrow_mut() = Some((key, accepted.clone()));+ *self.placement_cache.borrow_mut() = Some((key, accepted.clone(), Instant::now())); accepted }
library/map/src/main/rust/src/vulkan/renderer/rebuild.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/rebuild.rs b/library/map/src/main/rust/src/vulkan/renderer/rebuild.rsindex a23ace9fd7..67a6405912 100644--- a/library/map/src/main/rust/src/vulkan/renderer/rebuild.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/rebuild.rs@@ -45,17 +45,18 @@ impl Drop for Renderer { unsafe { let _ = self.context.device.device_wait_idle(); for tile in self.tiles.values() {- for layer in &tile.layers {- layer.vertices.destroy(&self.context.device);- layer.indices.destroy(&self.context.device);+ // Draw slices are plain indices into the pools — each pool is one pair.+ if let Some((v, i)) = &tile.flat {+ v.destroy(&self.context.device);+ i.destroy(&self.context.device); }- for region in &tile.regions {- region.vertices.destroy(&self.context.device);- region.indices.destroy(&self.context.device);+ if let Some((v, i)) = &tile.lines {+ v.destroy(&self.context.device);+ i.destroy(&self.context.device); }- for road in &tile.carriageways {- road.vertices.destroy(&self.context.device);- road.indices.destroy(&self.context.device);+ if let Some((v, i)) = &tile.ribbons {+ v.destroy(&self.context.device);+ i.destroy(&self.context.device); } if let Some(buildings) = &tile.buildings { buildings.vertices.destroy(&self.context.device);@@ -68,17 +69,17 @@ impl Drop for Renderer { } self.tiles.clear(); for (_, tile) in &self.retiring {- for layer in &tile.layers {- layer.vertices.destroy(&self.context.device);- layer.indices.destroy(&self.context.device);+ if let Some((v, i)) = &tile.flat {+ v.destroy(&self.context.device);+ i.destroy(&self.context.device); }- for region in &tile.regions {- region.vertices.destroy(&self.context.device);- region.indices.destroy(&self.context.device);+ if let Some((v, i)) = &tile.lines {+ v.destroy(&self.context.device);+ i.destroy(&self.context.device); }- for road in &tile.carriageways {- road.vertices.destroy(&self.context.device);- road.indices.destroy(&self.context.device);+ if let Some((v, i)) = &tile.ribbons {+ v.destroy(&self.context.device);+ i.destroy(&self.context.device); } if let Some(buildings) = &tile.buildings { buildings.vertices.destroy(&self.context.device);
library/map/src/main/rust/src/vulkan/renderer/record_extra.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/record_extra.rs b/library/map/src/main/rust/src/vulkan/renderer/record_extra.rsindex 31f7c027ad..14319576de 100644--- a/library/map/src/main/rust/src/vulkan/renderer/record_extra.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/record_extra.rs@@ -3,6 +3,7 @@ use super::{ PUCK_CONE_HALF_STROKE_DP, PUCK_DOT_DP, PUCK_QUAD_DP, PUCK_RIM_DP, QUAD_INDICES, Renderer, SCRIM_COLOR, TRAFFIC_WIDTH_DP, UserPuck, anchors_for, argb_to_rgba, scale_alpha, };+use super::fog::{apply_fog, fog_factor}; use crate::camera::Camera; use crate::marker::{Marker, MARKER_SIZE_DP}; use crate::style::paint::Stroke;@@ -39,6 +40,7 @@ impl Renderer { layers: &[Layer], palette: Palette, ordered: &[u64],+ clear: u32, submitted: &mut usize, ) { let device = &self.context.device;@@ -50,6 +52,11 @@ impl Renderer { if tile.carriageways.is_empty() { continue; }+ // The ribbon pool, bound at offset 0; each road draws its slice by firstIndex.+ let Some((pool_v, pool_i)) = tile.ribbons.as_ref().map(|(v, i)| (v.buffer, i.buffer))+ else {+ continue;+ }; let tile_to_clip = camera.tile_to_clip(tile.z, tile.x, tile.y); let tile_span_px = camera.tile_span_px(tile.z); let yellow = f32::from(tile.yellow_centre);@@ -76,8 +83,13 @@ impl Renderer { bound = true; } // The asphalt only. The markings are the shader's own palette, because they have- // to match the white it antialiases them against.- let asphalt = scale_alpha(layer.color(palette), layer.opacity_at(camera.zoom));+ // to match the white it antialiases them against. Distance-fogged like the+ // flat layers so carriageways haze with the ground under tilt.+ let asphalt = apply_fog(+ scale_alpha(layer.color(palette), layer.opacity_at(camera.zoom)),+ clear,+ fog_factor(camera, tile.z, tile.x, tile.y),+ ); // A lane connector carries no paint. An intersection is not marked out into // lanes on the ground, and a connector is drawn in the carriageway's own colour, // so its markings would be the only part of it with any contrast against the road@@ -111,14 +123,14 @@ impl Renderer { 0, push.as_bytes(), );- device.cmd_bind_vertex_buffers(command_buffer, 0, &[road.vertices.buffer], &[0]);+ device.cmd_bind_vertex_buffers(command_buffer, 0, &[pool_v], &[0]); device.cmd_bind_index_buffer( command_buffer,- road.indices.buffer,+ pool_i, 0, vk::IndexType::UINT32, );- device.cmd_draw_indexed(command_buffer, road.index_count, 1, 0, 0, 0);+ device.cmd_draw_indexed(command_buffer, road.index_count, 1, road.first_index, 0, 0); *submitted += 1; } }@@ -270,12 +282,16 @@ impl Renderer { /// opacity for this zoom — the same colour the flat earth fill would have used — pushed once and /// shared by every tile. `line.x` carries the tile's world-px span, the scale that turns the /// mesh's tile-normalised heights into the world-px height the WS0 matrix's `z` input expects.+ /// Distance-fogged per tile toward the background like the flat layers (buildings keep their+ /// per-vertex colours and are deliberately not fogged — no shader change for a z14+-only+ /// layer whose tiles sit inside the near ramp anyway). pub(super) unsafe fn record_terrain( &self, command_buffer: vk::CommandBuffer, camera: &Camera, layers: &[Layer], palette: Palette,+ clear: u32, submitted: &mut usize, ) { let Some(earth) =@@ -287,7 +303,8 @@ impl Renderer { if opacity <= 0.0 { return; }- let colour = argb_to_rgba(scale_alpha(earth.color(palette), opacity));+ let unfogged = argb_to_rgba(scale_alpha(earth.color(palette), opacity));+ let fog_rgb = argb_to_rgba(clear); let device = &self.context.device; let mut bound = false; for tile in self.tiles.values() {@@ -300,12 +317,46 @@ impl Renderer { ); bound = true; }+ // Same fog as the flat layers, mixed one step later (linear floats rather than+ // packed ARGB — same ramp, rounding apart). Per tile: far ground hazes out.+ let f = fog_factor(camera, tile.z, tile.x, tile.y);+ let colour = [+ unfogged[0] + (fog_rgb[0] - unfogged[0]) * f,+ unfogged[1] + (fog_rgb[1] - unfogged[1]) * f,+ unfogged[2] + (fog_rgb[2] - unfogged[2]) * f,+ unfogged[3] + (fog_rgb[3] - unfogged[3]) * f,+ ];+ // Tile-local eye for the terrain specular, derived the way `fog_factor` derives+ // its tile geometry: camera centre in world px (`project`, at the camera zoom)+ // minus the tile origin, over the span (`tile_span_dp`). Tile u/v are world axes+ // normalised, so no bearing rotation enters — the matrix already owns that.+ let span = camera.tile_span_dp(tile.z);+ let (eye_u, eye_v, eye_h) = if span > 0.0 {+ let centre = crate::camera::project(camera.center_lon, camera.center_lat, camera.zoom);+ (+ ((centre.x - f64::from(tile.x) * span) / span) as f32,+ ((centre.y - f64::from(tile.y) * span) / span) as f32,+ ((1.5 * f64::from(camera.height_dp)) / span) as f32,+ )+ } else {+ (0.5, 0.5, 1.0e4)+ }; let push = Push { tile_to_clip: camera.tile_to_clip(tile.z, tile.x, tile.y), color: colour, // `line.x`: the tile's world-px span, the tile-norm-height -> world-px scale. line: [camera.tile_span_dp(tile.z) as f32, 0.0, 0.0, 0.0],- misc: [0.0, 0.0, 0.0, camera.time_seconds],+ // `misc.xyz`: the tile-local eye for the Blinn-Phong specular — the camera+ // centre in world px minus the tile origin, over the span, so u/v land in+ // 0..1 (off-tile when the centre is elsewhere, which is fine: the view+ // vector stays well-defined). Eye height is the MapLibre-like eye distance+ // (1.5 viewport-heights, the `d` behind `Camera::perspective`) in the same+ // tile-norm units as the mesh heights, so `eye - frag` is a true direction+ // in tile space. At pitch 0 the fragment shader skips the specular outright,+ // so this only ever steers tilted highlights. A degenerate span falls back+ // to far-above-centre, where the view vector is straight down and the+ // highlight collapses to ~0.+ misc: [eye_u, eye_v, eye_h, camera.time_seconds], morph: MORPH_NONE, }; device.cmd_push_constants(
library/map/src/main/rust/src/vulkan/renderer/record_extra2.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/record_extra2.rs b/library/map/src/main/rust/src/vulkan/renderer/record_extra2.rsindex 063b4d95cf..700883c7e8 100644--- a/library/map/src/main/rust/src/vulkan/renderer/record_extra2.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/record_extra2.rs@@ -50,6 +50,11 @@ impl Renderer { if tile.traffic.is_empty() { continue; }+ // The line pool, bound at offset 0; each segment draws its slice by firstIndex.+ let Some((pool_v, pool_i)) = tile.lines.as_ref().map(|(v, i)| (v.buffer, i.buffer))+ else {+ continue;+ }; let tile_to_clip = camera.tile_to_clip(tile.z, tile.x, tile.y); let tile_span_px = camera.tile_span_px(tile.z); for segment in &tile.traffic {@@ -80,14 +85,14 @@ impl Renderer { 0, push.as_bytes(), );- device.cmd_bind_vertex_buffers(command_buffer, 0, &[segment.vertices.buffer], &[0]);+ device.cmd_bind_vertex_buffers(command_buffer, 0, &[pool_v], &[0]); device.cmd_bind_index_buffer( command_buffer,- segment.indices.buffer,+ pool_i, 0, vk::IndexType::UINT32, );- device.cmd_draw_indexed(command_buffer, segment.index_count, 1, 0, 0, 0);+ device.cmd_draw_indexed(command_buffer, segment.index_count, 1, segment.first_index, 0, 0); *submitted += 1; } }@@ -111,6 +116,12 @@ impl Renderer { let mut any = false; for tile in self.tiles.values() {+ // The flat pool, bound at offset 0; each region piece draws its slice by+ // firstIndex.+ let Some((pool_v, pool_i)) = tile.flat.as_ref().map(|(v, i)| (v.buffer, i.buffer))+ else {+ continue;+ }; for region in tile.regions.iter().filter(|r| r.id == selected) { if !any { device.cmd_bind_pipeline(@@ -137,16 +148,16 @@ impl Renderer { device.cmd_bind_vertex_buffers( command_buffer, 0,- &[region.vertices.buffer],+ &[pool_v], &[0], ); device.cmd_bind_index_buffer( command_buffer,- region.indices.buffer,+ pool_i, 0, vk::IndexType::UINT32, );- device.cmd_draw_indexed(command_buffer, region.index_count, 1, 0, 0, 0);+ device.cmd_draw_indexed(command_buffer, region.index_count, 1, region.first_index, 0, 0); *submitted += 1; } }
library/map/src/main/rust/src/vulkan/renderer/upload.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/upload.rs b/library/map/src/main/rust/src/vulkan/renderer/upload.rsindex 1607f4193f..19a4a34606 100644--- a/library/map/src/main/rust/src/vulkan/renderer/upload.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/upload.rs@@ -1,8 +1,7 @@ use super::{ BuildingBuffers, CarriagewayBuffers, FRAMES_IN_FLIGHT, LayerBuffers, RegionBuffers,- Renderer, ResidentTile, RouteBuffers, TerrainBuffers, TrafficBuffers, TransientBuffers,+ Renderer, ResidentTile, TerrainBuffers, TrafficBuffers, };-use crate::overlay::RouteMesh; use crate::tile::geometry::TileMesh; use crate::tile::select; use crate::vulkan::buffers::Buffer;@@ -12,219 +11,157 @@ use ash::vk; use std::collections::HashSet; impl Renderer {- /// Draw `mesh` as the navigation route, or take the route away with `None`.++ /// Upload a tile's geometry, replacing anything already resident for it. ///- /// Pure state: a route arrives once and then does not change, so it has- /// no business being an argument on [`render`](Self::render). Old buffers- /// retire through the frames-in-flight grace queue; on upload failure the- /// route is left cleared rather than half-set.- pub fn set_route(&mut self, mesh: Option<&RouteMesh>) -> Result<(), String> {- if let Some(previous) = self.route.take() {- self.transients.push(TransientBuffers {- vbuf: previous.vertices,- ibuf: previous.indices,- frames: FRAMES_IN_FLIGHT,- });+ /// Same-format meshes share one vertex + one index buffer per pool (see+ /// [`upload_packed`](crate::vulkan::buffers::upload_packed)): fills (+ the region-mask+ /// shapes, which are position-only fills) in [`flat`](ResidentTile::flat), strokes (+ the+ /// traffic segments, which ride the stroke vertex) in [`lines`](ResidentTile::lines), and+ /// ribbon carriageways in [`ribbons`](ResidentTile::ribbons). Buildings and terrain are+ /// already one mesh per tile and keep their own pair. A dense tile costs ~5 allocations+ /// instead of ~60-100, on the same Choreographer callback as before.+ pub fn upload(&mut self, key: u64, mesh: &TileMesh) -> Result<(), String> {+ use crate::style::LayerKind;+ use crate::tess::{fill, ribbon, stroke};+ use crate::vulkan::buffers::upload_packed;+ let instance = &self.context.instance;+ let physical = self.context.physical_device;+ let device = &self.context.device;+ // Fills and region shapes share the position-only flat pool; collect which flat mesh+ // each belongs to so the draw slices line up with the packed order below.+ let mut flat_meshes: Vec<(&[f32], &[u32])> = Vec::new();+ let mut flat_region_at: Vec<usize> = Vec::new();+ let mut flat_layer_at: Vec<usize> = Vec::new();+ for layer_mesh in &mesh.meshes {+ if layer_mesh.kind != LayerKind::Fill || layer_mesh.indices.is_empty() {+ continue;+ }+ flat_layer_at.push(flat_meshes.len());+ flat_meshes.push((&layer_mesh.vertices, &layer_mesh.indices)); }- let Some(mesh) = mesh else { return Ok(()) };- if mesh.indices.is_empty() {- return Ok(());+ for region in &mesh.regions {+ flat_region_at.push(flat_meshes.len());+ flat_meshes.push((®ion.vertices, ®ion.indices)); }- // SAFETY: uploading fresh GPU buffers; the old ones retired above.- let buffers = unsafe { self.upload_route_buffers(mesh)? };- self.route = Some(buffers);- Ok(())- }-- /// Draw `mesh` as the pack-driven rail-lines overlay, or take it away- /// with `None`. Same mesh, grace queue and cleared-on-failure contract- /// as [`set_route`](Self::set_route); a frame does nothing but draw.- pub fn set_rail_lines(&mut self, mesh: Option<&RouteMesh>) -> Result<(), String> {- if let Some(previous) = self.rail_lines.take() {- self.transients.push(TransientBuffers {- vbuf: previous.vertices,- ibuf: previous.indices,- frames: FRAMES_IN_FLIGHT,- });+ // Strokes and traffic segments share the 7-float stroke pool.+ let mut line_meshes: Vec<(&[f32], &[u32])> = Vec::new();+ let mut line_layer_at: Vec<usize> = Vec::new();+ let mut line_traffic_at: Vec<usize> = Vec::new();+ for layer_mesh in &mesh.meshes {+ if layer_mesh.kind != LayerKind::Line || layer_mesh.indices.is_empty() {+ continue;+ }+ line_layer_at.push(line_meshes.len());+ line_meshes.push((&layer_mesh.vertices, &layer_mesh.indices)); }- let Some(mesh) = mesh else { return Ok(()) };- if mesh.indices.is_empty() {- return Ok(());+ for segment in &mesh.traffic {+ if segment.indices.is_empty() {+ continue;+ }+ line_traffic_at.push(line_meshes.len());+ line_meshes.push((&segment.vertices, &segment.indices)); }- // SAFETY: uploading fresh GPU buffers; the old ones retired above.- let buffers = unsafe { self.upload_route_buffers(mesh)? };- self.rail_lines = Some(buffers);- Ok(())- }- /// Upload a [`RouteMesh`] into GPU [`RouteBuffers`], shared by the route- /// and rail-lines slots. On failure the vertices are destroyed and the- /// slot stays cleared rather than half-set.- ///- /// # Safety: call only after retiring the slot's previous buffers — a- /// command buffer submitted last frame may still be reading them.- unsafe fn upload_route_buffers(&self, mesh: &RouteMesh) -> Result<RouteBuffers, String> {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- &mesh.vertices,- )?;- let indices = match Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- &mesh.indices,- ) {- Ok(buffer) => buffer,- Err(e) => {- vertices.destroy(&self.context.device);- return Err(e);+ let mut ribbon_meshes: Vec<(&[f32], &[u32])> = Vec::new();+ for road in &mesh.carriageways {+ if road.indices.is_empty() {+ continue; }+ ribbon_meshes.push((&road.vertices, &road.indices));+ }+ // SAFETY: uploading fresh GPU buffers for a tile whose previous buffers (if any)+ // are retired below, after every buffer below has landed.+ let flat = unsafe {+ upload_packed(instance, physical, device, fill::FLOATS_PER_VERTEX, &flat_meshes)? };- Ok(RouteBuffers {- placement: mesh.placement,- vertices,- indices,- index_count: mesh.indices.len() as u32,- segments: mesh.segments.clone(),- })- }-- /// Upload a tile's geometry, replacing anything already resident for it.- pub fn upload(&mut self, key: u64, mesh: &TileMesh) -> Result<(), String> {- let mut layers = Vec::with_capacity(mesh.meshes.len());+ let lines = unsafe {+ upload_packed(instance, physical, device, stroke::FLOATS_PER_VERTEX, &line_meshes)?+ };+ let ribbons = unsafe {+ upload_packed(+ instance,+ physical,+ device,+ ribbon::FLOATS_PER_VERTEX,+ &ribbon_meshes,+ )?+ };+ let mut flat_layer_iter = flat_layer_at.iter();+ let mut line_layer_iter = line_layer_at.iter();+ let mut layers: Vec<LayerBuffers> = Vec::with_capacity(mesh.meshes.len()); for layer_mesh in &mesh.meshes { if layer_mesh.indices.is_empty() { continue; }- unsafe {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- &layer_mesh.vertices,- )?;- let indices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- &layer_mesh.indices,- )?;- layers.push(LayerBuffers {- layer_index: layer_mesh.layer_index,- kind: layer_mesh.kind,- vertices,- indices,- index_count: layer_mesh.indices.len() as u32,- color_override: layer_mesh.color_override,- lane: layer_mesh.lane,- });- }+ // The `*_at` vectors parallel their pool's mesh order: the nth fill-kind mesh is+ // the nth entry of the flat pool's first-index list, and likewise for lines.+ let first_index = match layer_mesh.kind {+ LayerKind::Fill => {+ let Some(at) = flat_layer_iter.next() else { continue };+ let Some((_, _, first)) = flat.as_ref() else { continue };+ first[*at]+ }+ LayerKind::Line => {+ let Some(at) = line_layer_iter.next() else { continue };+ let Some((_, _, first)) = lines.as_ref() else { continue };+ first[*at]+ }+ LayerKind::Symbol => continue,+ };+ layers.push(LayerBuffers {+ layer_index: layer_mesh.layer_index,+ kind: layer_mesh.kind,+ first_index,+ index_count: layer_mesh.indices.len() as u32,+ color_override: layer_mesh.color_override,+ lane: layer_mesh.lane,+ }); }+ let flat_first: Vec<u32> = flat.as_ref().map(|(_, _, f)| f.clone()).unwrap_or_default();+ let line_first: Vec<u32> =+ lines.as_ref().map(|(_, _, f)| f.clone()).unwrap_or_default(); let mut regions = Vec::with_capacity(mesh.regions.len());- for region in &mesh.regions {- unsafe {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- ®ion.vertices,- )?;- let indices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- ®ion.indices,- )?;- regions.push(RegionBuffers {- id: region.id,- vertices,- indices,- index_count: region.indices.len() as u32,- rings: region.rings.clone(),- area: region.area,- level: region.level,- });- }+ for (n, region) in mesh.regions.iter().enumerate() {+ let Some(&first_index) = flat_first.get(flat_region_at[n]) else { continue };+ regions.push(RegionBuffers {+ id: region.id,+ first_index,+ index_count: region.indices.len() as u32,+ rings: region.rings.clone(),+ area: region.area,+ level: region.level,+ }); } let mut traffic = Vec::with_capacity(mesh.traffic.len());- for segment in &mesh.traffic {+ for (n, segment) in mesh.traffic.iter().enumerate() { if segment.indices.is_empty() { continue; }- unsafe {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- &segment.vertices,- )?;- let indices = match Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- &segment.indices,- ) {- Ok(buffer) => buffer,- Err(e) => {- vertices.destroy(&self.context.device);- return Err(e);- }- };- traffic.push(TrafficBuffers {- id: segment.id,- vertices,- indices,- index_count: segment.indices.len() as u32,- });- }+ let Some(&first_index) = line_first.get(line_traffic_at[n]) else { continue };+ traffic.push(TrafficBuffers {+ id: segment.id,+ first_index,+ index_count: segment.indices.len() as u32,+ }); }- // The tile's road carriageways: one mesh per distinct road shape, uploaded like the- // traffic segments above.+ let ribbon_first: Vec<u32> =+ ribbons.as_ref().map(|(_, _, f)| f.clone()).unwrap_or_default(); let mut carriageways = Vec::with_capacity(mesh.carriageways.len());+ let mut ri = 0usize; for road in &mesh.carriageways { if road.indices.is_empty() { continue; }- unsafe {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- &road.vertices,- )?;- let indices = match Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- &road.indices,- ) {- Ok(buffer) => buffer,- Err(e) => {- vertices.destroy(&self.context.device);- return Err(e);- }- };- carriageways.push(CarriagewayBuffers {- layer_index: road.layer_index,- lanes: road.lanes,- split: road.split,- oneway: road.oneway,- vertices,- indices,- index_count: road.indices.len() as u32,- });- }+ let Some(&first_index) = ribbon_first.get(ri) else { continue };+ ri += 1;+ carriageways.push(CarriagewayBuffers {+ layer_index: road.layer_index,+ lanes: road.lanes,+ split: road.split,+ oneway: road.oneway,+ first_index,+ index_count: road.indices.len() as u32,+ }); } // The tile's 3D buildings, if any: one combined mesh, uploaded like the rest. let buildings = if mesh.buildings.indices.is_empty() {@@ -291,6 +228,9 @@ impl Renderer { } }; let tile = ResidentTile {+ flat: flat.map(|(v, i, _)| (v, i)),+ lines: lines.map(|(v, i, _)| (v, i)),+ ribbons: ribbons.map(|(v, i, _)| (v, i)), layers, buildings, terrain,@@ -383,21 +323,19 @@ impl Renderer { return true; } unsafe {- for layer in &tile.layers {- layer.vertices.destroy(device);- layer.indices.destroy(device);- }- for region in &tile.regions {- region.vertices.destroy(device);- region.indices.destroy(device);+ // Draw slices are plain indices into the pools — nothing per draw to free.+ // Each pool is one pair no matter how many meshes packed into it.+ if let Some((v, i)) = &tile.flat {+ v.destroy(device);+ i.destroy(device); }- for segment in &tile.traffic {- segment.vertices.destroy(device);- segment.indices.destroy(device);+ if let Some((v, i)) = &tile.lines {+ v.destroy(device);+ i.destroy(device); }- for road in &tile.carriageways {- road.vertices.destroy(device);- road.indices.destroy(device);+ if let Some((v, i)) = &tile.ribbons {+ v.destroy(device);+ i.destroy(device); } if let Some(buildings) = &tile.buildings { buildings.vertices.destroy(device);