maps: suppress connector markings; add carriageway taper scaffolding
- Commit
d2fbc8c00ae75fbe66f9fdfc462063f1794a2665- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-10 18:59 UTC (2 months ago)
- Parents
0536ee3
Diff
library/map/src/main/rust/shaders/road_surface.frag
diff --git a/library/map/src/main/rust/shaders/road_surface.frag b/library/map/src/main/rust/shaders/road_surface.fragindex 596ed5b0f6..b0114b07e5 100644--- a/library/map/src/main/rust/shaders/road_surface.frag+++ b/library/map/src/main/rust/shaders/road_surface.frag@@ -53,6 +53,20 @@ layout(push_constant) uniform Push { // Mirrors `style::paint::MIN_HALF_WIDTH_PX`; must match `road_surface.vert`. const float MIN_HALF_WIDTH_PX = 0.5; +// A `line.z` below this means "paint no markings on this ribbon at all". A real centre-line+// `t` is an across-road coordinate bounded to [-1, +1], so no road can reach it; the+// renderer pushes exactly -2.0 (`pipeline::NO_MARKINGS`). The threshold sits halfway+// between the two so neither side depends on the exact value.+//+// It exists for the lane connectors through a junction. Real road paint stops at the stop+// line and resumes on the far side — an intersection is not marked out into lanes — so a+// connector carrying edge lines is not merely noisy, it is wrong. And it is *only* noise:+// a connector is drawn in the same colour as the carriageway it continues, so where it+// overlies the road its asphalt contributes nothing and its markings are the entire+// visible ribbon. Twelve of those per junction read as a tangle of hairlines rather than+// as road surface.+const float NO_MARKINGS_BELOW = -1.5;+ // A painted marking is about 0.15 m in a lane about 3.5 m wide. Held as a fraction of the // lane rather than an absolute width so it stays a ground measurement across zooms. const float MARK_WIDTH_LANES = 0.045;@@ -96,7 +110,7 @@ void main() { clamp((lanePx - MARK_FADE_START_PX) / (MARK_FADE_FULL_PX - MARK_FADE_START_PX), 0.0, 1.0); vec3 rgb = push.color.rgb;- if (legible > 0.0) {+ if (legible > 0.0 && push.line.z > NO_MARKINGS_BELOW) { float markHalfPx = max(lanePx * MARK_WIDTH_LANES * 0.5, MIN_MARK_HALF_PX); bool oneway = push.line.w >= 0.5; float centreT = push.line.z;
library/map/src/main/rust/src/tess/ribbon.rs
diff --git a/library/map/src/main/rust/src/tess/ribbon.rs b/library/map/src/main/rust/src/tess/ribbon.rsindex 67b4c1f585..ad32bf3f2e 100644--- a/library/map/src/main/rust/src/tess/ribbon.rs+++ b/library/map/src/main/rust/src/tess/ribbon.rs@@ -26,6 +26,34 @@ //! place on the carriageway is the same number at every zoom. The geometry is a //! function of the tile alone. //!+//! # A taper is a ratio, and a ratio is not a width+//!+//! Where a road's lane count changes, two abutting sections are two features with two+//! lane counts, so the renderer draws them as two meshes at two half-widths and the+//! carriageway steps. Removing that step means the width has to vary *along* the road,+//! which reads like the invariant above forbids it. It does not, and the distinction is+//! the whole of [`Taper`]: what the invariant rules out is a **screen measurement** in a+//! vertex, because that is what a zoom step changes. A dimensionless ratio — this+//! vertex carries a road four fifths as wide as the push constant says — is not a screen+//! measurement, and a zoom step does not touch it.+//!+//! It needs no new attribute either, because the normal is already not a unit vector:+//! [`join_normal`] lengthens it by the miter factor, and the vertex shader multiplies by+//! it without ever assuming a length. So a taper is that same normal scaled a second+//! time, and the vertex stays six floats, the push constant stays a push constant, and+//! `road_surface.vert` is untouched.+//!+//! Both sides of a transition scale toward a width derived from the *node* rather than+//! from either section (see [`crate::tile::taper`]), so they cannot arrive at it+//! disagreeing. The step is not detected and corrected; it is unrepresentable.+//!+//! What this does **not** move is the lane markings: `lanes` and the centre-line `t` are+//! still per-mesh push constants, so through a taper the shader squeezes the section's+//! own lane count into a narrowing road rather than wedging one lane out, and the centre+//! line converges on the narrow section's without exactly meeting it. Both would need a+//! seventh float — still dimensionless, still invariant-safe — and neither is the step+//! the eye actually catches.+//! //! # Joins //! //! Miter joins and butt caps, computed and clamped exactly as the stroke path does, and@@ -40,17 +68,89 @@ use super::stroke::MITER_LIMIT; /// Floats per vertex: `x, y, nx, ny, t, distance`. pub const FLOATS_PER_VERTEX: usize = 6; -/// Tessellate one carriageway part.+/// How much narrower the carriageway is at each end of a part than along its middle.+///+/// `start` and `end` are ratios in `(0, 1]` against this part's *own* width: `1.0` is+/// full width and `0.5` is half of it, because the section this end runs into carries+/// half the lanes. `run` is how far back from that end the ramp reaches, in the same+/// tile-local `0..1` units the emitted positions use.+///+/// A ratio and a ground length, never a pixel: see the module docs on why that is what+/// lets the width stay a push constant.+#[derive(Debug, Clone, Copy, PartialEq)]+pub struct Taper {+ start: f32,+ end: f32,+ run: f32,+}++impl Taper {+ /// A part that abuts nothing of a different width — the whole of the junction+ /// connector path, and the overwhelming majority of roads.+ pub const NONE: Taper = Taper { start: 1.0, end: 1.0, run: 0.0 };++ /// Clamped on the way in, so a ratio outside `(0, 1]` — which would invert the road+ /// or collapse it to nothing — cannot reach the tessellator to be checked for later.+ ///+ /// A taper that ramps to full width at both ends *is* [`NONE`](Taper::NONE) and is+ /// returned as it, so "this part does not taper" has one spelling rather than one per+ /// run length it happened to be offered.+ pub fn new(start: f32, end: f32, run: f32) -> Taper {+ let (start, end) = (ratio(start), ratio(end));+ if start >= 1.0 && end >= 1.0 {+ return Taper::NONE;+ }+ Taper { start, end, run: if run > 0.0 { run } else { 0.0 } }+ }++ /// Whether this taper would change any vertex. A `run` of zero cannot ramp.+ fn is_flat(self) -> bool {+ self.run <= 0.0+ }+}++/// A width ratio, held strictly positive so a taper can never produce a zero-width or+/// inside-out carriageway. The floor is one 255th because the narrowest a real ratio can+/// be is one lane against the 255 a `u8` lane count admits.+fn ratio(value: f32) -> f32 {+ if value.is_finite() {+ value.clamp(1.0 / 255.0, 1.0)+ } else {+ 1.0+ }+}++/// Tessellate one carriageway part at a uniform width. /// /// `coords` is flat `[x0, y0, ...]` in tile coordinates; `extent` is the layer's /// extent, so positions come out in 0..1 and the renderer needs no per-layer scale. /// Indices are relative to the first vertex already in `vertices`. pub fn ribbon(coords: &[i32], extent: u32, vertices: &mut Vec<f32>, indices: &mut Vec<u32>) {- let points = dedupe(coords);- let n = points.len() / 2;- if n < 2 {+ ribbon_tapered(coords, extent, Taper::NONE, vertices, indices);+}++/// As [`ribbon`], but ramping to a neighbouring section's width at either end.+///+/// The ramp is applied to the join normal, which the vertex shader already treats as a+/// length rather than a direction, so nothing about the vertex format or the push+/// constants changes. A vertex is inserted where each ramp begins: without one, the+/// ramp would run from whatever vertex the simplifier happened to leave, and a straight+/// half-kilometre of road would taper over its whole length.+pub fn ribbon_tapered(+ coords: &[i32],+ extent: u32,+ taper: Taper,+ vertices: &mut Vec<f32>,+ indices: &mut Vec<u32>,+) {+ let mut points = dedupe(coords);+ if points.len() / 2 < 2 { return; }+ // `taper.run` is in the same 0..1 units as the output; the points are still in+ // extent units, so the ramp has to be measured in those.+ let widths = taper_widths(&mut points, taper, taper.run * extent as f32);+ let n = points.len() / 2; let scale = 1.0 / extent as f32; let base = (vertices.len() / FLOATS_PER_VERTEX) as u32;@@ -58,6 +158,9 @@ pub fn ribbon(coords: &[i32], extent: u32, vertices: &mut Vec<f32>, indices: &mu for i in 0..n { let (nx, ny) = join_normal(&points, n, i);+ // Empty for an untapered part, which is nearly all of them, so the common path+ // pays one bounds check and multiplies by nothing.+ let width = widths.get(i).copied().unwrap_or(1.0); if i > 0 { // Scaled with the positions: the dash and marking-repeat patterns are@@ -71,8 +174,8 @@ pub fn ribbon(coords: &[i32], extent: u32, vertices: &mut Vec<f32>, indices: &mu let py = points[i * 2 + 1] as f32 * scale; // Tile y grows downward, so the perpendicular `(-dy, dx)` points to the right // of travel — the `-1` vertex is the left kerb, as a driver would name it.- vertices.extend_from_slice(&[px, py, nx, ny, -1.0, distance]);- vertices.extend_from_slice(&[px, py, nx, ny, 1.0, distance]);+ vertices.extend_from_slice(&[px, py, nx * width, ny * width, -1.0, distance]);+ vertices.extend_from_slice(&[px, py, nx * width, ny * width, 1.0, distance]); } // Two triangles per segment, wound as the stroke path winds them so face culling@@ -83,6 +186,101 @@ pub fn ribbon(coords: &[i32], extent: u32, vertices: &mut Vec<f32>, indices: &mu } } +/// The width ratio at each point, inserting the vertices the ramps need as it goes.+///+/// Empty when there is no taper, which the caller reads as one everywhere rather than+/// paying a vector per part for the case that is nearly every part.+fn taper_widths(points: &mut Vec<i32>, taper: Taper, run: f32) -> Vec<f32> {+ if taper.is_flat() {+ return Vec::new();+ }+ let lengths = cumulative(points);+ let Some(&total) = lengths.last() else { return Vec::new() };+ // Half the part at most, so the two ramps meet in the middle rather than crossing+ // and inverting. A section shorter than two ramps tapers over all of it.+ let run = run.min(total * 0.5);+ if run <= 0.0 {+ return Vec::new();+ }++ let mut wanted: Vec<f32> = Vec::new();+ if taper.end < 1.0 {+ wanted.push(total - run);+ }+ if taper.start < 1.0 {+ wanted.push(run);+ }+ // Two ramps that meet share the vertex they meet on. Inserting one for each would+ // put two coincident points in the line, and a zero-length segment has no direction+ // — the NaN `dedupe` exists to prevent, reintroduced after it has already run.+ if wanted.len() == 2 && (wanted[0] - wanted[1]).abs() < MIN_SPLIT_GAP {+ wanted.pop();+ }+ // Furthest along first: its insertion cannot move the index the nearer one was+ // measured at, so both are computed against the original line and applied in turn.+ let splits: Vec<(usize, i32, i32)> =+ wanted.iter().filter_map(|&along| split_at(points, &lengths, along)).collect();+ for (at, x, y) in splits {+ points.splice(at * 2..at * 2, [x, y]);+ }++ // Re-measured, because rounding an inserted point to integer tile units moves it a+ // fraction off the line it was cut from and so changes the length it sits on.+ let lengths = cumulative(points);+ let total = lengths.last().copied().unwrap_or(0.0);+ lengths+ .iter()+ .map(|&along| ramp(along, run, taper.start).min(ramp(total - along, run, taper.end)))+ .collect()+}++/// How near an existing point a ramp's own vertex may be inserted, in tile units.+///+/// The inserted point is rounded to integer tile units, so nearer than this and rounding+/// could land it exactly on its neighbour, where [`dedupe`] has already run and would not+/// drop it again; nearer than a whole unit and [`direction`] would be normalising a+/// sub-unit segment, which the connector path relies on never happening.+const MIN_SPLIT_GAP: f32 = 1.5;++/// The ratio at a point `along` past the end that ramps to `at_end`: exactly `at_end` on+/// the end itself, exactly one from `run` onwards.+fn ramp(along: f32, run: f32, at_end: f32) -> f32 {+ let fraction = (along / run).clamp(0.0, 1.0);+ at_end + (1.0 - at_end) * fraction+}++/// Where a vertex has to be inserted to put one at arc length `at`, as+/// `(index it goes before, x, y)` — or nothing when a vertex is already close enough.+///+/// "Close enough" is [`MIN_SPLIT_GAP`].+fn split_at(points: &[i32], lengths: &[f32], at: f32) -> Option<(usize, i32, i32)> {+ let after = (1..lengths.len()).find(|&i| lengths[i] >= at)?;+ let before = after - 1;+ let span = lengths[after] - lengths[before];+ if span <= 0.0 || at - lengths[before] < MIN_SPLIT_GAP || lengths[after] - at < MIN_SPLIT_GAP {+ return None;+ }+ let fraction = (at - lengths[before]) / span;+ let x = points[before * 2] as f32+ + fraction * (points[after * 2] - points[before * 2]) as f32;+ let y = points[before * 2 + 1] as f32+ + fraction * (points[after * 2 + 1] - points[before * 2 + 1]) as f32;+ Some((after, x.round() as i32, y.round() as i32))+}++/// Arc length from the first point to each point, in tile units.+fn cumulative(points: &[i32]) -> Vec<f32> {+ let n = points.len() / 2;+ let mut out = Vec::with_capacity(n);+ let mut total = 0.0;+ out.push(0.0);+ for i in 1..n {+ total += segment_length(points, i - 1, i);+ out.push(total);+ }+ out+}+ /// The normal at point `i`: unit at the ends, a clamped miter in between. fn join_normal(points: &[i32], n: usize, i: usize) -> (f32, f32) { let before = if i > 0 { Some(direction(points, i - 1, i)) } else { None };@@ -322,4 +520,184 @@ mod tests { assert!((distance(&v, 2) - 3.0).abs() < 1e-6, "300 tile units at extent 100"); assert!((distance(&v, 4) - 7.0).abs() < 1e-6, "plus 400 more"); }++ /// The kerb offset the vertex shader lands on, in tile-local units, for the push+ /// constant `half_width`. Everything below asserts on this rather than on the raw+ /// normal, because it is what actually reaches a pixel.+ fn kerb_offset(v: &[f32], i: usize, half_width: f32) -> f32 {+ let (x, y) = shade(v, i, 1.0, half_width);+ ((x - at(v, i, 0)).powi(2) + (y - at(v, i, 1)).powi(2)).sqrt()+ }++ #[test]+ fn no_taper_is_byte_identical_to_the_untapered_path() {+ // The overwhelming majority of parts, and the whole of the junction connector+ // path. A ratio of one must not perturb a single float.+ let line = [0, 0, 300, 0, 300, 400, 700, 400];+ let (mut plain_v, mut plain_i) = (Vec::new(), Vec::new());+ ribbon(&line, 4096, &mut plain_v, &mut plain_i);+ let (mut none_v, mut none_i) = (Vec::new(), Vec::new());+ ribbon_tapered(&line, 4096, Taper::NONE, &mut none_v, &mut none_i);+ assert_eq!(plain_v, none_v);+ assert_eq!(plain_i, none_i);++ // And a taper whose ratios are both one is the same thing however long its run.+ let (mut flat_v, mut flat_i) = (Vec::new(), Vec::new());+ ribbon_tapered(&line, 4096, Taper::new(1.0, 1.0, 0.05), &mut flat_v, &mut flat_i);+ assert_eq!(plain_v, flat_v);+ assert_eq!(plain_i, flat_i);+ }++ #[test]+ fn a_tapered_end_is_exactly_the_ratio_and_the_far_end_is_untouched() {+ // The property the whole design rests on: the narrow end is *exactly* the+ // neighbour's width, not nearly it, so two sections meeting there cannot leave+ // a step between them.+ let mut v = Vec::new();+ // 1000 units long at extent 1000, so tile-local length is 1.0 and a run of 0.2+ // is 200 units.+ ribbon_tapered(&[0, 0, 1000, 0], 1000, Taper::new(0.5, 1.0, 0.2), &mut v, &mut Vec::new());+ let last = v.len() / FLOATS_PER_VERTEX - 1;+ assert!((kerb_offset(&v, 0, 40.0) - 20.0).abs() < 1e-5, "start is half width");+ assert!((kerb_offset(&v, last, 40.0) - 40.0).abs() < 1e-5, "end is full width");+ }++ #[test]+ fn the_ramp_reaches_full_width_at_the_run_and_stays_there() {+ let mut v = Vec::new();+ ribbon_tapered(&[0, 0, 1000, 0], 1000, Taper::new(0.5, 1.0, 0.2), &mut v, &mut Vec::new());+ let n = v.len() / FLOATS_PER_VERTEX;+ assert_eq!(n, 6, "a vertex was inserted where the ramp ends");+ // The inserted point is at 200 units along, which is 0.2 in tile-local units.+ assert!((position_x(&v, 2) - 0.2).abs() < 1e-5, "at {}", position_x(&v, 2));+ assert!((kerb_offset(&v, 2, 40.0) - 40.0).abs() < 1e-5, "full width from the run on");+ }++ #[test]+ fn a_taper_narrows_monotonically_and_never_inverts_the_road() {+ let mut v = Vec::new();+ ribbon_tapered(+ &[0, 0, 250, 0, 500, 0, 750, 0, 1000, 0],+ 1000,+ Taper::new(0.25, 0.5, 0.3),+ &mut v,+ &mut Vec::new(),+ );+ let n = v.len() / FLOATS_PER_VERTEX;+ let widths: Vec<f32> = (0..n).step_by(2).map(|i| kerb_offset(&v, i, 40.0)).collect();+ assert!(widths.iter().all(|w| *w > 0.0), "a zero width draws nothing: {widths:?}");+ assert!(widths.iter().all(|w| *w <= 40.0 + 1e-5), "never wider than the push: {widths:?}");+ assert!((widths[0] - 10.0).abs() < 1e-5, "start quarter width: {}", widths[0]);+ let end = widths.len() - 1;+ assert!((widths[end] - 20.0).abs() < 1e-5, "end half width: {}", widths[end]);+ // Rising away from the start, falling toward the end: no bulge in between.+ let peak = widths.iter().cloned().fold(f32::MIN, f32::max);+ assert!((peak - 40.0).abs() < 1e-5, "the middle reaches full width: {widths:?}");+ }++ #[test]+ fn a_taper_leaves_t_on_the_kerbs_so_the_markings_still_span_the_road() {+ // `road_surface.frag` places every marking against `t`. If a taper moved it the+ // dividers would drift off the asphalt exactly where the road is changing.+ let mut v = Vec::new();+ ribbon_tapered(+ &[0, 0, 400, 0, 400, 400],+ 4096,+ Taper::new(0.4, 0.6, 0.02),+ &mut v,+ &mut Vec::new(),+ );+ let n = v.len() / FLOATS_PER_VERTEX;+ for i in 0..(n / 2) {+ assert_eq!(across(&v, i * 2), -1.0, "left kerb is exactly -1");+ assert_eq!(across(&v, i * 2 + 1), 1.0, "right kerb is exactly +1");+ }+ }++ #[test]+ fn a_tapered_marking_still_survives_a_width_change() {+ // The invariant the module exists to protect, re-asserted *through* a taper: a+ // ratio is not a screen measurement, so a zoom step still needs no+ // re-tessellation.+ let mut v = Vec::new();+ ribbon_tapered(&[0, 0, 1000, 0], 1000, Taper::new(0.5, 1.0, 0.2), &mut v, &mut Vec::new());+ let divider = -1.0 / 3.0;+ let fraction = |vertex: usize, half_width: f32| {+ let (lx, ly) = shade(&v, vertex, -1.0, half_width);+ let (rx, ry) = shade(&v, vertex + 1, 1.0, half_width);+ let (mx, my) = shade(&v, vertex, divider, half_width);+ let span = ((rx - lx).powi(2) + (ry - ly).powi(2)).sqrt();+ ((mx - lx).powi(2) + (my - ly).powi(2)).sqrt() / span+ };+ for vertex in [0, 2] {+ let narrow = fraction(vertex, 2.5);+ let wide = fraction(vertex, 37.0);+ assert!((narrow - wide).abs() < 1e-5, "vertex {vertex}: {narrow} vs {wide}");+ assert!((narrow - (divider + 1.0) / 2.0).abs() < 1e-5);+ }+ }++ #[test]+ fn two_ramps_longer_than_the_part_meet_instead_of_crossing() {+ // A section shorter than two taper runs — a slip lane between two changes. The+ // ends must still be exact and nothing in between may invert.+ let mut v = Vec::new();+ ribbon_tapered(&[0, 0, 100, 0], 1000, Taper::new(0.5, 0.25, 0.4), &mut v, &mut Vec::new());+ let n = v.len() / FLOATS_PER_VERTEX;+ let last = n - 1;+ assert!((kerb_offset(&v, 0, 40.0) - 20.0).abs() < 1e-5);+ assert!((kerb_offset(&v, last, 40.0) - 10.0).abs() < 1e-5);+ for i in 0..n {+ let w = kerb_offset(&v, i, 40.0);+ assert!(w > 0.0 && w <= 40.0 + 1e-5, "vertex {i} width {w}");+ }+ }++ #[test]+ fn a_ramp_that_lands_on_an_existing_vertex_inserts_nothing() {+ // The guard the connector path relies on: `dedupe` drops exact duplicates and+ // `direction` normalises segments of at least one tile unit, so a split point+ // within rounding distance of a vertex must not be inserted at all.+ let mut v = Vec::new();+ // A run of 0.2 at extent 1000 is 200 units, which is exactly the second point.+ ribbon_tapered(&[0, 0, 200, 0, 1000, 0], 1000, Taper::new(0.5, 1.0, 0.2), &mut v, &mut Vec::new());+ assert_eq!(v.len() / FLOATS_PER_VERTEX, 6, "three points, no fourth inserted");+ assert!((kerb_offset(&v, 2, 40.0) - 40.0).abs() < 1e-5, "and it is the full-width point");+ }++ #[test]+ fn every_float_of_a_tapered_ribbon_is_finite() {+ for taper in [+ Taper::new(0.5, 0.5, 0.25),+ Taper::new(1.0 / 255.0, 1.0, 0.5),+ Taper::new(0.5, 0.5, 10.0),+ Taper::new(f32::NAN, -3.0, f32::NEG_INFINITY),+ ] {+ for line in [+ &[0, 0, 100, 0][..],+ &[0, 0, 1, 0, 1, 1, 2, 1][..],+ &[0, 0, 1000, 0, 0, 10][..],+ &[0, 0, 100, 0, 0, 0][..],+ ] {+ let mut v = Vec::new();+ ribbon_tapered(line, 4096, taper, &mut v, &mut Vec::new());+ for (i, f) in v.iter().enumerate() {+ assert!(f.is_finite(), "float {i} is {f} for {taper:?} on {line:?}");+ }+ }+ }+ }++ #[test]+ fn a_ratio_outside_the_unit_range_cannot_be_constructed() {+ // Clamped at the constructor rather than checked at the tessellator: a zero+ // ratio draws nothing and a negative one turns the road inside out, and neither+ // should be a state the caller can hand over to be caught later.+ assert_eq!(Taper::new(2.0, 1.5, 0.1), Taper::new(1.0, 1.0, 0.1));+ assert!(Taper::new(0.0, -1.0, 0.1).start > 0.0);+ assert!(Taper::new(0.0, -1.0, 0.1).end > 0.0);+ assert_eq!(Taper::new(f32::NAN, f32::INFINITY, 0.1), Taper::new(1.0, 1.0, 0.1));+ assert!(Taper::new(0.5, 0.5, -1.0).is_flat(), "a negative run cannot ramp");+ assert!(Taper::NONE.is_flat());+ } }
library/map/src/main/rust/src/tile/geometry.rs
diff --git a/library/map/src/main/rust/src/tile/geometry.rs b/library/map/src/main/rust/src/tile/geometry.rsindex 20d13cb92b..7432a4e55c 100644--- a/library/map/src/main/rust/src/tile/geometry.rs+++ b/library/map/src/main/rust/src/tile/geometry.rs@@ -15,6 +15,7 @@ use crate::tess::{fill, ribbon, roof, stroke, terrain}; use crate::tile::arrow::{self, ArrowInstance}; use crate::tile::symbol; use crate::tile::select::ANCESTOR_DEPTH;+use crate::tile::taper; use tilecodec::mamaps::body::{Body, GEOM_LINE, GEOM_POINT, GEOM_POLYGON}; use tilecodec::mamaps::dict::{ LAYER_BUILDINGS, LAYER_EARTH, LAYER_JUNCTION, LAYER_ROADS, LAYER_TRAFFIC,@@ -467,20 +468,7 @@ pub fn build_toggled( (1, true, 0.0) } else { let oneway = feature.is_oneway();- // Most roads carry no `lanes` tag at all, and a zero lane count would- // push a zero width and draw nothing. OSM's own reading of an untagged- // road is one lane each way, which is also what makes the centre line- // appear.- let lanes = match feature.lane_count {- 0 => {- if oneway {- 1- } else {- 2- }- }- count => count,- };+ let lanes = taper::carriageway_lanes(feature.lane_count, oneway); let split = split_t(tile, layer, feature_index, lanes, left_hand); (lanes, oneway, split) };@@ -680,6 +668,14 @@ fn terrain_mesh(tile: &Body, ground_width_m: f64) -> TerrainMesh { /// actually carries — the extra lane going to the forward direction — and runs it through the same /// arithmetic as a known one. On an even count that still comes out at 0.0, and it is what real /// data gives anyway: a three-lane two-way road is tagged 2/1, not "centred".+///+/// # Its counterpart is the arrow fan+///+/// That no-table assumption is made a second time, independently, in [`arrow_meshes`] — which fans+/// each direction's arrows over the very boundary this line is painted on. **The two are+/// counterparts and have to be changed together.** If one starts assuming a different split and+/// the other does not, the arrows detach from the centre line on exactly the archives that carry+/// no table, which is the case with no third source to catch the disagreement. fn split_t(tile: &Body, layer: &Layer, feature_index: usize, lanes: u8, left_hand: bool) -> f32 { let (forward, backward) = known_split(tile, layer.source_layer_id, feature_index) .unwrap_or_else(|| {@@ -695,8 +691,9 @@ fn split_t(tile: &Body, layer: &Layer, feature_index: usize, lanes: u8, left_han /// /// The single read of that table. [`split_t`] puts the centre line at the boundary it implies and /// [`arrow_meshes`] fans each direction's arrows over its own side of that same boundary; reading-/// it once means the marking and the arrows cannot disagree about where the road divides. They-/// differ only in what they assume when it is absent, which is a judgement each makes for itself.+/// it once means the marking and the arrows cannot disagree about where the road divides. Where it+/// is absent the two synthesise a split separately instead, and those syntheses are counterparts+/// that have to be kept in step — see the note on [`split_t`]. fn known_split(tile: &Body, layer_id: u8, feature_index: usize) -> Option<(u16, u16)> { tile.feature_carriageway(layer_id, feature_index) .map(|shape| (shape.forward as u16, shape.backward as u16))@@ -745,20 +742,14 @@ fn arrow_meshes(tile: &Body, z: u8, left_hand: bool) -> Vec<ArrowInstance> { } // How the road divides, from the same table the centre line is placed from, so an arrow // and the marking beside it cannot disagree about which lanes belong to which direction.- // Absent that, the same fallback the ribbon and `split_t` use — an untagged road is one- // lane each way, or one lane for a one-way, and an odd count gives the extra lane forward.+ // Absent that, this synthesises a split and so does `split_t`: the two are counterparts+ // and must be changed together, or the arrows come away from the centre line on precisely+ // the archives that carry no table. They agree on every two-way road. They differ only for+ // a one-way — all lanes forward here, an even division there — and that is harmless solely+ // because a one-way carriageway draws no centre line for the split to be wrong about. // Not read off the mask lists, which describe only the lanes that carry a turn indication. let oneway = feature.is_oneway();- let lanes = match feature.lane_count {- 0 => {- if oneway {- 1- } else {- 2- }- }- count => count,- };+ let lanes = taper::carriageway_lanes(feature.lane_count, oneway); let lanes_each_way = known_split(tile, LAYER_ROADS, index).unwrap_or_else(|| { let lanes = u16::from(lanes); if oneway {@@ -1667,6 +1658,47 @@ mod tests { ); } + /// **What makes the `NO_MARKINGS` sentinel safe.** The renderer signals "paint no markings on+ /// this ribbon" by pushing -2.0 into `Push.line.z`, the slot that otherwise carries the+ /// centre-line split. That is only sound because a real split is an across-road coordinate and+ /// so cannot leave `[-1, +1]` — a road that ever pushed a value below -1.5 would silently lose+ /// its lane markings.+ ///+ /// `vulkan/` is `#[cfg(target_os = "android")]`, so the sentinel itself is not reachable from a+ /// host test. This pins the half that is: the producer side, over every shape a road can take,+ /// including the lopsided splits that push furthest toward a kerb.+ #[test]+ fn a_roads_split_can_never_reach_the_no_markings_sentinel() {+ use tilecodec::mamaps::body::{Carriageway, MarkingConvention};++ let mut worst: f32 = 0.0;+ for left_hand in [false, true] {+ for lanes in 1..=12u8 {+ // The unknown-split path, which is what every archive takes today.+ let mut body = carriageway_body(&[(lanes, false), (lanes, true)]);+ body.convention = Some(MarkingConvention { left_hand, yellow_centre: false });+ for mesh in build(&body, carriageway_only(), 16, 0, 0, false).carriageways {+ worst = worst.max(mesh.split.abs());+ }+ // And every tagged division of those lanes, including all-forward and+ // all-backward, which are the extremes that land the split on a kerb.+ for forward in 0..=lanes {+ let shape = Carriageway {+ forward,+ backward: lanes - forward,+ solid_dividers: 0,+ };+ worst = worst.max(split_for(lanes, shape).abs());+ }+ }+ }+ assert!(+ worst <= 1.0,+ "a road pushed a split of {worst}, outside the +/-1 an across-road coordinate can \+ take; anything past -1.5 would be read as the no-markings sentinel",+ );+ }+ /// Turn arrows are produced from the archive's turn-lane table at high zoom and gated off /// below it: a road with `turn:lanes` yields one arrow per marked lane, pointing along the /// road, and none when the tile is too coarse.
library/map/src/main/rust/src/tile/mod.rs
diff --git a/library/map/src/main/rust/src/tile/mod.rs b/library/map/src/main/rust/src/tile/mod.rsindex bc772d34ce..8172a0c077 100644--- a/library/map/src/main/rust/src/tile/mod.rs+++ b/library/map/src/main/rust/src/tile/mod.rs@@ -13,3 +13,4 @@ pub mod select; pub mod source; pub mod sprite; pub mod symbol;+pub mod taper;
library/map/src/main/rust/src/tile/taper.rs
diff --git a/library/map/src/main/rust/src/tile/taper.rs b/library/map/src/main/rust/src/tile/taper.rsnew file mode 100644index 0000000000..90f6bdf1ae--- /dev/null+++ b/library/map/src/main/rust/src/tile/taper.rs@@ -0,0 +1,466 @@+//! Where one section of road runs into another that carries a different number of lanes.+//!+//! # The defect+//!+//! [`crate::coalesce`]'s merge key includes `lane_count`, so a road whose lane count+//! changes arrives as two features. [`crate::tile::geometry`] gives each its own+//! [`CarriagewayMesh`](crate::tile::geometry::CarriagewayMesh) and+//! `Renderer::record_carriageways` pushes each a half-width of+//! `lane width x lanes / 2`. **A mesh has exactly one width.** So where a four-lane+//! section abuts a two-lane one the carriageway steps, and nothing connects the old+//! lanes to the new — a hard shoulder-step mid-road.+//!+//! # Why the fix is here and not in the tiler+//!+//! Because a mesh has exactly one width, no geometry the tiler could emit removes the+//! step; a transition feature would be drawn flat like every other and would only turn+//! one step into two. The tiler also knows nothing extra: `coalesce_lines_with_ids` runs+//! on an already-clipped, already-tile-local layer, which is the same view this module+//! has. And the one structure in the build that carries real topology — the v6 routing+//! graph behind the `junction` layer — collapses degree-2 chains, which is exactly what+//! a mid-block lane change is. It has already thrown the node away.+//!+//! # A width that belongs to the node, not to either section+//!+//! Two abutting ends could each taper to what they think the other is and still+//! disagree. So neither decides: the width where they meet is `min` of the two lane+//! counts, a function of the pair alone, and each section ramps to it over+//! [`TAPER_M`] of its own length. Both derive the same number from the same two inputs,+//! so a step is not detected and repaired — it cannot be expressed. The narrower section+//! computes a ratio of one and does not taper at all.+//!+//! Ends pair only when the pairing is *mutually* the straightest at that node, so a side+//! street ending at a junction never narrows the road it joins, and a road clipped at+//! the tile border pairs with nothing and keeps the width it has always had.++use std::collections::HashMap;++use crate::tess::ribbon::Taper;+use tilecodec::mamaps::body::{Body, GEOM_LINE};+use tilecodec::mamaps::dict::LAYER_ROADS;++/// How far back from a lane-count change the carriageway ramps to its new width, in+/// metres.+///+/// A ground length rather than a screen one, so the taper is the same stretch of road at+/// every zoom and the geometry stays a function of the tile. Roughly the merge taper a+/// 50 km/h urban road is signed for; a motorway's is longer, but this module has no+/// speed to scale by and a short taper reads as a transition where no taper reads as a+/// wall.+pub const TAPER_M: f64 = 40.0;++/// How straight two ends have to run into each other to be one road continuing.+///+/// The dot product of the two outward directions, which is `-1` for a perfectly straight+/// through-run. `-0.8` admits about 37 degrees of bend — enough for a lane drop on a+/// curve, far short of a side street.+const STRAIGHT_ENOUGH: f32 = -0.8;++/// The carriageway's lane count: the tagged total, or what an untagged road is worth.+///+/// **The one place this fallback is written.** Most roads carry no `lanes` tag at all,+/// and a zero would push a zero width and draw nothing; OSM's own reading of an untagged+/// road is one lane each way, which is also what makes the centre line appear. The+/// transition scan and the mesh that gets tapered have to agree on it exactly — two+/// layers disagreeing about how wide an untagged road is has caused more than one bug+/// here — so they call this rather than each carrying a copy.+pub fn carriageway_lanes(lane_count: u8, oneway: bool) -> u8 {+ match lane_count {+ 0 => {+ if oneway {+ 1+ } else {+ 2+ }+ }+ count => count,+ }+}++/// The tile-local length of a [`TAPER_M`] ramp, in the `0..1` units [`Taper`] takes.+///+/// Zero for a tile with no ground width, which leaves every taper flat rather than+/// dividing by nothing.+pub fn taper_run(ground_width_m: f64) -> f32 {+ if ground_width_m > 0.0 {+ (TAPER_M / ground_width_m) as f32+ } else {+ 0.0+ }+}++/// One end of one carriageway part, as the scan sees it.+#[derive(Debug, Clone, Copy)]+struct End {+ point: (i32, i32),+ /// The direction the road leaves this end in — *away* from its own geometry. Two+ /// ends that continue each other therefore point opposite ways.+ away: (f32, f32),+ lanes: u8,+}++/// Every point in this tile where the carriageway changes width, and what width it+/// changes to.+#[derive(Debug, Default, Clone)]+pub struct Nodes {+ lanes: HashMap<(i32, i32), u8>,+}++impl Nodes {+ /// Scan the tile's road layer for abutting sections of differing lane count.+ ///+ /// Roads only. A junction connector is one lane through an intersection by+ /// construction and is placed with a setback from the arms, so it neither needs a+ /// taper nor should contribute a width to one.+ pub fn scan(tile: &Body) -> Nodes {+ let Some(source) = tile.layer(LAYER_ROADS) else { return Nodes::default() };+ let mut ends: Vec<End> = Vec::new();+ for feature in &source.features {+ if feature.geom_type != GEOM_LINE {+ continue;+ }+ let lanes = carriageway_lanes(feature.lane_count, feature.is_oneway());+ for part in source.parts_of(feature) {+ ends.extend(part_ends(source.points(part), lanes));+ }+ }+ Nodes { lanes: transitions(&ends) }+ }++ /// The taper for one part of a `lanes`-wide section, given a ramp length from+ /// [`taper_run`].+ ///+ /// `lanes` must be the count the mesh is drawn at — [`carriageway_lanes`], not the+ /// raw tag — or the ratio is against a width the renderer never uses.+ pub fn taper(&self, coords: &[i32], lanes: u8, run: f32) -> Taper {+ if self.lanes.is_empty() || coords.len() < 4 || lanes == 0 {+ return Taper::NONE;+ }+ let last = coords.len() / 2 - 1;+ let ratio = |point: (i32, i32)| match self.lanes.get(&point) {+ Some(&node) if node < lanes => f32::from(node) / f32::from(lanes),+ _ => 1.0,+ };+ Taper::new(+ ratio((coords[0], coords[1])),+ ratio((coords[last * 2], coords[last * 2 + 1])),+ run,+ )+ }+}++/// The two ends of one part, or nothing when it has no two distinct points to take a+/// direction from.+///+/// Takes the tile's own `(i16, i16)` points rather than the flat form the tessellator+/// uses, so scanning a tile costs no allocation per part.+fn part_ends(points: &[(i16, i16)], lanes: u8) -> Vec<End> {+ let n = points.len();+ if n < 2 {+ return Vec::new();+ }+ let at = |i: usize| (i32::from(points[i].0), i32::from(points[i].1));+ let first = at(0);+ let last = at(n - 1);+ // The nearest point that is not coincident, so a repeated coordinate — which the+ // simplifier does leave behind — does not produce a zero direction.+ let after_first = (1..n).map(at).find(|&p| p != first);+ let before_last = (0..n - 1).rev().map(at).find(|&p| p != last);+ match (after_first, before_last) {+ (Some(second), Some(penultimate)) => vec![+ End { point: first, away: direction(second, first), lanes },+ End { point: last, away: direction(penultimate, last), lanes },+ ],+ _ => Vec::new(),+ }+}++/// The unit direction from `from` to `to`, or zero when they coincide — which+/// [`part_ends`] has already excluded, so a zero here simply never pairs.+fn direction(from: (i32, i32), to: (i32, i32)) -> (f32, f32) {+ let (dx, dy) = ((to.0 - from.0) as f32, (to.1 - from.1) as f32);+ let length = (dx * dx + dy * dy).sqrt();+ if length > 0.0 {+ (dx / length, dy / length)+ } else {+ (0.0, 0.0)+ }+}++/// Reduce a tile's part ends to the points where the carriageway changes width.+///+/// At each point the straightest *pair* of ends is the road continuing through it; every+/// other end there belongs to something joining, not continuing. Taking the single+/// global minimum makes the pair mutual for free — the two ends of the straightest pair+/// are each other's straightest — which is what stops two sections deriving different+/// partners and so different widths.+fn transitions(ends: &[End]) -> HashMap<(i32, i32), u8> {+ let mut at_point: HashMap<(i32, i32), Vec<usize>> = HashMap::new();+ for (i, end) in ends.iter().enumerate() {+ at_point.entry(end.point).or_default().push(i);+ }++ let mut out = HashMap::new();+ for (point, here) in at_point {+ if here.len() < 2 {+ continue;+ }+ let mut best: Option<(f32, u8, u8)> = None;+ for (rank, &a) in here.iter().enumerate() {+ for &b in &here[rank + 1..] {+ let (one, two) = (ends[a], ends[b]);+ let dot = one.away.0 * two.away.0 + one.away.1 * two.away.1;+ if dot > STRAIGHT_ENOUGH {+ continue;+ }+ if best.is_none_or(|(previous, _, _)| dot < previous) {+ best = Some((dot, one.lanes, two.lanes));+ }+ }+ }+ // Equal counts are the same road merely cut in two — there is nothing to ramp+ // between, and recording it would make every part of every road taper to itself.+ if let Some((_, one, two)) = best {+ if one != two {+ out.insert(point, one.min(two));+ }+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A straight run of `lanes` lanes from `from` to `to`, as a part's two ends.+ fn section(from: (i16, i16), to: (i16, i16), lanes: u8) -> Vec<End> {+ part_ends(&[from, to], lanes)+ }++ fn scanned(sections: &[Vec<End>]) -> HashMap<(i32, i32), u8> {+ transitions(§ions.iter().flatten().copied().collect::<Vec<_>>())+ }++ #[test]+ fn the_lane_fallback_matches_the_width_the_carriageway_is_drawn_at() {+ // Pinned against `tile/geometry.rs`'s carriageway branch. If these two ever+ // disagree the taper ramps to a width the renderer does not draw.+ assert_eq!(carriageway_lanes(0, false), 2, "untagged two-way is one lane each way");+ assert_eq!(carriageway_lanes(0, true), 1, "untagged one-way is one lane");+ assert_eq!(carriageway_lanes(4, false), 4, "a tagged count wins");+ assert_eq!(carriageway_lanes(1, true), 1);+ assert_eq!(carriageway_lanes(255, false), 255);+ }++ #[test]+ fn two_sections_of_differing_width_transition_at_the_point_they_share() {+ let found = scanned(&[+ section((0, 0), (100, 0), 4),+ section((100, 0), (200, 0), 2),+ ]);+ assert_eq!(found.get(&(100, 0)), Some(&2), "the narrower of the two");+ assert_eq!(found.len(), 1, "and nothing at the far ends: {found:?}");+ }++ #[test]+ fn both_sections_derive_the_same_width_whichever_side_asks() {+ // The property that makes a step unrepresentable rather than merely corrected,+ // asserted the way the defect is seen: as two kerbs that do or do not meet.+ let nodes = Nodes { lanes: scanned(&[+ section((0, 0), (1000, 0), 4),+ section((1000, 0), (2000, 0), 2),+ ]) };+ let run = 0.2;+ let wide = kerbs(&[0, 0, 1000, 0], nodes.taper(&[0, 0, 1000, 0], 4, run), 4);+ let narrow =+ kerbs(&[1000, 0, 2000, 0], nodes.taper(&[1000, 0, 2000, 0], 2, run), 2);++ // Where they meet: the wide section's last pair against the narrow one's first.+ let (wide_left, wide_right) = wide[wide.len() - 1];+ let (narrow_left, narrow_right) = narrow[0];+ assert!((wide_left - narrow_left).abs() < 1e-6, "{wide_left} vs {narrow_left}");+ assert!((wide_right - narrow_right).abs() < 1e-6, "{wide_right} vs {narrow_right}");+ // And it is the narrow road's width they agree on, not some average: two lanes+ // of the half-lane-each-side offset the renderer pushes.+ assert!((wide_right - wide_left - 2.0 * LANE).abs() < 1e-6);++ // The defect itself, for contrast: without the taper the wide section ends two+ // lanes wider and that difference is the shoulder-step seen on the device.+ let stepped = kerbs(&[0, 0, 1000, 0], Taper::NONE, 4);+ let (stepped_left, stepped_right) = stepped[stepped.len() - 1];+ assert!(+ (stepped_right - stepped_left) - (narrow_right - narrow_left) > LANE,+ "the untapered end should be at least a lane wider",+ );+ }++ /// One lane's half-width in tile-local units, standing in for the style ramp.+ const LANE: f32 = 0.01;++ /// The two kerbs at each point of a tessellated part, in tile-local units.+ ///+ /// Reproduces what actually reaches a pixel: `record_carriageways` pushes+ /// `lane width x lanes / 2` and `road_surface.vert` offsets by+ /// `normal * t * halfWidth`. Asserting on this rather than on a ratio is what makes+ /// these tests fail if the renderer and the taper ever stop agreeing.+ fn kerbs(coords: &[i32], taper: Taper, lanes: u8) -> Vec<(f32, f32)> {+ use crate::tess::ribbon::{ribbon_tapered, FLOATS_PER_VERTEX};+ let half_width = LANE * f32::from(lanes) / 2.0;+ let mut v = Vec::new();+ ribbon_tapered(coords, 1000, taper, &mut v, &mut Vec::new());+ (0..v.len() / FLOATS_PER_VERTEX / 2)+ .map(|i| {+ let at = |vertex: usize| {+ let f = vertex * FLOATS_PER_VERTEX;+ // The y offset, because these fixtures all run east and the kerbs+ // are therefore north and south of the centreline.+ v[f + 1] + v[f + 3] * v[f + 4] * half_width+ };+ (at(i * 2), at(i * 2 + 1))+ })+ .collect()+ }++ /// How wide a tapered part is at each end, in lanes.+ fn end_lanes(taper: Taper, lanes: u8) -> (f32, f32) {+ let widths = kerbs(&[0, 0, 1000, 0], taper, lanes);+ let span = |(left, right): (f32, f32)| (right - left) / LANE;+ (span(widths[0]), span(widths[widths.len() - 1]))+ }++ #[test]+ fn equal_lane_counts_are_not_a_transition() {+ // A road cut in two by something that is not a lane change — a bridge, a surface+ // change — must not pinch where the pieces meet.+ let found = scanned(&[+ section((0, 0), (100, 0), 3),+ section((100, 0), (200, 0), 3),+ ]);+ assert!(found.is_empty(), "{found:?}");+ }++ #[test]+ fn a_side_street_never_narrows_the_road_it_joins() {+ // Three ends at one point: the road continuing straight through, and a two-lane+ // street arriving at right angles. The straight pair wins, and it agrees, so+ // there is no transition at all.+ let found = scanned(&[+ section((0, 0), (100, 0), 4),+ section((100, 0), (200, 0), 4),+ section((100, 100), (100, 0), 2),+ ]);+ assert!(found.is_empty(), "the side street is not the through pair: {found:?}");+ }++ #[test]+ fn a_side_street_does_not_decide_a_transition_between_two_others() {+ // Same junction, but the through road does change width. The transition is+ // between the two straight ends, and the side street's narrower count is+ // ignored rather than taken as the minimum.+ let found = scanned(&[+ section((0, 0), (100, 0), 6),+ section((100, 0), (200, 0), 4),+ section((100, 100), (100, 0), 1),+ ]);+ assert_eq!(found.get(&(100, 0)), Some(&4), "min of the through pair, not of all three");+ }++ #[test]+ fn ends_that_are_not_straight_enough_do_not_pair() {+ // A sharp fork rather than a road continuing: 90 degrees apart, well past the+ // bend a lane drop can have.+ let found = scanned(&[+ section((0, 0), (100, 0), 4),+ section((100, 0), (100, 100), 2),+ ]);+ assert!(found.is_empty(), "{found:?}");+ }++ #[test]+ fn a_gentle_bend_still_pairs() {+ // A lane drop on a curve is a real thing and must not be missed for being a few+ // degrees off straight.+ let found = scanned(&[+ section((0, 0), (1000, 0), 4),+ section((1000, 0), (1990, 140), 2),+ ]);+ assert_eq!(found.get(&(1000, 0)), Some(&2), "about 8 degrees of bend: {found:?}");+ }++ #[test]+ fn a_part_that_touches_nothing_gets_no_taper() {+ let nodes = Nodes { lanes: scanned(&[section((0, 0), (100, 0), 4)]) };+ assert_eq!(nodes.taper(&[0, 0, 100, 0], 4, 0.2), Taper::NONE);+ }++ #[test]+ fn a_road_clipped_at_the_tile_border_keeps_the_width_it_has() {+ // Only one section is in this tile, so its far end pairs with nothing. It must+ // draw exactly as it does today rather than tapering into the seam.+ let nodes = Nodes { lanes: scanned(&[+ section((0, 0), (100, 0), 4),+ section((100, 0), (200, 0), 2),+ ]) };+ let clipped = nodes.taper(&[200, 0, 400, 0], 2, 0.2);+ assert_eq!(clipped, Taper::NONE, "neither end of it is a transition");+ }++ #[test]+ fn the_wider_section_tapers_and_the_narrower_one_does_not() {+ let nodes = Nodes { lanes: scanned(&[+ section((0, 0), (1000, 0), 4),+ section((1000, 0), (2000, 0), 2),+ ]) };+ assert_ne!(nodes.taper(&[0, 0, 1000, 0], 4, 0.2), Taper::NONE, "the wide one ramps");+ assert_eq!(+ nodes.taper(&[1000, 0, 2000, 0], 2, 0.2),+ Taper::NONE,+ "the narrow one is already the node's width",+ );+ }++ #[test]+ fn a_section_narrower_at_both_ends_tapers_at_both() {+ let nodes = Nodes { lanes: scanned(&[+ section((0, 0), (100, 0), 2),+ section((100, 0), (200, 0), 6),+ section((200, 0), (300, 0), 3),+ ]) };+ let middle = nodes.taper(&[100, 0, 200, 0], 6, 0.2);+ let (start, end) = end_lanes(middle, 6);+ assert!((start - 2.0).abs() < 1e-5, "two lanes at the start: {start}");+ assert!((end - 3.0).abs() < 1e-5, "three at the end: {end}");+ }++ #[test]+ fn a_ground_length_ramp_is_the_same_road_at_every_tile_size() {+ // A z14 tile is about 1900 m across at San Francisco's latitude and a z16 one a+ // quarter of that, so the tile-local run has to be four times as long there for+ // the taper to be the same stretch of tarmac.+ let coarse = taper_run(1900.0);+ let fine = taper_run(475.0);+ assert!((fine / coarse - 4.0).abs() < 1e-3, "{fine} vs {coarse}");+ assert!((coarse - (TAPER_M / 1900.0) as f32).abs() < 1e-9);+ assert_eq!(taper_run(0.0), 0.0, "a tile with no ground width cannot ramp");+ assert_eq!(taper_run(-1.0), 0.0);+ }++ #[test]+ fn a_degenerate_part_contributes_no_ends() {+ assert!(part_ends(&[], 4).is_empty());+ assert!(part_ends(&[(5, 5)], 4).is_empty());+ assert!(part_ends(&[(5, 5), (5, 5)], 4).is_empty(), "coincident points have no direction");+ assert_eq!(part_ends(&[(5, 5), (5, 5), (9, 5)], 4).len(), 2, "a repeat is stepped over");+ }++ #[test]+ fn a_repeated_coordinate_does_not_break_the_direction() {+ // The simplifier leaves these behind and `tess::ribbon::dedupe` drops them, so+ // the scan has to step over them too or a real transition is missed.+ let ends = part_ends(&[(0, 0), (0, 0), (100, 0)], 4);+ assert_eq!(ends.len(), 2);+ assert!((ends[0].away.0 + 1.0).abs() < 1e-6, "leaving the start heading west");+ assert!((ends[1].away.0 - 1.0).abs() < 1e-6, "leaving the end heading east");+ }+}
library/map/src/main/rust/src/vulkan/pipeline.rs
diff --git a/library/map/src/main/rust/src/vulkan/pipeline.rs b/library/map/src/main/rust/src/vulkan/pipeline.rsindex 029748b340..8822f1d363 100644--- a/library/map/src/main/rust/src/vulkan/pipeline.rs+++ b/library/map/src/main/rust/src/vulkan/pipeline.rs@@ -28,6 +28,13 @@ pub const PUSH_CONSTANT_BYTES: u32 = 64 + 16 + 16 + 16 + 16; /// The default `Push::morph`: fully present, no LOD cross-fade. Every draw but WS-D's uses it. pub const MORPH_NONE: [f32; 4] = [1.0, 0.0, 0.0, 0.0]; +/// `Push::line[2]` for a ribbon that carries no markings at all — see the [`Push`] doc comment.+///+/// Below the `[-1, +1]` a real centre-line `t` is bounded to, so it cannot collide with one.+/// `road_surface.frag` tests against its own `NO_MARKINGS_BELOW` of -1.5, halfway between this and+/// the nearest legal split, so neither side is sensitive to the exact value.+pub const NO_MARKINGS: f32 = -2.0;+ /// The push constant block, matching the `Push` block the shaders declare. /// /// `repr(C)` so the field order is the declaration order, which is what the SPIR-V@@ -73,6 +80,24 @@ pub const MORPH_NONE: [f32; 4] = [1.0, 0.0, 0.0, 0.0]; /// /// It is ignored when `line.w` is set, so a one-way may push anything there. ///+/// # `line.z` also carries "no markings at all", as [`NO_MARKINGS`]+///+/// Because a real split is an across-road coordinate it cannot leave `[-1, +1]`, so a value below+/// that range is free to mean something else. [`NO_MARKINGS`] (-2.0) tells `road_surface.frag` to+/// paint the asphalt and nothing on it — no edge lines, no dividers, no centre line.+///+/// The junction layer's lane connectors use it. A connector is a notional path across an+/// intersection, and road paint does not mark those out on the ground; it is also drawn in the+/// carriageway's own colour, so where it overlies the road its asphalt is invisible and its+/// markings are the whole of what shows. Twelve connectors at a crossroads then read as a tangle+/// of hairlines rather than as a widening of the junction.+///+/// Chosen over a new slot or a wider block deliberately: a connector is always a one-way, so+/// `line.z` is *already* dead on exactly the draws this applies to — the shader has never read it+/// there. That makes the reuse something the code enforces rather than a convention a reader has+/// to hold, and it costs no vertex attribute, no `Push` growth past the guaranteed 128 bytes, and+/// no archive format change.+/// /// `misc.z` is the driving convention, resolved per tile at archive build time — the Americas paint /// the line between opposing traffic yellow and most of the rest of the world paints it white. It /// is a flag rather than a colour because the marking palette belongs to the shader alongside the
library/map/src/main/rust/src/vulkan/renderer.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer.rs b/library/map/src/main/rust/src/vulkan/renderer.rsindex bde0673c26..39a0098c9e 100644--- a/library/map/src/main/rust/src/vulkan/renderer.rs+++ b/library/map/src/main/rust/src/vulkan/renderer.rs@@ -11,7 +11,7 @@ use crate::vulkan::buffers::Buffer; use crate::vulkan::context::{ANativeWindow, Context}; use crate::vulkan::images::{AtlasSet, SampledImage}; use crate::vulkan::pick::Pick;-use crate::vulkan::pipeline::{Pipelines, Push, MORPH_NONE};+use crate::vulkan::pipeline::{Pipelines, Push, MORPH_NONE, NO_MARKINGS}; use crate::vulkan::swapchain::Swapchain; use ash::vk; use std::cell::Cell;@@ -19,6 +19,7 @@ use std::cmp::Reverse; use std::collections::HashMap; use std::collections::HashSet; use std::ops::RangeInclusive;+use tilecodec::mamaps::dict::LAYER_JUNCTION; /// How many frames may be in flight. Two is enough to keep the GPU fed behind vsync /// without adding latency the user can feel when panning.@@ -1754,13 +1755,24 @@ impl Renderer { // 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));+ // 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+ // beneath — twelve hairline pairs per junction rather than a widening of the+ // asphalt. `NO_MARKINGS` rides in the centre-line slot, which a one-way leaves+ // dead; see the `Push` doc comment in [`crate::vulkan::pipeline`].+ let centre_t = if layer.source_layer_id == LAYER_JUNCTION {+ NO_MARKINGS+ } else {+ road.split+ }; let push = Push { tile_to_clip, color: argb_to_rgba(asphalt), line: [ half_width_px, road.lanes as f32,- road.split,+ centre_t, f32::from(road.oneway), ], misc: [tile_span_px, edge_aa, yellow, camera.time_seconds],