diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index bfd9fe4fd4..38bb317d17 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -425,6 +425,16 @@ pub trait FeatureSource: Send + Sync { fn visit_chunks(&self, _extent: Option, _bytes: usize, _visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { Err(DataError::Unsupported("a source that can't be read a chunk at a time".into())) } + /// Whether [`FeatureSource::visit_ids_chunks`] is available. + fn visits_ids(&self) -> bool { + false + } + /// The features with these ids ([`Feature::id`], in order), visited a chunk at a time in + /// source order, as [`FeatureSource::visit_chunks`] visits them: for a read of features + /// someone already knows by id. Ids the source doesn't hold are left out. + fn visit_ids_chunks(&self, _ids: &[u64], _bytes: usize, _visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { + Err(DataError::Unsupported("a source that can't be read by feature id".into())) + } /// [`FeatureSource::visit_chunks`] for a whole request, its box in the source's own system /// ([`Request::own`]) too (one over the whole plane, [`whole_plane`], reads every feature as a /// map in that system draws them): a source that reads one this way tests each feature's own box diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index af40ca4c61..79b5b21342 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -262,6 +262,141 @@ impl ShpSource { } } +impl ShpSource { + /// A complete visit of a request's records, or of those numbered `numbered` (from 0, in + /// order), parsed and given a chunk at a time ([`FeatureSource::visit_request_chunks`], + /// [`FeatureSource::visit_ids_chunks`]). Only a whole read looks at the stored boxes. + fn visit_with( + &self, + req: &Request, + numbered: Option<&[u32]>, + bytes: usize, + visit: &mut dyn FnMut(Vec) -> Result<()>, + ) -> Result { + let encoding = self.encoding.decoder(); + let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?; + let req = Request { limit: usize::MAX, ..*req }; + // The request's box in the file's own system, when it is one (a box in another system + // is read as if absent), and whether it is one over the whole plane, which narrows + // nothing: every record, those without a box too, as a whole read. + let own = self.reproject.own_box(&req); + let everywhere = own == Some(super::whole_plane()); + let extent = self.reproject.request_box(&req).filter(|_| !everywhere); + if extent.is_some_and(|e| e.is_empty()) { + return Ok(Batch { complete: true, ..Batch::default() }); + } + // Rounded outward, as the index keeps the records' boxes, so a box reaching the extent by + // less than an f32 step is still found. + let bounds = extent.map(|e| [f32_down(e.min_x), f32_down(e.min_y), f32_up(e.max_x), f32_up(e.max_y)]); + // As in `read`, an extent the file's system couldn't bound (#1925) visits every record. + let late = req.extent.is_some() && bounds.is_none(); + // A whole read looks at whether the stored boxes hold their shapes, once. + let checking = + numbered.is_none() && req.extent.is_none() && (own.is_none() || everywhere) && self.boxes.load(Relaxed) == BOXES_UNKNOWN; + let mut missed = false; + // A record a whole read couldn't read this time had its box left unchecked: the check + // waits for a read that reads them all. + let mut unchecked = false; + let mut shp = Cursor::open(&self.shp)?; + let mut dbf = Cursor::open(&self.dbf)?; + let mut buf = Vec::new(); + let mut row = vec![0u8; self.table.row_len]; + let (mut skipped, mut unread_dates, mut null_text, mut boxed_off, mut not_utf8) = (0, Vec::new(), Vec::new(), 0u64, Vec::new()); + let mut deleted = 0usize; + // The same directory, ordering, extent rules and read-only scan fallback as sampled + // reads, with no interaction row cap. The index visits records without materializing + // their directory or the complete feature collection in memory. + // Every record id fits u32. This format bound visits them all while keeping SQLite's + // LIMIT within its signed integer range on 64-bit hosts. + crate::progress::begin(self.info.count.and_then(|n| usize::try_from(n).ok()).unwrap_or(0)); + let mut each = |i: u32, place: Place| -> Result<()> { + crate::progress::step(1)?; + if u64::from(place.len) > MAX_RECORD { + skipped += 1; + return Ok(()); + } + buf.resize(place.len as usize, 0); + if shp.read_at(u64::from(place.offset), &mut buf).is_err() { + skipped += 1; + unchecked = true; + return Ok(()); + } + let geometry = match parse_shape(&buf) { + // A coordinate that isn't a number (NaN or infinite) has no place: the record is + // left out and counted, as one that can't be converted (#1985). One under a stored + // box the index takes ([`index::usable`]) is counted apart too, as the index framed + // it by that box; a backwards one it can't frame, and counts as unboxed instead. + Ok(Some(g)) if !g.is_finite() => { + skipped += 1; + boxed_off += u64::from(index::usable(record_box(&buf, u64::from(place.len)))); + return Ok(()); + } + Ok(Some(g)) => { + // A box the index took as stored (one in order) that misses part of the shape. + if checking && !missed { + let stored = record_box(&buf, u64::from(place.len)); + missed = index::usable(stored) && !holds(stored, &g.extent()); + } + match self.reproject.place(g, &req) { + Some(placed) => Some(placed), + None => { + skipped += 1; + return Ok(()); + } + } + } + Ok(None) => None, + Err(()) => { + skipped += 1; + return Ok(()); + } + }; + // As in `read`, the shape itself is checked. + // As a read by area, its box in the file's own system included, gives no rows + // without a shape. + if geometry.as_ref().map_or(if own.is_some() { !everywhere } else { req.extent.is_some() }, |g| !g.inside) { + return Ok(()); + } + let geometry = geometry.map(|p| p.geometry); + let attrs = if u64::from(i) < self.table.rows { + let at = self.table.header_len + u64::from(i) * self.table.row_len as u64; + if dbf.read_at(at, &mut row).is_err() { + skipped += 1; + return Ok(()); + } + // A deleted row: its shape is left out too, and counted. + if row.first() == Some(&b'*') { + deleted += 1; + return Ok(()); + } + self.table.values(&row, &encoding, &self.encoding, &mut unread_dates, &mut null_text, &mut not_utf8) + } else { + vec![Value::Null; self.table.columns.len()] + }; + chunks.push(Feature { id: u64::from(i) + 1, geometry, attrs }) + }; + let (matched, complete) = match numbered { + Some(numbers) => self.index.visit_numbered(numbers, &mut each)?, + None => self.index.visit_complete(bounds, &mut each)?, + }; + chunks.flush()?; + if checking && complete && (missed || !unchecked) { + self.boxes.store(if missed { BOXES_DONT } else { BOXES_HOLD }, Relaxed); + } + Ok(Batch { + features: Vec::new(), + matched, + complete, + skipped, + unread_dates, + rounded_dates: Vec::new(), + null_text, + notes: boxed_off_note(boxed_off, false, late).into_iter().chain(deleted_note(deleted, false)).collect(), + not_utf8, + }) + } +} + impl FeatureSource for ShpSource { fn info(&self) -> &SourceInfo { &self.info @@ -430,121 +565,15 @@ impl FeatureSource for ShpSource { /// As [`FeatureSource::visit_chunks`], narrowed by the request's box in the file's own system /// when it gives one ([`Request::own`]), and each shape's own box tested against it. fn visit_request_chunks(&self, req: &Request, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { - let encoding = self.encoding.decoder(); - let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?; - let req = Request { limit: usize::MAX, ..*req }; - // The request's box in the file's own system, when it is one (a box in another system - // is read as if absent), and whether it is one over the whole plane, which narrows - // nothing: every record, those without a box too, as a whole read. - let own = self.reproject.own_box(&req); - let everywhere = own == Some(super::whole_plane()); - let extent = self.reproject.request_box(&req).filter(|_| !everywhere); - if extent.is_some_and(|e| e.is_empty()) { - return Ok(Batch { complete: true, ..Batch::default() }); - } - // Rounded outward, as the index keeps the records' boxes, so a box reaching the extent by - // less than an f32 step is still found. - let bounds = extent.map(|e| [f32_down(e.min_x), f32_down(e.min_y), f32_up(e.max_x), f32_up(e.max_y)]); - // As in `read`, an extent the file's system couldn't bound (#1925) visits every record. - let late = req.extent.is_some() && bounds.is_none(); - // A whole read looks at whether the stored boxes hold their shapes, once. - let checking = req.extent.is_none() && (own.is_none() || everywhere) && self.boxes.load(Relaxed) == BOXES_UNKNOWN; - let mut missed = false; - // A record a whole read couldn't read this time had its box left unchecked: the check - // waits for a read that reads them all. - let mut unchecked = false; - let mut shp = Cursor::open(&self.shp)?; - let mut dbf = Cursor::open(&self.dbf)?; - let mut buf = Vec::new(); - let mut row = vec![0u8; self.table.row_len]; - let (mut skipped, mut unread_dates, mut null_text, mut boxed_off, mut not_utf8) = (0, Vec::new(), Vec::new(), 0u64, Vec::new()); - let mut deleted = 0usize; - // The same directory, ordering, extent rules and read-only scan fallback as sampled - // reads, with no interaction row cap. The index visits records without materializing - // their directory or the complete feature collection in memory. - // Every record id fits u32. This format bound visits them all while keeping SQLite's - // LIMIT within its signed integer range on 64-bit hosts. - crate::progress::begin(self.info.count.and_then(|n| usize::try_from(n).ok()).unwrap_or(0)); - let (matched, complete) = self.index.visit_complete(bounds, |i, place| { - crate::progress::step(1)?; - if u64::from(place.len) > MAX_RECORD { - skipped += 1; - return Ok(()); - } - buf.resize(place.len as usize, 0); - if shp.read_at(u64::from(place.offset), &mut buf).is_err() { - skipped += 1; - unchecked = true; - return Ok(()); - } - let geometry = match parse_shape(&buf) { - // A coordinate that isn't a number (NaN or infinite) has no place: the record is - // left out and counted, as one that can't be converted (#1985). One under a stored - // box the index takes ([`index::usable`]) is counted apart too, as the index framed - // it by that box; a backwards one it can't frame, and counts as unboxed instead. - Ok(Some(g)) if !g.is_finite() => { - skipped += 1; - boxed_off += u64::from(index::usable(record_box(&buf, u64::from(place.len)))); - return Ok(()); - } - Ok(Some(g)) => { - // A box the index took as stored (one in order) that misses part of the shape. - if checking && !missed { - let stored = record_box(&buf, u64::from(place.len)); - missed = index::usable(stored) && !holds(stored, &g.extent()); - } - match self.reproject.place(g, &req) { - Some(placed) => Some(placed), - None => { - skipped += 1; - return Ok(()); - } - } - } - Ok(None) => None, - Err(()) => { - skipped += 1; - return Ok(()); - } - }; - // As in `read`, the shape itself is checked; a read by area, its box in the file's - // own system included, gives no rows without a shape. - if geometry.as_ref().map_or(if own.is_some() { !everywhere } else { req.extent.is_some() }, |g| !g.inside) { - return Ok(()); - } - let geometry = geometry.map(|p| p.geometry); - let attrs = if u64::from(i) < self.table.rows { - let at = self.table.header_len + u64::from(i) * self.table.row_len as u64; - if dbf.read_at(at, &mut row).is_err() { - skipped += 1; - return Ok(()); - } - // A deleted row: its shape is left out too, and counted. - if row.first() == Some(&b'*') { - deleted += 1; - return Ok(()); - } - self.table.values(&row, &encoding, &self.encoding, &mut unread_dates, &mut null_text, &mut not_utf8) - } else { - vec![Value::Null; self.table.columns.len()] - }; - chunks.push(Feature { id: u64::from(i) + 1, geometry, attrs }) - })?; - chunks.flush()?; - if checking && complete && (missed || !unchecked) { - self.boxes.store(if missed { BOXES_DONT } else { BOXES_HOLD }, Relaxed); - } - Ok(Batch { - features: Vec::new(), - matched, - complete, - skipped, - unread_dates, - rounded_dates: Vec::new(), - null_text, - notes: boxed_off_note(boxed_off, false, late).into_iter().chain(deleted_note(deleted, false)).collect(), - not_utf8, - }) + self.visit_with(req, None, bytes, visit) + } + fn visits_ids(&self) -> bool { + true + } + /// The records whose features have these ids (record numbers from 1), in file order. + fn visit_ids_chunks(&self, ids: &[u64], bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { + let numbers: Vec = ids.iter().filter_map(|id| id.checked_sub(1).and_then(|n| u32::try_from(n).ok())).collect(); + self.visit_with(&Request { extent: None, limit: usize::MAX, own: None }, Some(&numbers), bytes, visit) } } diff --git a/crates/data/src/source/shp/index.rs b/crates/data/src/source/shp/index.rs index dfafc9ed47..154a97eefc 100644 --- a/crates/data/src/source/shp/index.rs +++ b/crates/data/src/source/shp/index.rs @@ -169,7 +169,7 @@ impl DiskIndex { /// through the directory in order: by id when few match, else in one pass over it. A join /// of the two tables sorted by id instead costs several seconds a few hundred thousand /// matches, and was run twice, once to count. - fn visit_matches(&self, db: &Connection, extent: [f32; 4], mut visit: impl FnMut(u32, Place) -> Result<()>) -> Result<(u64, bool)> { + fn visit_matches(&self, db: &Connection, extent: [f32; 4], visit: impl FnMut(u32, Place) -> Result<()>) -> Result<(u64, bool)> { let [x0, y0, x1, y1] = extent; let words = usize::try_from(self.count.div_ceil(64)).map_err(|_| bad("spatial index: too many records"))?; let mut hits: Vec = Vec::new(); @@ -197,6 +197,18 @@ impl DiskIndex { } } } + self.visit_hits(db, &hits, matched, visit) + } + + /// Every record marked in `hits` (one bit a record), `matched` of them, in file order: by id + /// when few are, else in one pass over the directory. + fn visit_hits( + &self, + db: &Connection, + hits: &[u64], + matched: u64, + mut visit: impl FnMut(u32, Place) -> Result<()>, + ) -> Result<(u64, bool)> { // What the progress counts from here: the records read, not every record of the file. crate::progress::begin(usize::try_from(matched).unwrap_or(usize::MAX)); let hit = |id: u64| usize::try_from(id / 64).ok().and_then(|w| hits.get(w)).is_some_and(|w| w & (1u64 << (id % 64)) != 0); @@ -419,6 +431,45 @@ impl Index { pub fn indexed(&self) -> bool { matches!(self.storage, Storage::Disk(_)) } + /// The records numbered in `ids` (from 0, in order; numbers past the file's are left out), in + /// file order, for a read of the features someone already knows by number. + pub fn visit_numbered(&self, ids: &[u32], mut visit: impl FnMut(u32, Place) -> Result<()>) -> Result<(u64, bool)> { + let words = usize::try_from(self.count.div_ceil(64)).map_err(|_| bad("spatial index: too many records"))?; + let mut hits: Vec = Vec::new(); + hits.try_reserve_exact(words).map_err(|e| bad(format!("spatial index: {e}")))?; + hits.resize(words, 0); + let mut matched = 0u64; + for &id in ids { + let id = u64::from(id); + if id >= self.count { + continue; + } + let Some(word) = usize::try_from(id / 64).ok().and_then(|w| hits.get_mut(w)) else { continue }; + let bit = 1u64 << (id % 64); + if *word & bit == 0 { + *word |= bit; + matched += 1; + } + } + // None of the file's: nothing to read, not even its directory. + if matched == 0 { + crate::progress::check()?; + return Ok((0, true)); + } + match &self.storage { + Storage::Disk(disk) => { + let db = connect(disk._lease.path(), false)?; + disk.visit_hits(&db, &hits, matched, visit) + } + // Without an index, the record headers are scanned and those numbered visited. + Storage::Scan { path, len } => { + crate::progress::begin(usize::try_from(matched).unwrap_or(usize::MAX)); + let hit = |id: u32| usize::try_from(id / 64).ok().and_then(|w| hits.get(w)).is_some_and(|w| w & (1u64 << (id % 64)) != 0); + scan_for(path, *len, false, |id, place, _| if hit(id) { visit(id, place) } else { Ok(()) })?; + Ok((matched, true)) + } + } + } pub fn visit(&self, extent: Option<[f32; 4]>, limit: usize, mut visit: impl FnMut(u32, Place) -> Result<()>) -> Result<(u64, bool)> { match &self.storage { Storage::Disk(disk) => disk.visit(extent, limit, visit), diff --git a/crates/data/src/source/shp/tests.rs b/crates/data/src/source/shp/tests.rs index 6b0e6b5eba..4ba32c65f7 100644 --- a/crates/data/src/source/shp/tests.rs +++ b/crates/data/src/source/shp/tests.rs @@ -978,3 +978,32 @@ fn a_complete_read_by_its_own_box_leaves_out_rows_without_a_shape() { assert_eq!(without_shape(&s, Some((utm, super::super::whole_plane()))), without_shape(&s, None)); }); } + +/// A read by feature ids gives exactly those features, in file order whatever order they are +/// asked in, leaves out ids the file doesn't hold, and doesn't count as the whole read that looks +/// at the stored boxes (#2788). +#[test] +fn a_read_by_ids_gives_those_features_in_file_order() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("pts.shp"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("n", FieldType::Integer)]); + for i in 0..300 { + ds.push(Some(Geometry::Point(Coord::new(f64::from(i % 20), f64::from(i / 20)))), vec![Value::Int(i64::from(i))]); + } + write_shapefile(&ds, &path); + cache::with_index_dir(tmp.path().join("cache"), || { + let s = ShpSource::open_path(&path, "pts").unwrap(); + assert!(s.visits_ids()); + let mut got = Vec::new(); + let batch = s + .visit_ids_chunks(&[250, 3, 0, 120, 3, 9_999], 4096, &mut |chunk| { + got.extend(chunk.iter().map(|f| (f.id, f.attrs.first().cloned()))); + Ok(()) + }) + .unwrap(); + assert!(batch.complete); + // Ids from 1: 0 and 9,999 aren't records of this file. + assert_eq!(got, [(3, Some(Value::Int(2))), (120, Some(Value::Int(119))), (250, Some(Value::Int(249)))]); + assert!(!s.finds_all_by_area(), "a read by ids isn't the whole read that looks at the boxes"); + }); +} diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index e040eb70cf..f8fc2208d8 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -19,10 +19,12 @@ use rustgis_data::source::{Batch, FeatureSource, Request, SourceInfo}; use rustgis_geom::{Coord, Extent}; use serde::{Deserialize, Serialize}; +mod drawn_index; #[cfg(test)] mod own_tests; mod render_lod; mod render_view; +pub use drawn_index::{DrawnBoxes, PACKING_BYTES}; pub use render_view::KEPT_VIEW_BYTES; mod window; pub(crate) use window::Query; @@ -186,6 +188,9 @@ pub struct SourceLayer { /// The last view's rows and drawn geometry, shared by render snapshots ([`render_view`]). #[serde(skip)] render_view: Arc>, + /// The features indexed by their boxes as drawn, shared by render snapshots ([`drawn_index`]). + #[serde(skip)] + render_drawn: Arc>, #[serde(skip)] pending: Option>, /// Projection used for this disposable window's geometry cache. @@ -1271,9 +1276,80 @@ impl SourceLayer { self.render_view.lock().unwrap_or_else(std::sync::PoisonError::into_inner).put(handle, key, read, res, chunks); } - /// Lets the kept view go when it holds more than `room` bytes. + /// Lets the drawn-box index, then the kept view, go when they hold more than `room` bytes + /// between them. pub fn trim_kept_view(&self, room: usize) { - self.render_view.lock().unwrap_or_else(std::sync::PoisonError::into_inner).trim(room); + let mut drawn = self.render_drawn.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + drawn.trim(room); + let left = room.saturating_sub(drawn.bytes()); + drop(drawn); + self.render_view.lock().unwrap_or_else(std::sync::PoisonError::into_inner).trim(left); + } + + /// The source's features indexed by their boxes as drawn for `key` (the projection and datum + /// grids, as the renderer names them), when a frame that read them all made one (#2788). + pub fn drawn_index(&self, key: &str) -> Option> { + let handle = self.handle.as_ref()?; + self.render_drawn.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(handle, key) + } + + /// Whether a frame reading every feature for `key` should gather their drawn boxes to make + /// an index: not when one is kept, or was too large to keep. + pub fn drawn_index_wanted(&self, key: &str, share: usize) -> bool { + let Some(handle) = &self.handle else { return false }; + self.render_drawn.lock().unwrap_or_else(std::sync::PoisonError::into_inner).wanted(handle, key, share) + } + + /// Packs the boxes as drawn (feature id, box) a frame gathered for `key` from a read of every + /// feature into an index, off that frame: on a worker on the desktop, as the packing takes + /// seconds for millions of features. It is kept when it fits `share` bytes (the source's share + /// of the map's view memory beside its interaction rows), the kept view then trimmed to what + /// is left; otherwise none is gathered again for `key`. Nothing is packed when an index is + /// kept or being packed for `key`; one whose worker can't start is gathered again. + pub fn index_drawn_boxes(&self, key: &str, boxes: Vec<(u32, [f32; 4])>, share: usize) { + let Some(handle) = self.handle.as_ref() else { return }; + let lock = + |m: &Mutex| m.lock().unwrap_or_else(std::sync::PoisonError::into_inner).begin(handle, key, share); + let Some(ticket) = lock(&self.render_drawn) else { return }; + let (drawn, view) = (Arc::clone(&self.render_drawn), Arc::clone(&self.render_view)); + let slot = Arc::clone(&drawn); + let pack = move || { + // Given up once this packing is no longer the one the slot waits for. + let replaced = || slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).building_ticket() != Some(ticket); + let index = DrawnBoxes::new(boxes, replaced); + // The kept view is trimmed to the room the index leaves only when the index is kept. + let left = slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).finish(ticket, index, share); + if let Some(left) = left { + view.lock().unwrap_or_else(std::sync::PoisonError::into_inner).trim(left); + } + }; + #[cfg(target_arch = "wasm32")] + { + let _ = &drawn; + pack(); + } + #[cfg(not(target_arch = "wasm32"))] + if std::thread::Builder::new().name("rustgis-drawn-index".into()).spawn(pack).is_err() { + drawn.lock().unwrap_or_else(std::sync::PoisonError::into_inner).finish(ticket, None, share); + } + } + + /// Keeps no index for `key`: its boxes, `need` bytes, were too large to gather; they are + /// gathered again once the source's share has that much room. + pub fn refuse_drawn_index(&self, key: &str, need: usize) { + let Some(handle) = &self.handle else { return }; + self.render_drawn.lock().unwrap_or_else(std::sync::PoisonError::into_inner).refuse(handle, key, need); + } + + /// Whether an index is being packed for `key` ([`SourceLayer::index_drawn_boxes`]). + pub fn drawn_index_building(&self, key: &str) -> bool { + let Some(handle) = &self.handle else { return false }; + self.render_drawn.lock().unwrap_or_else(std::sync::PoisonError::into_inner).building(handle, key) + } + + /// The memory the drawn-box index holds. + pub fn drawn_index_bytes(&self) -> usize { + self.render_drawn.lock().unwrap_or_else(std::sync::PoisonError::into_inner).bytes() } /// Puts the kept chunks drawn again, with the geometry drawing made of them, in place of @@ -1815,6 +1891,7 @@ impl SourceLayer { self.pending = None; self.render_lod = Default::default(); self.render_view = Default::default(); + self.render_drawn = Default::default(); } /// Whether `other` (a copy of this one) reads the same source the same way: the same file and @@ -1839,6 +1916,7 @@ impl SourceLayer { pub fn reset(&mut self) { self.render_lod = Default::default(); self.render_view = Default::default(); + self.render_drawn = Default::default(); self.reset_window(); } @@ -2195,6 +2273,7 @@ impl SourceLayer { window: _, render_lod: _, render_view: _, + render_drawn: _, pending: _, projection: _, ready_cache: _, diff --git a/crates/map/src/source/drawn_index.rs b/crates/map/src/source/drawn_index.rs new file mode 100644 index 0000000000..353b433ad0 --- /dev/null +++ b/crates/map/src/source/drawn_index.rs @@ -0,0 +1,335 @@ +//! A streamed source's features indexed by their boxes as drawn on the map (#2788): in map units, +//! after projection, the boxes a frame culls by ([`crate::Layer::projected_extents`]). A frame +//! that reads only the features whose drawn boxes meet its cull extent draws what reading every +//! feature draws, in any projection and from any coordinate system, where the source's own boxes +//! can't say which those are. Built from a frame that read every feature, for one projection and +//! set of datum grids, and shared by render snapshots like the kept view ([`super::render_view`]). +use rustgis_data::source::FeatureSource; +use std::sync::{Arc, Weak}; + +/// How many boxes a node of the index holds. +const NODE: usize = 16; + +/// The memory a feature takes in an index: its id and box (20 bytes), sorted in place where they +/// were gathered, and its share of the nodes above them (a box over 16 features, a box over 256, +/// …: a little over a byte), rounded up. +pub const PACKING_BYTES: usize = 22; + +/// Boxes (f32, rounded outward) packed into a static R-tree: leaves of [`NODE`] boxes sorted by +/// the Sort-Tile-Recursive method (Leutenegger, Lopez and Edgington, "STR: a simple and efficient +/// algorithm for R-tree packing", 1997), each level above them the boxes of the nodes below. +pub struct DrawnBoxes { + /// The features' ids and boxes, sorted into leaves of `NODE`. + leaves: Vec<(u32, [f32; 4])>, + /// From just above the leaves up: each level's boxes, a node's children `NODE` boxes of the + /// level below. + nodes: Vec>, +} + +/// `b` met by `q`, both boxes as `[min x, min y, max x, max y]`. +fn meets(b: &[f32; 4], q: &[f32; 4]) -> bool { + b[0] <= q[2] && b[2] >= q[0] && b[1] <= q[3] && b[3] >= q[1] +} + +/// The box around `boxes`. +fn around<'a>(boxes: impl Iterator) -> [f32; 4] { + boxes.fold([f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY], |a, b| { + [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])] + }) +} + +impl DrawnBoxes { + /// The index of these features' drawn boxes (feature id, box), sorted where they lie: the + /// only memory it adds is the nodes above them. `None` when those can't be held, or `stop` + /// says to give up (it is asked between the steps). Each of its two sorts is one step that + /// doesn't look at `stop`: about a second for millions of features, on the worker that packs + /// it, never the frame. + pub fn new(mut boxes: Vec<(u32, [f32; 4])>, stop: impl Fn() -> bool) -> Option { + let centre = |b: &[f32; 4], axis: usize| f64::from(b[axis]) + f64::from(b[axis + 2]); + // Sort-Tile-Recursive: in vertical slices of whole leaves by x, each slice by y. + boxes.sort_unstable_by(|a, b| centre(&a.1, 0).total_cmp(¢re(&b.1, 0))); + if stop() { + return None; + } + let leaves = boxes.len().div_ceil(NODE); + let slice = (leaves as f64).sqrt().ceil().max(1.0) as usize * NODE; + for s in boxes.chunks_mut(slice) { + s.sort_unstable_by(|a, b| centre(&a.1, 1).total_cmp(¢re(&b.1, 1))); + } + if stop() { + return None; + } + boxes.shrink_to_fit(); + let mut nodes: Vec> = Vec::new(); + let mut up = Vec::new(); + up.try_reserve_exact(leaves).ok()?; + up.extend(boxes.chunks(NODE).map(|c| around(c.iter().map(|(_, b)| b)))); + while up.len() > 1 { + let mut next = Vec::new(); + next.try_reserve_exact(up.len().div_ceil(NODE)).ok()?; + next.extend(up.chunks(NODE).map(|c| around(c.iter()))); + nodes.push(std::mem::replace(&mut up, next)); + } + nodes.push(up); + Some(DrawnBoxes { leaves: boxes, nodes }) + } + + /// How many features it holds. + pub fn len(&self) -> usize { + self.leaves.len() + } + + /// Whether it holds none. + pub fn is_empty(&self) -> bool { + self.leaves.is_empty() + } + + /// The memory it holds. + pub fn bytes(&self) -> usize { + self.leaves.capacity() * std::mem::size_of::<(u32, [f32; 4])>() + + self.nodes.iter().map(|l| l.capacity() * std::mem::size_of::<[f32; 4]>()).sum::() + } + + /// The ids of the features whose boxes meet `q`, in order; `None` when more than `most` do, + /// or `stop` says to give up (it is asked as the search goes). + pub fn query(&self, q: [f32; 4], most: usize, stop: impl Fn() -> bool) -> Option> { + if stop() { + return None; + } + let mut out = Vec::new(); + // The levels from the top down, the leaves (level 0) last. + let top = self.nodes.len(); + let mut stack = vec![(top, 0usize)]; + let mut looked = 0usize; + while let Some((level, i)) = stack.pop() { + looked += 1; + if looked.is_multiple_of(4096) && stop() { + return None; + } + if level == 0 { + if let Some((id, b)) = self.leaves.get(i) + && meets(b, &q) + { + out.push(u64::from(*id)); + if out.len() > most { + return None; + } + } + continue; + } + let Some(b) = self.nodes.get(level - 1).and_then(|l| l.get(i)) else { continue }; + if !meets(b, &q) { + continue; + } + let below = if level == 1 { self.leaves.len() } else { self.nodes.get(level - 2).map_or(0, Vec::len) }; + stack.extend((i * NODE..((i + 1) * NODE).min(below)).map(|c| (level - 1, c))); + } + out.sort_unstable(); + Some(out) + } +} + +/// The index kept for a source: for one projection and set of datum grids (its key), or none, +/// with whether one was found too large to keep for them. +#[derive(Default)] +pub(super) struct DrawnIndex { + source: Option>, + key: String, + boxes: Option>, + /// The memory an index for this key was found to need when it didn't fit: one is gathered + /// again once that much is free. + too_large: Option, + /// The latest room the map gave the index ([`DrawnIndex::trim`]): one packed while the room + /// shrank isn't kept past it. + room: Option, + /// The ticket of the index being packed for this key, off the frame that gathered its boxes: + /// only that packing may keep its index. + building: Option, + /// The last ticket given. + tickets: u64, +} + +impl DrawnIndex { + /// Forgets everything kept for another source or key. + fn follow(&mut self, source: &Arc, key: &str) { + let same = self.source.as_ref().and_then(Weak::upgrade).is_some_and(|old| Arc::ptr_eq(&old, source)); + if !same || self.key != key { + *self = DrawnIndex { + source: Some(Arc::downgrade(source)), + key: key.into(), + tickets: self.tickets, + room: self.room, + ..DrawnIndex::default() + }; + } + } + + /// The index for this key, if one is kept. + pub(super) fn get(&mut self, source: &Arc, key: &str) -> Option> { + self.follow(source, key); + self.boxes.clone() + } + + /// Whether a frame reading every feature should gather their boxes to make one: not when one + /// is kept or was too large for this key. + pub(super) fn wanted(&mut self, source: &Arc, key: &str, share: usize) -> bool { + self.follow(source, key); + self.boxes.is_none() && self.too_large.is_none_or(|need| need <= share) && self.building.is_none() + } + + /// Marks an index as being packed for this key, and gives the ticket it is kept with; `None` + /// when one is kept, being packed, or was too large. + pub(super) fn begin(&mut self, source: &Arc, key: &str, share: usize) -> Option { + if !self.wanted(source, key, share) { + return None; + } + self.tickets += 1; + self.building = Some(self.tickets); + self.building + } + + /// The ticket of the index being packed, if one is. + pub(super) fn building_ticket(&self) -> Option { + self.building + } + + /// Whether one is being packed for this key. + pub(super) fn building(&mut self, source: &Arc, key: &str) -> bool { + self.follow(source, key); + self.building.is_some() + } + + /// Keeps the index packed with `ticket`, when that packing is still the one this slot waits + /// for (not one for a projection, datum grids or source since replaced) and it fits `share` + /// and the latest room: the room left beside it when it was kept, `None` when it wasn't. + /// `None` boxes (its packing couldn't start, or stopped) keep none, to be gathered again. + pub(super) fn finish(&mut self, ticket: u64, boxes: Option, share: usize) -> Option { + if self.building != Some(ticket) { + return None; + } + self.building = None; + let room = self.room.map_or(share, |r| r.min(share)); + match boxes { + Some(b) if b.bytes() <= room => { + let left = room - b.bytes(); + self.boxes = Some(Arc::new(b)); + Some(left) + } + Some(b) => { + self.too_large = Some(b.bytes()); + None + } + None => None, + } + } + + /// Keeps no index for this key: its boxes, `need` bytes, were too large to gather. + pub(super) fn refuse(&mut self, source: &Arc, key: &str, need: usize) { + self.follow(source, key); + self.too_large = Some(need); + self.boxes = None; + } + + /// The memory the kept index holds. + pub(super) fn bytes(&self) -> usize { + self.boxes.as_ref().map_or(0, |b| b.bytes()) + } + + /// Lets the index go when it holds more than `room` bytes. + pub(super) fn trim(&mut self, room: usize) { + self.room = Some(room); + let bytes = self.bytes(); + if bytes > room { + self.boxes = None; + self.too_large = Some(bytes); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A packing keeps its index only while the slot still waits for it: not after the slot + /// moved to another projection (key) and back, nor after another packing began. + #[test] + fn a_packing_keeps_its_index_only_while_the_slot_waits_for_it() { + use rustgis_data::source::{Batch, Request, SourceInfo}; + struct Empty(SourceInfo); + impl FeatureSource for Empty { + fn info(&self) -> &SourceInfo { + &self.0 + } + fn read(&self, _: &Request) -> rustgis_data::Result { + Ok(Batch::default()) + } + } + let info = SourceInfo { + name: "s".into(), + format: "test", + geometry_type: rustgis_data::GeometryType::Polygon, + fields: Vec::new(), + extent: rustgis_geom::Extent::EMPTY, + count: Some(1), + crs: "EPSG:4326".into(), + indexed: true, + notes: Default::default(), + zm_dropped: false, + }; + let source: Arc = Arc::new(Empty(info)); + let one = || DrawnBoxes::new(vec![(1, [0.0, 0.0, 1.0, 1.0])], || false); + let mut slot = DrawnIndex::default(); + let a = slot.begin(&source, "a", 1000).unwrap(); + assert!(slot.begin(&source, "a", 1000).is_none(), "one packing at a time"); + // The view moved to another projection, and back: the first packing is stale. + assert!(slot.begin(&source, "b", 1000).is_some()); + assert!(slot.get(&source, "a").is_none()); + let again = slot.begin(&source, "a", 1000).unwrap(); + assert!(slot.finish(a, one(), 1000).is_none(), "a stale packing keeps nothing"); + assert!(slot.finish(again, one(), 1000).is_some()); + assert!(slot.get(&source, "a").is_some_and(|i| i.len() == 1)); + // The room shrank while one was packed: it isn't kept, and is again once there is room. + slot.trim(0); + assert!(slot.get(&source, "a").is_none()); + assert!(slot.begin(&source, "a", 1).is_none(), "too large for the room now"); + let t = slot.begin(&source, "a", 1000).unwrap(); + assert!(slot.finish(t, one(), 1000).is_none(), "the latest room is 0"); + slot.trim(600); + let t = slot.begin(&source, "a", 1000).unwrap(); + let left = slot.finish(t, one(), 1000); + assert!(left.is_some_and(|l| l < 600), "what the latest room leaves beside it: {left:?}"); + } + + /// The index finds what a scan of every box finds, in id order, over boxes of every size, + /// none, one, and a query of nothing. + #[test] + fn the_index_finds_what_a_scan_finds() { + let mut boxes = Vec::new(); + let mut seed = 7u64; + let mut next = || { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (seed >> 33) as f32 / (1u64 << 31) as f32 + }; + for id in 0..5_000u32 { + let (x, y, w, h) = (next() * 1000.0, next() * 1000.0, next() * next() * 200.0, next() * 3.0); + boxes.push((id * 3 + 1, [x, y, x + w, y + h])); + } + let index = DrawnBoxes::new(boxes.clone(), || false).unwrap(); + assert_eq!(index.len(), 5_000); + for q in [[0.0f32, 0.0, 1000.0, 1000.0], [400.0, 400.0, 420.0, 401.0], [-10.0, -10.0, -1.0, -1.0], [500.0, 0.0, 500.0, 1000.0]] { + let mut scan: Vec = boxes.iter().filter(|(_, b)| meets(b, &q)).map(|(id, _)| u64::from(*id)).collect(); + scan.sort_unstable(); + assert_eq!(index.query(q, usize::MAX, || false), Some(scan.clone()), "{q:?}"); + // Past `most`, none: the caller reads everything. + assert_eq!(index.query(q, scan.len().saturating_sub(1), || false).is_some(), scan.is_empty(), "{q:?}"); + } + assert_eq!(DrawnBoxes::new(Vec::new(), || false).unwrap().query([0.0, 0.0, 1.0, 1.0], 9, || false), Some(vec![])); + let one = DrawnBoxes::new(vec![(9, [1.0, 1.0, 2.0, 2.0])], || false).unwrap(); + assert_eq!( + (one.query([0.0, 0.0, 1.0, 1.0], 9, || false), one.query([3.0, 3.0, 4.0, 4.0], 9, || false)), + (Some(vec![9]), Some(vec![])) + ); + assert!(DrawnBoxes::new(boxes.clone(), || true).is_none(), "a stopped packing gives none"); + assert_eq!(index.query([0.0, 0.0, 1000.0, 1000.0], usize::MAX, || true), None, "a stopped search gives none"); + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 881b210697..9350af8fca 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -2567,15 +2567,37 @@ fn visit_complete( visit_within(source, None, visit) } -/// As [`visit_complete`], for the features a request gives (those whose boxes meet its extent, -/// or its box in the source's own system), or every feature for `None`. +/// What a streamed layer's frame reads to draw its view ([`visit_within`]). +enum ViewRead { + /// The features a request gives: those whose boxes meet its extent, or its box in the + /// source's own system. + Request(rustgis_data::source::Request), + /// The features with these ids, in order, found by their boxes as drawn (#2788). + Ids(Vec), +} + +/// `e` rounded outward to f32, as an index of boxes keeps them. +fn f32_box(e: &Extent) -> [f32; 4] { + let down = |v: f64| { + let f = v as f32; + if f64::from(f) > v { f.next_down() } else { f } + }; + let up = |v: f64| { + let f = v as f32; + if f64::from(f) < v { f.next_up() } else { f } + }; + [down(e.min_x), down(e.min_y), up(e.max_x), up(e.max_y)] +} + +/// As [`visit_complete`], for the features a read gives, or every feature for `None`. fn visit_within( source: &dyn rustgis_data::source::FeatureSource, - request: Option, + read: Option<&ViewRead>, visit: &mut dyn FnMut(Vec) -> rustgis_data::Result<()>, ) -> rustgis_data::Result { - let result = match request { - Some(req) => source.visit_request_chunks(&req, COMPLETE_CHUNK_BYTES, visit)?, + let result = match read { + Some(ViewRead::Request(req)) => source.visit_request_chunks(req, COMPLETE_CHUNK_BYTES, visit)?, + Some(ViewRead::Ids(ids)) => source.visit_ids_chunks(ids, COMPLETE_CHUNK_BYTES, visit)?, None => source.visit_chunks(None, COMPLETE_CHUNK_BYTES, visit)?, }; if !result.complete { @@ -6495,51 +6517,33 @@ fn render_frame( let crs = source.coord_crs(); let view_only = globe.is_none() && !gpu - && source.finds_all_by_area() && matches!(labels_to, Labels::Own | Labels::Turned(_)) && draws_in_view_only(&chunk, !display.paused, shore.is_some()); // On a map drawn in the file's own system. - let own_units = globe.is_none() + let own_map = globe.is_none() && crs != rustgis_data::raster::Crs::LonLat && source.reads_own_box() && flat.held(crs).is_ok_and(|held| held.is_identity()); - let own = view_only && own_units; - let whole = - || rustgis_data::source::Request { extent: None, limit: usize::MAX, own: Some((crs, rustgis_data::source::whole_plane())) }; - let lonlat = !own && crs == rustgis_data::raster::Crs::LonLat && matches!(flat, rustgis_map::projection::Flat::Mercator); - // The box a read of the map extent `e` asks for, in its path's units. - let box_of = |e: &Extent| { - if own { - Some(*e) - } else if lonlat && within_mercator_lats(e) { - lonlat_box(&flat, e) - } else { - None - } - }; - let partial = |b: &Extent| { - let ll = if own { lonlat_box(&flat, b) } else { Some(*b) }; - ll.is_none_or(|ll| !covers_most(&ll, &source.info().extent)) - }; - // A box as a read asks for it. - let ask = |b: Extent| rustgis_data::source::Request { - extent: if own { lonlat_box(&flat, &b) } else { Some(b) }, - limit: usize::MAX, - own: own.then_some((crs, b)), - }; - let near = view_only.then(|| box_of(&ctx.cull)).flatten().filter(partial); - // The source's long loops that only look at Cancel see the frame's stop too. - let _stop = cancel::current().map(rustgis_data::progress::also_stop_when); - // A view read this way is kept with the geometry drawn from it, for the frames of the - // views inside it: the same view again, a short pan, a zoom in, a restyle, an export. - // It is read a margin wider than it draws, so a short pan still finds it, unless a view - // this coarse was too large to keep. It is kept for the projection and the datum grids - // the frame drew with, within what the source's share of the map's view memory leaves - // beside its interaction rows. - let res = view.camera.res; + let own_units = view_only && own_map; + let lonlat_box_holds = view_only + && !own_units + && crs == rustgis_data::raster::Crs::LonLat + && matches!(flat, rustgis_map::projection::Flat::Mercator) + && within_mercator_lats(&ctx.cull); + // Both read by the file's own boxes, once a whole read has found them holding their + // shapes. + let own = own_units && source.finds_all_by_area(); + let lonlat = lonlat_box_holds && source.finds_all_by_area(); + // Every other pairing reads by the features' boxes as drawn, once a frame that read + // them all has indexed them (#2788); not one the file's own boxes serve, even before + // they are found holding, which an index would only duplicate, nor a file in + // longitude/latitude on Web Mercator, which draws from its display copy, whose boxes + // aren't gathered (at the latitudes Web Mercator clamps it reads every feature). + let mercator_lonlat = crs == rustgis_data::raster::Crs::LonLat && matches!(flat, rustgis_map::projection::Flat::Mercator); + let drawn = view_only && !own_units && !lonlat_box_holds && !mercator_lonlat && source.visits_ids(); // Only while the source is as it was opened: a file changed since reads again, and // one gone fails as a read of it would. - let unchanged = match near.map(|_| source.same_as_opened()) { + let unchanged = match (own || lonlat || drawn).then(|| source.same_as_opened()) { Some(Err(e)) => { if let Some(s) = &mut layer.source { s.error = Some(e.to_string()); @@ -6552,15 +6556,90 @@ fn render_frame( }; let owner = layer.source.as_ref(); let grids = rustgis_data::raster::crs::grid_generation(); - let kept_key = format!("{key} {grids} {}", if own { "own" } else { "lonlat" }); - let room = owner.map_or(0, |o| o.budget().saturating_sub(layer.view_cache_bytes()).min(rustgis_map::source::KEPT_VIEW_BYTES)); - let kept = near.filter(|_| unchanged).and_then(|n| owner?.kept_view(&kept_key, &n, room)); + let path_key = format!( + "{key} {grids} {}", + if own { + "own" + } else if lonlat { + "lonlat" + } else { + "drawn" + } + ); + // Looked up for every frame that may read only its view, so that a packing for another + // key (a projection, datum grids or way of reading since left) no longer counts. + let index = view_only.then(|| owner?.drawn_index(&path_key)).flatten().filter(|_| drawn && unchanged); + // What a frame asks the source for to draw the map extent `e` (the cull extent, or a + // wider one to keep): `None` reads every feature. The box must hold every feature + // drawn in `e`, straight edges and all: + // - on a map drawn in the source's own system (a UTM file on a UTM map, a Web Mercator + // file on Web Mercator), `e` itself, in the file's units: the map draws its geometry + // as it is; + // - on Web Mercator, for a source in longitude/latitude, `e`'s box in + // longitude/latitude, short of the latitudes Web Mercator clamps: Web Mercator maps + // longitude and latitude each on its own, so a feature whose box misses that box is + // drawn wholly outside `e`; + // - otherwise, the features whose boxes as drawn meet `e`, from the index (#2788): the + // boxes the draw loop culls by. + // A box over most of the layer reads it all, in file order: asking for nearly every + // feature costs more than reading the few left over. + let read_of = |e: &Extent| -> Option { + if own { + let ll = lonlat_box(&flat, e); + (!ll.is_some_and(|ll| covers_most(&ll, &source.info().extent))) + .then_some(ViewRead::Request(rustgis_data::source::Request { extent: ll, limit: usize::MAX, own: Some((crs, *e)) })) + } else if lonlat { + let b = lonlat_box(&flat, e).filter(|_| within_mercator_lats(e))?; + (!covers_most(&b, &source.info().extent)).then_some(ViewRead::Request(rustgis_data::source::Request { + extent: Some(b), + limit: usize::MAX, + own: None, + })) + } else { + let index = index.as_ref()?; + // Under half of them, or a stopped frame, which reads no further. + let ids = index.query(f32_box(e), index.len().saturating_sub(1) / 2, cancel::requested)?; + Some(ViewRead::Ids(ids)) + } + }; + // The source's long loops that only look at Cancel see the frame's stop too. + let _stop = cancel::current().map(rustgis_data::progress::also_stop_when); + let near_read = read_of(&ctx.cull); + let near = near_read.is_some().then_some(ctx.cull); + // A view read this way is kept with the geometry drawn from it, for the frames of the + // views inside it: the same view again, a short pan, a zoom in, a restyle, an export. + // It is read a margin wider than it draws, so a short pan still finds it, unless a view + // this coarse was too large to keep. It is kept for the projection, the datum grids and + // the way the frame read, within what the source's share of the map's view memory + // leaves beside its interaction rows and its index; its boxes are in map units. + let res = view.camera.res; + let share = owner.map_or(0, |o| o.budget().saturating_sub(layer.view_cache_bytes())); + let room = share.saturating_sub(owner.map_or(0, |o| o.drawn_index_bytes())).min(rustgis_map::source::KEPT_VIEW_BYTES); + let kept = near.filter(|_| unchanged).and_then(|n| owner?.kept_view(&path_key, &n, room)); let wide = cull_extent(view, KEEP_MARGIN); - let keep = (near.is_some() && unchanged && kept.is_none() && owner.is_some_and(|o| o.view_worth_keeping(&kept_key, res))) - .then(|| box_of(&wide)) - .flatten() - .filter(partial); + let keep = (near.is_some() && unchanged && kept.is_none() && owner.is_some_and(|o| o.view_worth_keeping(&path_key, res))) + .then(|| read_of(&wide).map(|r| (wide, r))) + .flatten(); let mut keeping: Option<(Vec, usize)> = (keep.is_some() || kept.is_some()).then(|| (Vec::new(), 0)); + // A frame reading every feature gathers their boxes as drawn, to index them, unless an + // index is kept or was too large for this key. + // Room for as many as the source says it holds, held at once and sorted where they lie + // to pack the index; none when that doesn't fit the source's share. + let wanted = drawn + && unchanged + && index.is_none() + && near_read.is_none() + && owner.is_some_and(|o| o.drawn_index_wanted(&path_key, share)); + let count = source.info().count.and_then(|n| usize::try_from(n).ok()); + let gathered_too_much = wanted && count.is_some_and(|n| n.saturating_mul(rustgis_map::source::PACKING_BYTES) > share); + let mut gathering: Option> = count.filter(|_| wanted && !gathered_too_much).and_then(|n| { + let mut boxes = Vec::new(); + boxes.try_reserve_exact(n).ok().map(|()| boxes) + }); + // Records the read left out: one it couldn't read this time may read on another. + let mut skipped = 0usize; + // The view's own read isn't needed when a wider one is read to keep: its ids let go. + let near_read = near_read.filter(|_| keep.is_none()); let mut draw_rows = |chunk: &mut rustgis_map::Layer| -> rustgis_data::Result<()> { chunk.selection = chunk .dataset @@ -6578,6 +6657,29 @@ fn render_frame( chunks.clear(); } } + // Each row's box as the frame culled it; a chunk drawn without them (or an id an + // index can't hold) leaves the index unmade. + let gathered = gathering.as_mut().is_some_and(|boxes| { + let extents = chunk.projected_extents(); + chunk.is_cached(&key) + && extents.len() == chunk.dataset.features.len() + && chunk.dataset.features.rows().zip(extents).all(|(row, e)| { + // A shape of another kind than the layer's (a malformed file) may be + // drawn past its box (a point's marker): no index. + row.geometry().is_none_or(|g| g.kind() == chunk.dataset.geometry_type) + && (e.is_empty() + // Never more than it has room for: a source that gives more + // than it said gets no index. + || (boxes.len() < boxes.capacity() + && u32::try_from(row.id()).is_ok_and(|id| { + boxes.push((id, f32_box(e))); + true + }))) + }) + }); + if !gathered { + gathering = None; + } chunk.clear_cache(); chunk.dataset.features = Vec::new().into(); Ok(()) @@ -6591,29 +6693,57 @@ fn render_frame( chunk.draw_rows_of(rows); draw_rows(&mut chunk) }), - // A read of every feature on a map in the file's own system takes those - // longitude/latitude can't place too, as a read of the view there does. - None => visit_within(source.as_ref(), keep.or(near).map(ask).or_else(|| own_units.then(whole)), &mut |features| { - // A frame no longer wanted reads no further (see `cancel`). - if cancel::requested() { - return Err(rustgis_data::DataError::Cancelled); - } - chunk.clear_cache(); - chunk.dataset.features = features.into(); - chunk.touch_geometry(); - draw_rows(&mut chunk) - }) - .map(|_| ()), + None => { + // A read of every feature on a map in the file's own system takes those + // longitude/latitude can't place too, as a read of the view there does. + let whole = own_map.then(|| { + ViewRead::Request(rustgis_data::source::Request { + extent: None, + limit: usize::MAX, + own: Some((crs, rustgis_data::source::whole_plane())), + }) + }); + let read = keep.as_ref().map(|(_, r)| r).or(near_read.as_ref()).or(whole.as_ref()); + visit_within(source.as_ref(), read, &mut |features| { + // A frame no longer wanted reads no further (see `cancel`). + if cancel::requested() { + return Err(rustgis_data::DataError::Cancelled); + } + chunk.clear_cache(); + chunk.dataset.features = features.into(); + chunk.touch_geometry(); + draw_rows(&mut chunk) + }) + .map(|batch| skipped = batch.skipped) + } }; // Kept only when drawn whole, for the datum grids there still are. - if let (Ok(()), Some(owner), Some((chunks, bytes))) = (&result, owner, keeping) + if let (Ok(()), Some(owner)) = (&result, owner) && rustgis_data::raster::crs::grid_generation() == grids { - let fits = bytes <= room; - match (keep, &kept) { - (Some(read), _) => owner.keep_view(&kept_key, read, res, fits.then_some((chunks, bytes))), - (None, Some(drawn)) if fits => owner.refresh_kept_view(&kept_key, drawn, chunks, bytes), - _ => {} + // Not a view a record was left out of: one it couldn't read this time may read on + // another. + if let Some((chunks, bytes)) = keeping.filter(|_| skipped == 0) { + let fits = bytes <= room; + match (keep, &kept) { + (Some((read, _)), _) => owner.keep_view(&path_key, read, res, fits.then_some((chunks, bytes))), + (None, Some(drawn)) if fits => owner.refresh_kept_view(&path_key, drawn, chunks, bytes), + _ => {} + } + } + // An index is made only from a read that gave every feature of a file as it was + // opened, in a frame still wanted: a feature left out of it would never be read. + if gathered_too_much { + owner.refuse_drawn_index(&path_key, count.unwrap_or(0).saturating_mul(rustgis_map::source::PACKING_BYTES)); + } else if let Some(boxes) = gathering.filter(|_| skipped == 0 && !cancel::requested()) + && source.same_as_opened().is_ok_and(|same| same) + { + owner.index_drawn_boxes(&path_key, boxes, share); + } else if wanted && !cancel::requested() && source.same_as_opened().is_ok_and(|same| same) { + // Gathered for nothing (a record left out, a row of another kind, more rows + // than the source said): the next whole read would be the same, so none is + // gathered again for this key, until the source is opened again. + owner.refuse_drawn_index(&path_key, usize::MAX); } } // Declined (`pictureless`): no frame, whatever the source made of the stop. @@ -7009,12 +7139,14 @@ fn layer_masks( && crs != rustgis_data::raster::Crs::LonLat && source.reads_own_box() && held.as_ref().is_some_and(|h| h.is_identity())) - .then(|| rustgis_data::source::Request { - extent: None, - limit: usize::MAX, - own: Some((crs, rustgis_data::source::whole_plane())), + .then(|| { + ViewRead::Request(rustgis_data::source::Request { + extent: None, + limit: usize::MAX, + own: Some((crs, rustgis_data::source::whole_plane())), + }) }); - let result = visit_within(source.as_ref(), whole, &mut |features| { + let result = visit_within(source.as_ref(), whole.as_ref(), &mut |features| { for feature in features { if let Some(g) = feature.geometry { let g = match (ctx.globe.is_some(), crs == rustgis_data::raster::Crs::LonLat) { diff --git a/crates/render/src/stream_tests.rs b/crates/render/src/stream_tests.rs index 1370de011f..2ddc79d82c 100644 --- a/crates/render/src/stream_tests.rs +++ b/crates/render/src/stream_tests.rs @@ -2013,6 +2013,20 @@ impl FeatureSource for Asked { self.asked.lock().unwrap().push(extent.map(|extent| Request { extent: Some(extent), limit: usize::MAX, own: None })); self.inner.visit_chunks(extent, bytes, visit) } + fn visits_ids(&self) -> bool { + self.inner.visits_ids() + } + /// Kept as a request of no extent with the number of ids as its limit (a read by ids), then + /// answered. + fn visit_ids_chunks( + &self, + ids: &[u64], + bytes: usize, + visit: &mut dyn FnMut(Vec) -> rustgis_data::Result<()>, + ) -> rustgis_data::Result { + self.asked.lock().unwrap().push(Some(Request { extent: None, limit: ids.len(), own: None })); + self.inner.visit_ids_chunks(ids, bytes, visit) + } /// Kept as asked, then answered by the wrapped source. fn visit_request_chunks( &self, @@ -2027,7 +2041,8 @@ impl FeatureSource for Asked { /// A projected Shapefile on a map drawn in its own system reads only the view, by the view's box /// in the file's units, and draws what reading the whole file drew (#2788); on a map in another -/// system it reads everything. A Web Mercator file on Web Mercator does the same. +/// system it reads by no box (by its index of boxes as drawn). A Web Mercator file on Web +/// Mercator reads by its box too. #[test] fn a_shapefile_on_a_map_in_its_own_system_reads_the_view_in_its_units() { use rustgis_data::raster::Crs; @@ -2098,7 +2113,150 @@ fn a_shapefile_on_a_map_in_its_own_system_reads_the_view_in_its_units() { assert_eq!(asked_crs, crs, "{what}"); assert!(b.width() < 10_000.0 && b.intersects(&Extent::new(x0, y0, x0 + 40_000.0, y0 + 40_000.0)), "{what}: {b:?}"); } else { - assert!(by_box.is_empty(), "{what}: a map in another system reads everything, not {by_box:?}"); + // A map in another system reads by the features' boxes as drawn (#2788), not by a box. + assert!( + by_box.iter().all(|r| r.own.is_none() && r.extent.is_none()), + "{what}: a map in another system reads by its index, not {by_box:?}" + ); + } + } +} + +/// How many reads a recording source has been asked. +fn asked_len(asked: &std::sync::Mutex>>) -> usize { + asked.lock().unwrap().len() +} + +/// A streamed Shapefile on a map that doesn't draw it as it is (a UTM file on Web Mercator or +/// Robinson, a longitude/latitude file on Robinson) reads every feature on its first frame and +/// indexes their boxes as drawn; the frames after read only the features that index finds in the +/// view, by id, and draw what the whole read drew (#2788). That includes a long line drawn +/// straight across the view on Robinson while its box in the file misses the view's box. +#[test] +fn a_shapefile_on_another_map_reads_the_view_by_its_boxes_as_drawn() { + use rustgis_data::raster::Crs; + use std::sync::{Arc, Mutex}; + rustgis_data::source::shp::use_temporary_index_dir(); + let dir = tempfile::tempdir().unwrap(); + let utm = Crs::from_epsg(32631).unwrap(); + let robinson = rustgis_map::Projection::Custom("robinson".into()); + let squares = |x0: f64, y0: f64, step: f64| { + let mut ds = Dataset::new("squares", GeometryType::Polygon, vec![Field::new("name", FieldType::Text)]); + for i in 0..40 { + for j in 0..40 { + let (x, y) = (x0 + f64::from(i) * step, y0 + f64::from(j) * step); + let w = step * 0.6; + let ring = vec![Coord::new(x, y), Coord::new(x + w, y), Coord::new(x + w, y + w), Coord::new(x, y + w), Coord::new(x, y)]; + ds.push(Some(Geometry::Polygon(vec![vec![ring]])), vec![Value::Text(format!("s{i}-{j}"))]); + } } + ds + }; + // A line from 60°E on the equator to 60°E at 80°N, beside squares of a degree. + let mut lines = Dataset::new("lines", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + lines.push(Some(Geometry::Line(vec![vec![Coord::new(60.0, 0.0), Coord::new(60.0, 80.0)]])), vec![Value::Text("long".into())]); + for i in 0..40 { + for j in 0..40 { + let (x, y) = (f64::from(i) - 20.0, f64::from(j) - 20.0); + lines.push( + Some(Geometry::Line(vec![vec![Coord::new(x, y), Coord::new(x + 0.6, y + 0.6)]])), + vec![Value::Text(format!("l{i}-{j}"))], + ); + } + } + let cases: [(&str, Dataset, Crs, rustgis_map::Projection); 3] = [ + ("utm on web mercator", squares(440_000.0, 5_400_000.0, 1000.0), utm, rustgis_map::Projection::default()), + ("utm on robinson", squares(440_000.0, 5_400_000.0, 1000.0), utm, robinson.clone()), + ("long line on robinson", lines, Crs::LonLat, robinson), + ]; + for (what, mut ds, crs, projection) in cases { + ds.held_in = crs; + let path = dir.path().join(format!("{}.shp", what.replace(' ', "-"))); + rustgis_data::io::write_path_in(&ds, &path, crs).unwrap(); + let mut base = Map::new("drawn"); + base.basemap = rustgis_map::Basemap::Blank; + base.projection = projection; + let opened = rustgis_data::source::shp::ShpSource::open_path(&path, "drawn").unwrap(); + let mut held = ds.clone(); + held.fields = opened.info().fields.clone(); + base.add_dataset(held); + let asked = Arc::new(Mutex::new(Vec::new())); + let asked_handle = Arc::clone(&asked); + let mut actual = base.clone(); + let mut layer = streamed(&base.layers[0], usize::MAX); + layer.source = + Some(SourceLayer::from_path(path.to_string_lossy(), None, Box::new(Asked { inner: Box::new(opened), asked: asked.clone() }))); + actual.layers[0] = layer; + let flat = actual.flat(); + // The long line's middle as drawn (its two ends' places, halfway), else the squares' middle. + let center = if what.starts_with("long") { + let (a, b) = (flat.forward(Coord::new(60.0, 0.0)).unwrap(), flat.forward(Coord::new(60.0, 80.0)).unwrap()); + Coord::new((a.x + b.x) / 2.0, (a.y + b.y) / 2.0) + } else { + flat.forward(Coord::new(2.25, 48.9)).unwrap() + }; + let view = View { width: 320.0, height: 240.0, pixels_per_point: 1.0, camera: Camera::new(center, 40.0), sky: false }; + // The first frame reads every feature and has their boxes indexed off the frame; the + // frames after read every feature until the index lands, then only those it finds. + let by_ids = |r: &Option| r.is_some_and(|r| r.extent.is_none() && r.own.is_none()); + let mut whole = None; + let mut frames = 0; + loop { + let Some(RenderOutput::Cpu(got)) = render_with_backend(&mut actual.clone(), &view, true, Backend::Cpu) else { + panic!("{what}: a complete frame"); + }; + let data = got.pixmap.data(); + let whole = whole.get_or_insert_with(|| data.to_vec()); + assert!(data == whole.as_slice(), "{what}, frame {frames}: the pixels changed"); + assert!(data.chunks(4).any(|p| p != &data[..4]), "{what}: nothing drawn"); + // Every read of the first frame is of every feature: there is no index yet. + if frames == 0 { + let first = asked.lock().unwrap().clone(); + assert!(!first.is_empty() && first.iter().all(Option::is_none), "{what}: the first frame read {first:?}"); + } + frames += 1; + if asked.lock().unwrap().last().is_some_and(by_ids) { + break; + } + assert!(frames < 2_000, "{what}: never read by ids"); + std::thread::sleep(std::time::Duration::from_millis(2)); // test-wait: the index is packed on a worker + } + // One more frame, read by ids too, draws the same. + let Some(RenderOutput::Cpu(got)) = render_with_backend(&mut actual.clone(), &view, true, Backend::Cpu) else { + panic!("{what}: a complete frame"); + }; + assert!(Some(got.pixmap.data()) == whole.as_deref(), "{what}: the pixels changed"); + let asked = asked.lock().unwrap(); + assert_eq!(asked.first(), Some(&None), "{what}: the first frame reads every feature"); + let last = asked.last().copied().flatten().filter(|r| by_ids(&Some(*r))); + // A fifth at most: the view is read a quarter of its size wider on each side, to be kept. + let ids = last.map_or(0, |r| r.limit); + assert!(ids > 0 && ids * 5 < ds.features.len(), "{what}: {ids} of {} features read for the view", ds.features.len()); + drop(asked); + // Zoomed in, a new level of detail decides its thinning from every feature (once a level, + // #1121); the view itself is read by ids, or drawn from the view kept, never whole. + let before = asked_len(&asked_handle); + let zoomed = View { camera: Camera { res: view.camera.res / 2.0, ..view.camera }, ..view }; + let Some(RenderOutput::Cpu(got)) = render_with_backend(&mut actual.clone(), &zoomed, true, Backend::Cpu) else { + panic!("{what}: a zoomed frame"); + }; + // Exactly one read of every feature (the new level's decision), the view itself read by + // ids or drawn from the view kept: a whole read of it would be a second. + let asked = asked_handle.lock().unwrap(); + let zoom = &asked[before..]; + assert!(zoom.iter().filter(|r| r.is_none()).count() == 1 && zoom.iter().all(|r| r.is_none() || by_ids(r)), "{what}: {zoom:?}"); + // And it draws what a source opened afresh, read whole, draws at that zoom. + let mut fresh = base.clone(); + let mut layer = streamed(&base.layers[0], usize::MAX); + layer.source = Some(SourceLayer::from_path( + path.to_string_lossy(), + None, + Box::new(rustgis_data::source::shp::ShpSource::open_path(&path, "drawn").unwrap()), + )); + fresh.layers[0] = layer; + let Some(RenderOutput::Cpu(whole_zoomed)) = render_with_backend(&mut fresh, &zoomed, true, Backend::Cpu) else { + panic!("{what}: a zoomed whole frame"); + }; + assert!(got.pixmap.data() == whole_zoomed.pixmap.data(), "{what}: the zoomed pixels changed"); } }