maps: billboard icons, scratch ring for symbols, bounded tile upload
- Commit
b9f3674c57595282bd534460d904f47a785ea254- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-11 21:27 UTC (2 months ago)
- Parents
10c2938
Diff
library/map/src/main/rust/shaders/sprite.frag
diff --git a/library/map/src/main/rust/shaders/sprite.frag b/library/map/src/main/rust/shaders/sprite.fragindex 7123943990..72a9296599 100644--- a/library/map/src/main/rust/shaders/sprite.frag+++ b/library/map/src/main/rust/shaders/sprite.frag@@ -5,8 +5,10 @@ // thresholded, smoothed and haloed; an icon is already the picture. Sampling it through // the SDF path would read its red channel as a distance and draw a smeared silhouette. //-// Shares `symbol.vert` and the symbol pipeline layout verbatim — same vertex format, same-// push block, same descriptor set slot. Only the bound atlas and this shader differ.+// Pairs with `symbol_billboard.vert` for POI icons (which billboard under tilt like the text+// beside them) and with `symbol.vert` for app markers (already resolved to clip space on the+// CPU). Same pipeline layout, same push block prefix, same descriptor set slot in both cases —+// only the bound atlas and this shader differ from the glyph path. layout(location = 0) in vec2 inUv; layout(location = 0) out vec4 outColor; layout(push_constant) uniform Push {
library/map/src/main/rust/shaders/symbol_billboard.vert
diff --git a/library/map/src/main/rust/shaders/symbol_billboard.vert b/library/map/src/main/rust/shaders/symbol_billboard.vertindex be1c438d49..fd4cd1e3b0 100644--- a/library/map/src/main/rust/shaders/symbol_billboard.vert+++ b/library/map/src/main/rust/shaders/symbol_billboard.vert@@ -1,15 +1,18 @@ #version 450 -// Billboard symbol vertex: point-label glyph quads that stay upright and pinned to their-// ground anchor under camera tilt. Text labels are tessellated per frame at the frame's text-// size (positions arrive tile-local and final), and each vertex also carries the label's-// ground anchor so this shader can, when tilted, project the anchor with perspective and hang-// the glyph off it at a constant screen offset.+// Billboard symbol vertex: point-label glyph quads and POI icon quads that stay upright and+// pinned to their ground anchor under camera tilt. Both are tessellated per frame (positions+// arrive tile-local and final), and each vertex also carries the label's ground anchor so this+// shader can, when tilted, project the anchor with perspective and hang the corner off it at a+// constant screen offset. Text and icons share this shader on purpose: they hang off the same+// anchor in the same pass, so two implementations of it could drift apart and separate the+// pictogram from its name. // // At pitch 0 the renderer clears the billboard flag (push.line.w) and this reduces to the plain // `tileToClip * position` the flat map has always used — byte-identical output. A curved (line) // label writes each glyph vertex as its own anchor (offset zero), so even with the flag set it-// projects straight onto the ground and stays map-aligned.+// projects straight onto the ground and stays map-aligned — which is correct: a road name belongs+// along the road, and is the one label that should lie flat. layout(location = 0) in vec2 inPosition; layout(location = 1) in vec2 inUv;@@ -24,7 +27,7 @@ layout(push_constant) uniform Push { // x: tile span in px (unused here), yzw: halo color rgb. vec4 misc; // The pitch-0 tile matrix's linear 2x2 (column-major m0,m1,m4,m5), so the screen-constant- // glyph offset can be reconstructed while the anchor goes through the perspective matrix.+ // offset can be reconstructed while the anchor goes through the perspective matrix. vec4 morph; } push; void main() {@@ -32,7 +35,7 @@ void main() { if (push.line.w > 0.5) { vec4 a = push.tileToClip * vec4(inAnchor, 0.0, 1.0); vec2 off = inPosition - inAnchor;- // Column-major 2x2 * off: the same screen offset the ortho matrix would give this glyph,+ // Column-major 2x2 * off: the same screen offset the ortho matrix would give this corner, // scaled by the anchor's clip-w so the perspective divide leaves it screen-constant. vec2 offClip = vec2(push.morph.x * off.x + push.morph.z * off.y, push.morph.y * off.x + push.morph.w * off.y);
library/map/src/main/rust/src/bridge.rs
diff --git a/library/map/src/main/rust/src/bridge.rs b/library/map/src/main/rust/src/bridge.rsindex 00d9193517..075eff9588 100644--- a/library/map/src/main/rust/src/bridge.rs+++ b/library/map/src/main/rust/src/bridge.rs@@ -96,6 +96,20 @@ const WORKER_COUNT: usize = 4; /// screen. const RESIDENT_TILE_CAP: usize = 64; +/// How many finished tiles may be uploaded in one frame.+///+/// The drain used to be unbounded, so however many tiles the workers happened to finish between+/// two frames all landed in the next one. Uploading a tile is around a hundred `vkAllocateMemory`+/// calls, on the Choreographer callback, and a burst of them is what the frame-time tail is made+/// of. What is left stays in the channel and is picked up next frame — nothing is dropped, and+/// the tile is not re-requested, because its key is only removed from `in_flight` once it is+/// actually drained.+///+/// Four is a deliberate middle: a screenful is a couple of dozen tiles, so a cold pan fills in+/// over roughly ten frames, which is a fraction of the fetch and decode latency that preceded it+/// and so is not visible. Lower would start to look like a trickle; higher gives the tail back.+const UPLOADS_PER_FRAME: usize = 4;+ /// What a worker reports back about a tile. enum TileResult { /// Tessellated and ready to upload.@@ -531,12 +545,16 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( // Task-17 pick needs the frame's density for Dp→device-px; remember it. map.density = density; - // Upload whatever the workers finished. Doing it here rather than on a worker keeps- // every Vulkan call on one thread.- while let Ok((key, result)) = map.finished.try_recv() {+ // Upload whatever the workers finished, up to `UPLOADS_PER_FRAME`. Doing it here rather than+ // on a worker keeps every Vulkan call on one thread; bounding it keeps a burst of finished+ // tiles from landing in a single frame.+ let mut uploads = 0usize;+ while uploads < UPLOADS_PER_FRAME {+ let Ok((key, result)) = map.finished.try_recv() else { break }; map.in_flight.remove(&key); match result { TileResult::Ready(mesh) => {+ uploads += 1; if let Err(e) = map.renderer.upload(key, &mesh) { log(&format!("uploading a tile failed: {e}")); }
library/map/src/main/rust/src/tile/symbol.rs
diff --git a/library/map/src/main/rust/src/tile/symbol.rs b/library/map/src/main/rust/src/tile/symbol.rsindex e7d63b536e..bf9cd6e09e 100644--- a/library/map/src/main/rust/src/tile/symbol.rs+++ b/library/map/src/main/rust/src/tile/symbol.rs@@ -27,12 +27,22 @@ use tilecodec::mamaps::body::{Body, Feature}; /// reads the per-vertex ground anchor to stay upright under tilt. pub const FLOATS_PER_VERTEX: usize = text::FLOATS_PER_VERTEX; -/// Floats per vertex for a POI **icon** quad: `x, y, u, v`.+/// Floats per vertex for a POI **icon** quad: `x, y, u, v, ax, ay` — the same layout the text+/// beside it uses, because an icon billboards the same way its label does. ///-/// Icons keep the original 4-float layout and draw through the on-ground sprite pipeline (shared-/// with the app markers, which also push 4-float quads), so they are not billboarded under tilt —-/// only the text is. Keeping the icon format unchanged is what lets the marker path stay untouched.-pub const ICON_FLOATS_PER_VERTEX: usize = 4;+/// An icon carries the ground anchor on every corner and draws through the billboard pipeline, so+/// under tilt it stands up to face the camera instead of foreshortening into the ground plane.+/// Sharing one mechanism with the text is deliberate rather than incidental: an icon and its label+/// hang off the same anchor in the same pass, so a second billboard implementation could disagree+/// with the first and slide the pictogram off the name it belongs to.+pub const ICON_FLOATS_PER_VERTEX: usize = text::FLOATS_PER_VERTEX;++/// Floats per vertex for an app **marker** quad: `x, y, u, v`.+///+/// Markers resolve their corners to clip space on the CPU and draw through the plain on-ground+/// sprite pipeline with an identity matrix, so there is no tile-local anchor for a vertex shader+/// to project and this format must not grow.+pub const MARKER_FLOATS_PER_VERTEX: usize = 4; /// Shape one place label into a [`ShapedLabel`] candidate. `weight` follows the /// layer's `medium` flag (country and big-city labels); the authored@@ -299,7 +309,11 @@ pub fn emit_label( /// draw even though they share a pipeline layout and a vertex format. /// /// `rotation` counter-rotates the quad exactly as it does for the text beside it, so a POI-/// pictogram stays the right way up under a heading-up camera.+/// pictogram stays the right way up under a heading-up camera. Tilt is handled separately and+/// on the GPU: every corner carries the label's ground anchor, and the billboard vertex shader+/// projects that anchor and hangs the corner off it at a constant screen offset, so the icon+/// faces the camera at any pitch. The half-extents below stay a tile-local offset *from* the+/// anchor rather than a resolved screen position, which is what lets the shader do that. #[allow(clippy::too_many_arguments)] pub fn emit_icon( label: &ShapedLabel,@@ -327,11 +341,16 @@ pub fn emit_icon( let (v0, v1) = (uv.v0 + dv, uv.v1 + dv); let base = (vertices.len() / ICON_FLOATS_PER_VERTEX) as u32; let start = vertices.len();- vertices.extend_from_slice(&[x0, y0, uv.u0, v0]);- vertices.extend_from_slice(&[x1, y0, uv.u1, v0]);- vertices.extend_from_slice(&[x1, y1, uv.u1, v1]);- vertices.extend_from_slice(&[x0, y1, uv.u0, v1]);+ // Trailing `cx, cy` is the ground anchor, repeated on all four corners. The corner positions+ // are the anchor plus a tile-local half-extent, so the shader recovers the screen offset by+ // subtracting the two — the same contract `tess::text::emit` writes for a glyph.+ vertices.extend_from_slice(&[x0, y0, uv.u0, v0, cx, cy]);+ vertices.extend_from_slice(&[x1, y0, uv.u1, v0, cx, cy]);+ vertices.extend_from_slice(&[x1, y1, uv.u1, v1, cx, cy]);+ vertices.extend_from_slice(&[x0, y1, uv.u0, v1, cx, cy]); indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);+ // Rotates the corner positions about the anchor and leaves the anchor itself alone, so the+ // offset the shader reconstructs is the counter-rotated one. text::upright_stride(&mut vertices[start..], label.anchor, rotation, ICON_FLOATS_PER_VERTEX); } @@ -729,4 +748,128 @@ mod tests { assert!((near.0 - far.0).abs() < 1e-5 && (near.1 - far.1).abs() < 1e-5, "screen offset changed with depth: {near:?} vs {far:?}"); }++ // --- POI icon billboarding ----------------------------------------------++ #[test]+ fn an_icon_quad_carries_its_ground_anchor_on_every_corner() {+ // The billboard shader recovers a corner's screen offset as `position - anchor`, so all+ // four corners must name the same anchor or the quad tears apart under tilt.+ let label = icon_label((0.4, 0.6));+ let (mut vertices, mut indices) = (Vec::new(), Vec::new());+ emit_icon(&label, test_sprite(), false, 1.0, 512.0, (1.0, 0.0), &mut vertices, &mut indices);+ assert_eq!(vertices.len(), 4 * ICON_FLOATS_PER_VERTEX, "expected one quad");+ for corner in vertices.chunks_exact(ICON_FLOATS_PER_VERTEX) {+ assert_eq!((corner[4], corner[5]), label.anchor, "corner lost its anchor");+ }+ }++ #[test]+ fn an_icon_corner_offset_is_a_tile_local_offset_from_the_anchor() {+ // Not a resolved screen position: the offset has to survive into the vertex as something+ // the shader can rotate, or billboarding would have to happen on the CPU per frame.+ let label = icon_label((0.4, 0.6));+ let (mut vertices, mut indices) = (Vec::new(), Vec::new());+ let (density, tile_span_px) = (2.0f32, 512.0f32);+ let sprite = test_sprite();+ emit_icon(&label, sprite, false, density, tile_span_px, (1.0, 0.0), &mut vertices,+ &mut indices);+ let half_w = sprite.width_dp * density * 0.5 / tile_span_px;+ let half_h = sprite.height_dp * density * 0.5 / tile_span_px;+ let first = &vertices[..ICON_FLOATS_PER_VERTEX];+ assert!((first[0] - first[4] + half_w).abs() < 1e-6, "x offset is not the half-width");+ assert!((first[1] - first[5] + half_h).abs() < 1e-6, "y offset is not the half-height");+ }++ #[test]+ fn a_billboarded_icon_stays_the_same_screen_size_at_any_pitch() {+ // The bug being fixed: on the ground plane a tilted camera foreshortens the quad, so its+ // screen height collapses. Billboarded, the icon must measure the same in NDC at pitch 60+ // as it does flat on — that is what "faces the camera" means here.+ let sprite = test_sprite();+ let (z, x, y) = CENTRED_TILE;+ let ndc_height = |pitch: f64, billboard: bool| {+ let cam = camera(pitch);+ let m = cam.tile_to_clip(z, x, y);+ let o = ortho2x2(&cam, z, x, y);+ let label = icon_label(CENTRE_ANCHOR);+ let (mut vertices, mut indices) = (Vec::new(), Vec::new());+ emit_icon(&label, sprite, false, 1.0, cam.tile_span_px(z) as f32, (1.0, 0.0),+ &mut vertices, &mut indices);+ let corner = |i: usize| {+ let v = &vertices[i * ICON_FLOATS_PER_VERTEX..];+ let c = billboard_clip(&m, o, (v[0], v[1]), (v[4], v[5]), billboard);+ c[1] / c[3]+ };+ (corner(2) - corner(0)).abs()+ };+ let flat = ndc_height(0.0, false);+ let tilted = ndc_height(60.0, true);+ assert!((tilted - flat).abs() < 1e-5, "icon changed screen height under tilt: \+ {flat} flat vs {tilted} tilted");+ // And the bug really was a bug: left on the ground plane, pitch 60 squashes it.+ let squashed = ndc_height(60.0, false);+ assert!(squashed < flat * 0.9, "expected the on-ground quad to foreshorten, got {squashed} \+ against {flat} flat");+ }++ #[test]+ fn a_billboarded_icon_stays_pinned_to_its_ground_point() {+ // Facing the camera must not mean floating free of the feature: the quad's centre has to+ // land exactly where the plain projection puts the POI's ground point.+ let cam = camera(55.0);+ let (z, x, y) = CENTRED_TILE;+ let m = cam.tile_to_clip(z, x, y);+ let o = ortho2x2(&cam, z, x, y);+ let label = icon_label(CENTRE_ANCHOR);+ let (mut vertices, mut indices) = (Vec::new(), Vec::new());+ emit_icon(&label, test_sprite(), false, 1.0, cam.tile_span_px(z) as f32, (1.0, 0.0),+ &mut vertices, &mut indices);+ let centre_ndc = |axis: usize| {+ let mut sum = 0.0;+ for v in vertices.chunks_exact(ICON_FLOATS_PER_VERTEX) {+ let c = billboard_clip(&m, o, (v[0], v[1]), (v[4], v[5]), true);+ sum += c[axis] / c[3];+ }+ sum / 4.0+ };+ let ground = billboard_clip(&m, o, CENTRE_ANCHOR, CENTRE_ANCHOR, false);+ assert!((centre_ndc(0) - ground[0] / ground[3]).abs() < 1e-5, "icon drifted in x");+ assert!((centre_ndc(1) - ground[1] / ground[3]).abs() < 1e-5, "icon drifted in y");+ }++ /// The z14 tile holding [`camera`]'s centre, and the tile-local point inside it that the+ /// centre falls on. Projecting an icon here keeps it near the middle of the viewport at any+ /// pitch — far from the horizon, where a clip `w` near zero would swamp the measurement.+ const CENTRED_TILE: (u8, u32, u32) = (14, 2620, 6332);+ const CENTRE_ANCHOR: (f32, f32) = (0.6, 0.4);++ /// A minimal POI label anchored at `anchor`. No shaped text: `emit_icon` reads only the+ /// anchor and the sprite.+ fn icon_label(anchor: (f32, f32)) -> ShapedLabel {+ ShapedLabel {+ layer_index: 0,+ anchor,+ name: "Cafe".to_string(),+ lines: Vec::new(),+ total_advance: 0.0,+ weight: Weight::Regular,+ rank: 4,+ pop: 0,+ sprite: None,+ kind: 0,+ feature_id: tilecodec::mamaps::body::ID_NONE,+ centreline: None,+ }+ }++ /// A 20x24 Dp icon somewhere in the middle of the sheet. Deliberately non-square, so a test+ /// that confused the two half-extents would fail.+ fn test_sprite() -> Sprite {+ Sprite {+ uv: crate::tile::glyph::UvRect { u0: 0.1, v0: 0.2, u1: 0.15, v1: 0.28 },+ width_dp: 20.0,+ height_dp: 24.0,+ }+ } }
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 4cdb594382..7030f10b98 100644--- a/library/map/src/main/rust/src/vulkan/buffers.rs+++ b/library/map/src/main/rust/src/vulkan/buffers.rs@@ -49,31 +49,15 @@ impl Buffer { .map_err(|e| format!("create_buffer {e:?}"))?; let requirements = device.get_buffer_memory_requirements(buffer);- let properties = instance.get_physical_device_memory_properties(physical_device);- // Prefer memory that is both device-local and host-visible, which on a unified- // mobile GPU is the common case and needs no staging copy. Fall back to plain- // host-visible, which is always present.- let memory_type = find_memory_type(- &properties,- requirements.memory_type_bits,- vk::MemoryPropertyFlags::DEVICE_LOCAL- | vk::MemoryPropertyFlags::HOST_VISIBLE- | vk::MemoryPropertyFlags::HOST_COHERENT,- )- .or_else(|| {- find_memory_type(- &properties,- requirements.memory_type_bits,- vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,- )- });- let memory_type = match memory_type {- Some(t) => t,- None => {- device.destroy_buffer(buffer, None);- return Err("no host-visible memory type for a vertex buffer".into());- }- };+ let memory_type =+ match host_visible_memory_type(instance, physical_device, requirements.memory_type_bits)+ {+ Some(t) => t,+ None => {+ device.destroy_buffer(buffer, None);+ return Err("no host-visible memory type for a vertex buffer".into());+ }+ }; let allocate = vk::MemoryAllocateInfo::default() .allocation_size(requirements.size)@@ -131,3 +115,207 @@ fn find_memory_type( && properties.memory_types[i as usize].property_flags.contains(flags) }) }++/// The memory type a host-written buffer should live in.+///+/// Prefer memory that is both device-local and host-visible, which on a unified mobile GPU is the+/// common case and needs no staging copy. Fall back to plain host-visible, which is always present.+///+/// # Safety+///+/// `physical_device` must belong to `instance`.+unsafe fn host_visible_memory_type(+ instance: &ash::Instance,+ physical_device: vk::PhysicalDevice,+ allowed: u32,+) -> Option<u32> {+ let properties = instance.get_physical_device_memory_properties(physical_device);+ find_memory_type(+ &properties,+ allowed,+ vk::MemoryPropertyFlags::DEVICE_LOCAL+ | vk::MemoryPropertyFlags::HOST_VISIBLE+ | vk::MemoryPropertyFlags::HOST_COHERENT,+ )+ .or_else(|| {+ find_memory_type(+ &properties,+ allowed,+ vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,+ )+ })+}++/// Alignment every suballocation starts at.+///+/// Vulkan puts no alignment requirement on a vertex buffer bind offset and requires only 4 for a+/// `UINT32` index buffer, so this is headroom rather than a rule: attribute fetch off a poorly+/// aligned address is measurably slower on some mobile hardware, and at this block size the+/// padding is free.+const SCRATCH_ALIGN: vk::DeviceSize = 64;++/// How big a block is when the ring has to grow. One block covers a whole frame's symbol geometry+/// on any realistic screenful, so the steady state is a single block and no allocation at all.+const SCRATCH_BLOCK: vk::DeviceSize = 2 * 1024 * 1024;++/// A persistent bump allocator for the geometry a single frame throws away.+///+/// Symbol batches used to take a fresh [`Buffer::upload`] per vertex and index buffer per draw —+/// two `vkAllocateMemory` per tile per symbol layer per size batch, several hundred device+/// allocations in a frame. That is the canonical Vulkan antipattern rather than merely a slow one:+/// `maxMemoryAllocationCount` is commonly around 4096, so the old path was a few busy frames from+/// the hard limit, and no driver optimises for it.+///+/// Instead each frame in flight owns one ring. Memory is allocated once, stays mapped for its whole+/// life, and a draw gets an offset into it. [`reset`](Self::reset) hands the whole ring back at the+/// top of the frame, once the fence says that frame's previous commands have retired.+#[derive(Default)]+pub struct ScratchRing {+ blocks: Vec<ScratchBlock>,+ /// The block [`push`](Self::push) is filling. Earlier blocks had something not fit, and their+ /// leftover tail is given up rather than tracked — a bump allocator that reset every frame+ /// gains nothing from a free list.+ cursor: usize,+}++struct ScratchBlock {+ buffer: vk::Buffer,+ memory: vk::DeviceMemory,+ /// Mapped for the block's whole life. The memory is `HOST_COHERENT`, so writes need no flush.+ mapped: *mut u8,+ capacity: vk::DeviceSize,+ used: vk::DeviceSize,+}++impl ScratchRing {+ /// Give the whole ring back, so the next frame writes over it.+ ///+ /// Only the write cursor is rewound; the blocks themselves are kept, which is the point. So a+ /// ring holds its high-water mark — one unusually label-dense frame pins its blocks for the+ /// life of the renderer, in 2 MiB steps. That is the trade being made: a bounded, small amount+ /// of retained memory in exchange for no device allocation on the frame path.+ ///+ /// # Safety+ ///+ /// The frame that last wrote through this ring must have completed — its in-flight fence+ /// signalled. Resetting early lets the next frame overwrite vertices a command buffer is+ /// still reading.+ pub unsafe fn reset(&mut self) {+ for block in &mut self.blocks {+ block.used = 0;+ }+ self.cursor = 0;+ }++ /// Copy `contents` into the ring; return the buffer to bind and the byte offset to bind it at.+ ///+ /// `None` for an empty slice, and when the ring had to grow and the allocation failed. The+ /// caller answers both by skipping the draw, so they are not worth distinguishing. There is+ /// nothing to unwind: a failed push consumed no space, and a successful one that a later push+ /// abandons is reclaimed by the next [`reset`](Self::reset).+ ///+ /// # Safety+ ///+ /// `device` must outlive the ring, and the returned binding is valid only until the next+ /// [`reset`](Self::reset).+ pub unsafe fn push<T: Copy>(+ &mut self,+ instance: &ash::Instance,+ physical_device: vk::PhysicalDevice,+ device: &ash::Device,+ contents: &[T],+ ) -> Option<(vk::Buffer, vk::DeviceSize)> {+ let size = std::mem::size_of_val(contents) as vk::DeviceSize;+ if size == 0 {+ return None;+ }+ loop {+ if self.cursor == self.blocks.len() {+ let capacity = align_up(size).max(SCRATCH_BLOCK);+ self.blocks.push(ScratchBlock::new(+ instance,+ physical_device,+ device,+ capacity,+ )?);+ }+ let block = &mut self.blocks[self.cursor];+ let offset = align_up(block.used);+ if offset + size <= block.capacity {+ block.used = offset + size;+ std::ptr::copy_nonoverlapping(+ contents.as_ptr() as *const u8,+ block.mapped.add(offset as usize),+ size as usize,+ );+ return Some((block.buffer, offset));+ }+ // A block allocated on the branch above is empty and at least `size` big, so the+ // loop can only reach here for a block that was already in the ring.+ self.cursor += 1;+ }+ }++ /// # Safety+ ///+ /// The device must be idle, or no command buffer may still reference the ring.+ pub unsafe fn destroy(&self, device: &ash::Device) {+ for block in &self.blocks {+ device.unmap_memory(block.memory);+ device.destroy_buffer(block.buffer, None);+ device.free_memory(block.memory, None);+ }+ }+}++impl ScratchBlock {+ unsafe fn new(+ instance: &ash::Instance,+ physical_device: vk::PhysicalDevice,+ device: &ash::Device,+ capacity: vk::DeviceSize,+ ) -> Option<ScratchBlock> {+ // One usage for both: a draw's vertices and its indices come out of the same block, and+ // splitting them would double the allocation count for no gain.+ let create_info = vk::BufferCreateInfo::default()+ .size(capacity)+ .usage(vk::BufferUsageFlags::VERTEX_BUFFER | vk::BufferUsageFlags::INDEX_BUFFER)+ .sharing_mode(vk::SharingMode::EXCLUSIVE);+ let buffer = device.create_buffer(&create_info, None).ok()?;+ let requirements = device.get_buffer_memory_requirements(buffer);+ let Some(memory_type) =+ host_visible_memory_type(instance, physical_device, requirements.memory_type_bits)+ else {+ device.destroy_buffer(buffer, None);+ return None;+ };+ let allocate = vk::MemoryAllocateInfo::default()+ .allocation_size(requirements.size)+ .memory_type_index(memory_type);+ let memory = match device.allocate_memory(&allocate, None) {+ Ok(m) => m,+ Err(_) => {+ device.destroy_buffer(buffer, None);+ return None;+ }+ };+ if device.bind_buffer_memory(buffer, memory, 0).is_err() {+ device.free_memory(memory, None);+ device.destroy_buffer(buffer, None);+ return None;+ }+ let mapped = match device.map_memory(memory, 0, capacity, vk::MemoryMapFlags::empty()) {+ Ok(p) => p as *mut u8,+ Err(_) => {+ device.free_memory(memory, None);+ device.destroy_buffer(buffer, None);+ return None;+ }+ };+ Some(ScratchBlock { buffer, memory, mapped, capacity, used: 0 })+ }+}++fn align_up(size: vk::DeviceSize) -> vk::DeviceSize {+ (size + SCRATCH_ALIGN - 1) & !(SCRATCH_ALIGN - 1)+}
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 8822f1d363..c701c255df 100644--- a/library/map/src/main/rust/src/vulkan/pipeline.rs+++ b/library/map/src/main/rust/src/vulkan/pipeline.rs@@ -203,11 +203,16 @@ pub struct Pipelines { /// vertex shader collapses the grid to the flat footprint, so the overhead map is unchanged. pub terrain: vk::Pipeline, pub symbol: vk::Pipeline,- /// POI icons. Same vertex format, same push block and the same- /// [`symbol_layout`](Self::symbol_layout) as [`symbol`](Self::symbol) — only the- /// fragment shader differs, because an icon is a picture and a glyph is a distance- /// field. Sharing the layout is what lets the renderer swap atlases with a descriptor- /// bind instead of a second pipeline layout.+ /// POI icons. The billboard vertex shader from [`symbol`](Self::symbol) paired with the sprite+ /// fragment shader, on the same 6-float format and the same+ /// [`symbol_layout`](Self::symbol_layout): an icon faces the camera under tilt exactly as its+ /// label does, but samples a picture rather than a distance field. Deliberately the *same*+ /// vertex shader as the text so the two can never disagree about where the anchor projects.+ pub icon: vk::Pipeline,+ /// App markers. The plain on-ground vertex shader on the 4-float+ /// [`MARKER_FLOATS_PER_VERTEX`](crate::tile::symbol::MARKER_FLOATS_PER_VERTEX) format: markers+ /// resolve their quads to clip space on the CPU and draw through an identity matrix, so they+ /// need no per-vertex anchor and no billboard branch. pub sprite: vk::Pipeline, /// Screen-anchored overlay quads — today only the user puck. Takes the push-only /// [`layout`](Self::layout), not [`symbol_layout`](Self::symbol_layout), because it@@ -322,9 +327,10 @@ impl Pipelines { .format(vk::Format::R32_SFLOAT) .offset(20), ];- // Sprite (POI icons + app markers): position (tile-local / clip) + uv (atlas), 4 floats.- // The on-ground path — not billboarded — so no per-vertex anchor. Shared with the marker- // path, which pushes 4-float clip-space quads, which is why this format must not grow.+ // Sprite (app markers): position (already clip-space) + uv (atlas), 4 floats. Markers+ // resolve their corners on the CPU and draw through an identity matrix, so there is no+ // tile-local anchor to project and this format must not grow. POI icons no longer use it —+ // they moved to the billboard format below so they face the camera under tilt. let symbol_attributes = [ vk::VertexInputAttributeDescription::default() .location(0)@@ -337,9 +343,10 @@ impl Pipelines { .format(vk::Format::R32G32_SFLOAT) .offset(8), ];- // Symbol text (billboarded): position (tile-local) + uv (atlas) + ground anchor- // (tile-local), 6 floats. The anchor lets `symbol_billboard.vert` keep point labels upright- // and pinned to the ground under tilt; at pitch 0 it is ignored and output is unchanged.+ // Symbol text and POI icons (billboarded): position (tile-local) + uv (atlas) + ground+ // anchor (tile-local), 6 floats. The anchor lets `symbol_billboard.vert` keep point labels+ // and their icons upright and pinned to the ground under tilt; at pitch 0 it is ignored and+ // output is unchanged. One format for both is what keeps an icon on top of its label. let symbol_billboard_attributes = [ vk::VertexInputAttributeDescription::default() .location(0)@@ -523,6 +530,21 @@ impl Pipelines { Stencil::Ignore, Depth::Off, );+ // POI icons: the billboard vertex shader (so they face the camera under tilt, exactly as+ // the text beside them does) paired with the sprite fragment shader (because an icon is a+ // picture, not a distance field). No new shader — both halves already existed.+ let icon = build(+ device,+ symbol_layout,+ render_pass,+ samples,+ symbol_billboard_vert,+ sprite_frag,+ (symbol::ICON_FLOATS_PER_VERTEX * 4) as u32,+ &symbol_billboard_attributes,+ Stencil::Ignore,+ Depth::Off,+ ); let sprite = build( device, symbol_layout,@@ -530,7 +552,7 @@ impl Pipelines { samples, symbol_vert, sprite_frag,- (symbol::ICON_FLOATS_PER_VERTEX * 4) as u32,+ (symbol::MARKER_FLOATS_PER_VERTEX * 4) as u32, &symbol_attributes, Stencil::Ignore, Depth::Off,@@ -597,7 +619,8 @@ impl Pipelines { device.destroy_shader_module(terrain_vert, None); device.destroy_shader_module(terrain_frag, None); - match (fill, line, ribbon, depth, building, terrain, symbol, sprite, puck, mask, scrim) {+ match (fill, line, ribbon, depth, building, terrain, symbol, icon, sprite, puck, mask, scrim)+ { ( Ok(fill), Ok(line),@@ -606,6 +629,7 @@ impl Pipelines { Ok(building), Ok(terrain), Ok(symbol),+ Ok(icon), Ok(sprite), Ok(puck), Ok(mask),@@ -620,14 +644,29 @@ impl Pipelines { building, terrain, symbol,+ icon, sprite, puck, mask, scrim, }),- (fill, line, ribbon, depth, building, terrain, symbol, sprite, puck, mask, scrim) => {+ (+ fill,+ line,+ ribbon,+ depth,+ building,+ terrain,+ symbol,+ icon,+ sprite,+ puck,+ mask,+ scrim,+ ) => { for created in [- fill, line, ribbon, depth, building, terrain, symbol, sprite, puck, mask, scrim,+ fill, line, ribbon, depth, building, terrain, symbol, icon, sprite, puck, mask,+ scrim, ] .into_iter() .flatten()@@ -652,6 +691,7 @@ impl Pipelines { device.destroy_pipeline(self.building, None); device.destroy_pipeline(self.terrain, None); device.destroy_pipeline(self.symbol, None);+ device.destroy_pipeline(self.icon, None); device.destroy_pipeline(self.sprite, None); device.destroy_pipeline(self.puck, None); device.destroy_pipeline(self.mask, None);
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 223cf57e16..94a3c40389 100644--- a/library/map/src/main/rust/src/vulkan/renderer.rs+++ b/library/map/src/main/rust/src/vulkan/renderer.rs@@ -7,7 +7,7 @@ use crate::style::paint::Stroke; use crate::style::{Anchor, Layer, LayerKind, Palette}; use crate::tile::geometry::{self, TileMesh}; use crate::tile::select;-use crate::vulkan::buffers::Buffer;+use crate::vulkan::buffers::{Buffer, ScratchRing}; use crate::vulkan::context::{ANativeWindow, Context}; use crate::vulkan::images::{AtlasSet, SampledImage}; use crate::vulkan::pick::Pick;@@ -164,6 +164,36 @@ struct TransientBuffers { frames: usize, } +/// What the symbol placer accepted: candidate id → (it took its alternate anchor, where in+/// acceptance order it landed).+type AcceptSet = HashMap<u64, (bool, u32)>;++/// Everything [`Renderer::place_symbols`] reads that can change what it decides.+///+/// 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)]+struct PlacementKey {+ center_lon: u64,+ center_lat: u64,+ zoom: u64,+ bearing: u64,+ pitch: u64,+ width_dp: u32,+ height_dp: u32,+ density: u32,+ extent: (u32, u32),+ filter: crate::style::KindFilter,+ /// Every resident tile with its upload stamp, so a tile that arrives or is replaced re-places+ /// even though the camera has not moved. `camera.time_seconds` is deliberately *not* in this+ /// key: it changes every frame and enters no collision box.+ tiles: Vec<(u64, u32)>,+ /// The style, by layer count. A style or toggle change re-tessellates the resident set, which+ /// restamps every tile above, so this only has to catch the layer set itself changing.+ layers: usize,+}+ /// Per-frame synchronisation and its command buffer. struct Frame { command_buffer: vk::CommandBuffer,@@ -350,6 +380,10 @@ pub struct Renderer { retiring: Vec<(usize, ResidentTile)>, /// Transient per-frame symbol buffers, same grace rule as `retiring`. transients: Vec<TransientBuffers>,+ /// One scratch bump allocator per frame in flight, which every symbol draw's geometry is+ /// suballocated from. Indexed by [`frame_index`](Self::frame_index) and reset once that+ /// frame's fence has signalled. See [`ScratchRing`].+ scratch: Vec<ScratchRing>, window: *mut ANativeWindow, pub width: u32, pub height: u32,@@ -372,6 +406,13 @@ pub struct Renderer { /// anchor lon/lat — so `pick_labels` answers without re-tessellating. /// Refreshed by `record_inner` every frame; read by the JNI pick path. placed: std::cell::RefCell<Vec<PlacedHit>>,+ /// The last symbol placement and the state it was computed from.+ ///+ /// [`place_symbols`](Self::place_symbols) projects a collision box for every glyph of every+ /// curved label and then runs a solver that is quadratic in accepted boxes, all of it on the+ /// Choreographer callback. None of that depends on the frame clock, so a camera that has not+ /// moved gets last frame's answer instead of the same computation again.+ placement_cache: std::cell::RefCell<Option<(PlacementKey, AcceptSet)>>, /// What this frame draws on top of every tile, in order. See [`Overlay`]. overlays: Vec<Overlay>, /// The geometry every overlay shares, uploaded once.@@ -570,12 +611,14 @@ impl Renderer { tiles: HashMap::new(), retiring: Vec::new(), transients: Vec::new(),+ scratch: (0..FRAMES_IN_FLIGHT).map(|_| ScratchRing::default()).collect(), window, width, height, needs_rebuild: false, submitted_draws: Cell::new(0), placed: std::cell::RefCell::new(Vec::new()),+ placement_cache: std::cell::RefCell::new(None), overlays: Vec::new(), quad, selected_region: None,@@ -1217,6 +1260,9 @@ impl Renderer { } // Only now is it safe to free what previous frames referenced. self.collect_retired();+ // Same fence, same reason: it says this frame slot's previous commands have retired, so+ // nothing is still reading the scratch they drew from.+ unsafe { self.scratch[self.frame_index].reset() }; let frame = &self.frames[self.frame_index]; let acquired = unsafe {@@ -1278,9 +1324,23 @@ impl Renderer { .image_indices(&indices); match loader.queue_present(queue, &present) { Ok(false) => {}- // Suboptimal or out of date: the window changed under us, so rebuild- // before the next frame rather than drawing into a stale swapchain.- Ok(true) | Err(vk::Result::ERROR_OUT_OF_DATE_KHR) => self.needs_rebuild = true,+ // `VK_SUBOPTIMAL_KHR` is a success code, not an error: the swapchain still+ // presents correctly, it just no longer matches the surface's ideal properties.+ // Rebuilding on it is disproportionate — `rebuild` is a `device_wait_idle`, a+ // swapchain teardown and a recompile of every pipeline, on the Choreographer+ // callback, inside a frame.+ //+ // It is also not self-limiting. Nothing guarantees the rebuild clears the+ // condition, and on Android it routinely does not: a swapchain whose+ // `preTransform` does not match the display's `currentTransform` reports+ // suboptimal on *every* present, so the old code recompiled all eleven pipelines+ // every frame for as long as that held. Note `acquire_next_image` above already+ // discards its own suboptimal flag, so this is now consistent rather than novel.+ //+ // The two cases that genuinely invalidate the swapchain still rebuild:+ // `ERROR_OUT_OF_DATE_KHR` here and at acquire, and `resize` from the host.+ Ok(true) => {}+ Err(vk::Result::ERROR_OUT_OF_DATE_KHR) => self.needs_rebuild = true, Err(e) => return Err(format!("queue_present {e:?}")), } }@@ -2537,11 +2597,12 @@ impl Renderer { // borrows `self`, and buffer upload takes `&self.context` while retiring // takes `&mut self`. let tile_clip = camera.tile_to_clip(tz, tx, ty);- // Billboarding under tilt (point labels only): the shader projects each glyph's ground- // anchor through `tile_clip` (perspective) and hangs the glyph off it at a constant screen- // offset, reconstructed from the pitch-0 tile matrix's linear 2x2. At pitch 0 the flag is- // clear and the shader draws straight through `tile_clip`, byte-identical to before. Curved- // labels carry each vertex as its own anchor, so they stay on the ground regardless.+ // Billboarding under tilt (point labels and their icons): the shader projects each corner's+ // ground anchor through `tile_clip` (perspective) and hangs the corner off it at a constant+ // screen offset, reconstructed from the pitch-0 tile matrix's linear 2x2. At pitch 0 the+ // flag is clear and the shader draws straight through `tile_clip`, byte-identical to+ // before. Curved labels carry each vertex as its own anchor, so they stay on the ground+ // regardless — a road name lies along the road, which is the one case where flat is right. let flat_clip = Camera { pitch_deg: 0.0, ..*camera }.tile_to_clip(tz, tx, ty); let ortho2x2 = [flat_clip[0], flat_clip[1], flat_clip[4], flat_clip[5]]; let billboard_flag = if camera.pitch_deg != 0.0 { 1.0 } else { 0.0 };@@ -2629,20 +2690,24 @@ impl Renderer { // Only the alpha is read by `sprite.frag`: an icon draws in its own // colours, since the reference sets no `icon-color`. color,- line: [0.0, 0.0, 0.0, 0.0],+ // `sprite.frag` reads none of `line`; `w` is the billboard flag the shared vertex+ // shader reads, so an icon stands up under tilt on the same terms as its label.+ line: [0.0, 0.0, 0.0, billboard_flag], misc: [tile_span_px, 0.0, 0.0, 0.0],- morph: MORPH_NONE,+ // The pitch-0 linear 2x2, as for the text below — the same matrix, so the icon and+ // the name beside it resolve their screen offsets identically.+ morph: [ortho2x2[0], ortho2x2[1], ortho2x2[2], ortho2x2[3]], }; self.draw_symbol_batch( command_buffer,- self.pipelines.sprite,+ self.pipelines.icon, sprite_set, &icon_vertices, &icon_indices, &push, submitted, );- // The sprite pipeline shares `LayerKind::Symbol`, so this still forces the+ // The icon pipeline shares `LayerKind::Symbol`, so this still forces the // fill/line path to rebind. The symbol pipeline is bound again immediately // below whenever there is any text — and a label with an icon always has // text, because `shape_label` returns nothing for an empty name.@@ -2675,11 +2740,14 @@ impl Renderer { } } - /// Upload one transient vertex/index pair, bind `pipeline` with `set`, and draw it.+ /// Suballocate one vertex/index pair out of this frame's scratch ring, bind `pipeline` with+ /// `set`, and draw it. /// /// The icon and text paths differ only in which pipeline and atlas they bind, so they- /// share this. Buffers retire on the frames-in-flight grace count: last frame's- /// command buffer may still reference them.+ /// share this. Geometry goes into [`Renderer::scratch`] rather than into a buffer of its own:+ /// a screenful of labels is several hundred of these a frame, and a `vkAllocateMemory` per+ /// draw is both slow and bounded by `maxMemoryAllocationCount`. The ring is reset at the top+ /// of the frame under the in-flight fence, which is what makes the memory safe to reuse. #[allow(clippy::too_many_arguments)] unsafe fn draw_symbol_batch( &mut self,@@ -2691,28 +2759,26 @@ impl Renderer { push: &Push, submitted: &mut usize, ) {+ let frame_index = self.frame_index; let device = &self.context.device;- let Ok(vbuf) = Buffer::upload(+ // Disjoint field borrows, deliberately not `self.context.device.clone()` as the frame path+ // does once per frame: `ash::Device` clones its whole function-pointer table, and this+ // runs a few hundred times a frame.+ let Some((vbuf, voffset)) = self.scratch[frame_index].push( &self.context.instance, self.context.physical_device, device,- vk::BufferUsageFlags::VERTEX_BUFFER, vertices, ) else { return; };- let ibuf = match Buffer::upload(+ let Some((ibuf, ioffset)) = self.scratch[frame_index].push( &self.context.instance, self.context.physical_device, device,- vk::BufferUsageFlags::INDEX_BUFFER, indices,- ) {- Ok(b) => b,- Err(_) => {- vbuf.destroy(device);- return;- }+ ) else {+ return; }; device.cmd_bind_pipeline(command_buffer, vk::PipelineBindPoint::GRAPHICS, pipeline); device.cmd_bind_descriptor_sets(@@ -2730,11 +2796,10 @@ impl Renderer { 0, push.as_bytes(), );- device.cmd_bind_vertex_buffers(command_buffer, 0, &[vbuf.buffer], &[0]);- device.cmd_bind_index_buffer(command_buffer, ibuf.buffer, 0, vk::IndexType::UINT32);+ device.cmd_bind_vertex_buffers(command_buffer, 0, &[vbuf], &[voffset]);+ device.cmd_bind_index_buffer(command_buffer, ibuf, ioffset, vk::IndexType::UINT32); device.cmd_draw_indexed(command_buffer, indices.len() as u32, 1, 0, 0, 0); *submitted += 1;- self.transients.push(TransientBuffers { vbuf, ibuf, frames: FRAMES_IN_FLIGHT }); } /// The per-frame symbol pre-pass: one collision candidate per shaped label@@ -2751,8 +2816,32 @@ impl Renderer { ordered: &[u64], extent: vk::Extent2D, filter: &crate::style::KindFilter,- ) -> HashMap<u64, (bool, u32)> {+ ) -> AcceptSet { use crate::tile::placement;+ let key = PlacementKey {+ center_lon: camera.center_lon.to_bits(),+ center_lat: camera.center_lat.to_bits(),+ zoom: camera.zoom.to_bits(),+ bearing: camera.bearing_deg.to_bits(),+ pitch: camera.pitch_deg.to_bits(),+ width_dp: camera.width_dp.to_bits(),+ height_dp: camera.height_dp.to_bits(),+ density: camera.density.to_bits(),+ extent: (extent.width, extent.height),+ filter: filter.clone(),+ tiles: ordered+ .iter()+ .map(|key| {+ (*key, self.tiles.get(key).map(|t| t.uploaded_at).unwrap_or(0.0).to_bits())+ })+ .collect(),+ layers: layers.len(),+ };+ if let Some((cached, accepted)) = self.placement_cache.borrow().as_ref() {+ if *cached == key {+ return accepted.clone();+ }+ } let mut candidates: Vec<placement::SegmentedCandidate> = Vec::new(); for (index, layer) in layers.iter().enumerate() { if layer.kind != LayerKind::Symbol {@@ -2839,11 +2928,13 @@ impl Renderer { // acceptance order it landed**. `place_segmented` returns its winners in priority order and // a `HashMap` would throw that away, which is what made `pick_labels`' "topmost first" a // claim rather than a fact.- placement::place_segmented(&candidates)+ let accepted: AcceptSet = placement::place_segmented(&candidates) .into_iter() .enumerate() .map(|(order, (id, flipped))| (id, (flipped, order as u32)))- .collect()+ .collect();+ *self.placement_cache.borrow_mut() = Some((key, accepted.clone()));+ accepted } /// Task-17 pick: the placed labels of the last frame whose screen boxes@@ -3145,6 +3236,10 @@ impl Drop for Renderer { transient.ibuf.destroy(&self.context.device); } self.transients.clear();+ for ring in &self.scratch {+ ring.destroy(&self.context.device);+ }+ self.scratch.clear(); for frame in &self.frames { self.context.device.destroy_fence(frame.in_flight, None); self.context.device.destroy_semaphore(frame.image_available, None);