Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions crates/engine/src/cmd/design.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1466,9 +1466,10 @@ fn edit_vertex(s: &mut Session, p: &Json) -> CmdResult {
/// same system that one of its other places reads exactly as (a vertex snapped to, a feature
/// pasted where it was copied from). Each other place is converted on its own to find what is
/// stored near it, so no stored place is missed however large the edit, and only stored places
/// one of them reads as are held. The search reads the box of every feature of the layers in its
/// system, each from its vertices, once a command (an added feature, a paste): work that grows
/// with those layers, which C2 is to take to a spatial index.
/// one of them reads as are held. The features near them are found through each layer's grid of
/// boxes ([`rustgis_map::Layer::rows_touching`]), made once until that layer's rows change: the
/// first search after an edit walks the edited layer's rows again to make its grid (as the search
/// before the grid did each time), the other layers of its system keep theirs.
/// Empty while the layer is in longitude/latitude: its edits are written as they are.
pub(crate) fn held_places(s: &Session, id: u32, originals: &[&Geometry], edited: &[&Geometry]) -> rustgis_data::HeldPlaces {
let mut held = rustgis_data::HeldPlaces::default();
Expand Down Expand Up @@ -1498,8 +1499,8 @@ pub(crate) fn held_places(s: &Session, id: u32, originals: &[&Geometry], edited:
return held;
}
for m in s.map().layers.iter().filter(|m| !m.is_raster() && m.dataset.coord_crs() == system) {
for f in &m.dataset.features {
if let Some(g) = &f.geometry
for row in m.rows_touching(&within) {
if let Some(g) = m.dataset.features.geometry(row)
&& g.extent().intersects(&within)
{
m.dataset.hold_places(g, Some(&within), &mut held);
Expand Down
14 changes: 14 additions & 0 deletions crates/map/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub mod projection;
pub mod qgis;
pub mod raster;
pub mod report;
mod row_boxes;
pub mod rows;
pub mod shadow;
pub mod slots;
Expand Down Expand Up @@ -350,6 +351,9 @@ pub struct Layer {
/// place of a layer held in another system takes long enough not to do it each frame.
#[serde(skip)]
extent_cache: ExtentCache,
/// A grid of its rows' boxes in its own coordinates, as last made ([`Layer::rows_touching`]).
#[serde(skip)]
row_boxes: row_boxes::Cache,
/// Whether its projected or longitude/latitude copy was used since the map was detached for a
/// drawing ([`Map::detach_reads`]): what an export drew, and so can say of itself.
/// Hit-testing and snapping use them too, but on the live map, which no export reads this
Expand Down Expand Up @@ -565,6 +569,7 @@ impl Layer {
unplaced: Unplaced::default(),
flat_unplaced: Unplaced::default(),
extent_cache: ExtentCache::default(),
row_boxes: Default::default(),
drawn: DrawnBy::default(),
geometry_rev: 0,
view_memory: Default::default(),
Expand Down Expand Up @@ -1689,6 +1694,14 @@ impl Layer {
query.is_filtered().then(|| (0..dataset.features.len()).map(|row| query.matches(dataset, row, env)).collect())
}

/// The rows whose shape's box, in the layer's own coordinates ([`Dataset::coord_crs`]), may
/// meet `within`: every row whose box does, perhaps some whose box doesn't, never one without
/// a shape; each once, in order. Looked up in a grid kept until the rows change (#2032
/// C2f-6), so a search near an edit doesn't read every feature.
pub fn rows_touching(&self, within: &Extent) -> Vec<usize> {
self.row_boxes.touching(&self.dataset.features, within)
}

/// Extent in longitude/latitude.
pub fn extent(&self) -> Extent {
match (&self.raster, &self.source) {
Expand Down Expand Up @@ -3735,6 +3748,7 @@ impl Layer {
unplaced: _,
flat_unplaced: _,
extent_cache: _,
row_boxes: _,
drawn: _,
view_memory: _,
geometry_kinds: _,
Expand Down
3 changes: 3 additions & 0 deletions crates/map/src/look.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ fn bare(layer: &Layer) -> Layer {
unplaced: _,
flat_unplaced: _,
extent_cache: _,
row_boxes: _,
drawn: _,
view_memory: _,
geometry_kinds: _,
Expand Down Expand Up @@ -176,6 +177,7 @@ fn bare(layer: &Layer) -> Layer {
unplaced: Default::default(),
flat_unplaced: Default::default(),
extent_cache: Default::default(),
row_boxes: Default::default(),
drawn: Default::default(),
view_memory: Default::default(),
geometry_kinds: Default::default(),
Expand Down Expand Up @@ -274,6 +276,7 @@ impl LayerLook {
unplaced: _,
flat_unplaced: _,
extent_cache: _,
row_boxes: _,
drawn: _,
view_memory: _,
geometry_kinds: _,
Expand Down
256 changes: 256 additions & 0 deletions crates/map/src/row_boxes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,256 @@
//! Which rows of a layer have a shape whose box, in the layer's own coordinates, may meet a given
//! box: a grid of the rows' boxes, kept without retaining the rows until the rows change (any
//! edit makes them other rows, as [`Features::allocation_key`] says). The places an edit keeps
//! ([`crate::Layer::rows_touching`]) are looked for through it, so that search no longer reads
//! every feature of every layer in the edited layer's system (#2032 C2f-6).

use std::sync::{Mutex, Weak};

use rustgis_data::{Feature, Features};
use rustgis_geom::Extent;

/// The most cells a row's box is listed in; a box across more is listed as wide, and looked at by
/// every search (a long road among many short ones).
const MAX_CELLS_PER_ROW: usize = 16;

#[derive(Debug, Default)]
struct Grid {
/// The rows the grid was made from, without keeping them.
rows: Weak<Vec<Feature>>,
/// The box all the listed boxes are in.
total: Extent,
cols: usize,
cell_w: f64,
cell_h: f64,
/// Each cell's rows, row by row then column by column.
cells: Vec<Vec<u32>>,
/// Rows whose box spans too many cells.
wide: Vec<u32>,
/// Whether there are rows past `u32::MAX`, which aren't listed.
beyond: bool,
}

#[derive(Debug, Default)]
pub(super) struct Cache(Mutex<Grid>);

/// A copy of a layer starts without a grid, as its rows may soon be other rows than these.
impl Clone for Cache {
fn clone(&self) -> Self {
Cache::default()
}
}

impl Grid {
/// The grid of `rows`' boxes: one walk over every row's vertices, with a box a row (32 bytes)
/// kept only while the grid is made. Capped at 256 by 256 cells, so the cells' own lists stay
/// small (about 1.5 MB at most) whatever the layer's size; a row's box is listed in at most
/// [`MAX_CELLS_PER_ROW`] cells.
fn new(rows: &Features) -> Grid {
// A box per row, empty for a row without a shape or a place (`Geometry::extent` leaves
// out a coordinate that isn't a number, so every other box is finite).
let boxes: Vec<Extent> = (0..rows.len()).map(|i| rows.geometry(i).map_or(Extent::EMPTY, |g| g.extent())).collect();
let total = boxes.iter().fold(Extent::EMPTY, |t, e| if e.is_empty() { t } else { t.union(e) });
let shaped = boxes.iter().filter(|e| !e.is_empty()).count();
// About one row a cell.
let cols = ((shaped as f64).sqrt().ceil() as usize).clamp(1, 256);
let mut grid = Grid {
rows: rows.allocation_key(),
total,
cols,
cell_w: total.width() / cols as f64,
cell_h: total.height() / cols as f64,
cells: vec![Vec::new(); cols * cols],
wide: Vec::new(),
beyond: false,
};
for (i, e) in boxes.iter().enumerate() {
let Ok(row) = u32::try_from(i) else {
// Past 4 billion rows a row can't be listed: every search looks at them all.
grid.beyond = true;
break;
};
match grid.span(e) {
Some((x0, y0, x1, y1)) if (x1 - x0 + 1) * (y1 - y0 + 1) <= MAX_CELLS_PER_ROW => {
for y in y0..=y1 {
for x in x0..=x1 {
grid.cells[y * cols + x].push(row);
}
}
}
Some(_) => grid.wide.push(row),
// No shape, or no place: never meets a box.
None => {}
}
}
grid
}

/// The column and row of the cell `v` is in along one axis, clamped to the grid.
fn cell(&self, v: f64, min: f64, size: f64) -> usize {
if size > 0.0 { (((v - min) / size).floor().max(0.0) as usize).min(self.cols - 1) } else { 0 }
}

/// The cells box `e` meets (first column, first row, last column, last row), `None` when it
/// meets none.
fn span(&self, e: &Extent) -> Option<(usize, usize, usize, usize)> {
if !e.intersects(&self.total) {
return None;
}
let t = &self.total;
Some((
self.cell(e.min_x, t.min_x, self.cell_w),
self.cell(e.min_y, t.min_y, self.cell_h),
self.cell(e.max_x, t.min_x, self.cell_w),
self.cell(e.max_y, t.min_y, self.cell_h),
))
}

/// The rows of the `len` whose box may meet `within`, each once, in order.
fn touching(&self, within: &Extent, len: usize) -> Vec<usize> {
if self.beyond {
return (0..len).collect();
}
let mut found: Vec<u32> = Vec::new();
if let Some((x0, y0, x1, y1)) = self.span(within) {
found.extend_from_slice(&self.wide);
for y in y0..=y1 {
for x in x0..=x1 {
found.extend_from_slice(&self.cells[y * self.cols + x]);
}
}
}
found.sort_unstable();
found.dedup();
found.into_iter().map(|r| r as usize).collect()
}
}

impl Cache {
/// The rows of `rows` whose shape's box may meet `within` (a superset of those that do; never
/// one without a shape), each once, in order. The grid is made again only once the rows
/// change.
pub(super) fn touching(&self, rows: &Features, within: &Extent) -> Vec<usize> {
// The grid is disposable; a poisoned lock does not invalidate the features themselves.
let mut grid = self.0.lock().unwrap_or_else(|e| e.into_inner());
if !grid.rows.ptr_eq(&rows.allocation_key()) {
*grid = Grid::new(rows);
}
grid.touching(within, rows.len())
}
}

#[cfg(test)]
mod tests {
use super::*;
use rustgis_data::{Dataset, Geometry, GeometryType};
use rustgis_geom::Coord;

fn line(a: (f64, f64), b: (f64, f64)) -> Option<Geometry> {
Some(Geometry::Line(vec![vec![Coord::new(a.0, a.1), Coord::new(b.0, b.1)]]))
}

/// The rows meeting `within`, read one by one as the search did before the grid.
fn scanned(ds: &Dataset, within: &Extent) -> Vec<usize> {
(0..ds.features.len()).filter(|&i| ds.features.geometry(i).is_some_and(|g| g.extent().intersects(within))).collect()
}

#[test]
fn the_grid_finds_every_row_a_scan_finds() {
let mut ds = Dataset::new("lines", GeometryType::Polyline, vec![]);
// A thousand short lines on a grid, a long one across them all, one without a shape and
// one with a place that isn't a number.
for i in 0..1000 {
let (x, y) = (f64::from(i % 40) * 1000.0, f64::from(i / 40) * 1000.0);
Comment on lines +161 to +163

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The memory note here (and the PR body, "the cell lists ... at most about 1.5 MB") is not accurate. The 256 by 256 cap bounds only the cell headers: 65,536 empty Vecs at 24 bytes each is about 1.5 MB. The row entries are not capped. Each row is listed in up to MAX_CELLS_PER_ROW (16) cells at 4 bytes each, so a layer of long boxes can keep up to 64 bytes per row (plus Vec capacity slack from doubling). Usually it is 1 to 4 cells, but the comment should say what scales with the rows.

Suggested change
// one with a place that isn't a number.
for i in 0..1000 {
let (x, y) = (f64::from(i % 40) * 1000.0, f64::from(i / 40) * 1000.0);
/// kept only while the grid is made. Capped at 256 by 256 cells, so the cells' headers (24 bytes
/// each) take about 1.5 MB at most; the rows are listed at 4 bytes per cell each, a box in at
/// most [`MAX_CELLS_PER_ROW`] cells.

Category: quality

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in #2906: the comment now says the cap bounds only the cell headers (about 1.5 MB), and that the rows are listed at 4 bytes a cell, in at most 16 cells each.

ds.push(line((x, y), (x + 400.0, y + 300.0)), vec![]);
}
ds.push(line((-5000.0, -5000.0), (50_000.0, 30_000.0)), vec![]);
ds.push(None, vec![]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This Vec<Extent> holds a box for every row (32 bytes a row) and is kept only until the grid is built. On a 10-million-row layer that is about 320 MB allocated on the UI thread, at the first search after each edit, and it is not sized with memory::planned or counted in cargo xtask memory. The AGENTS.md size rule asks for work that grows with its input to go in pieces it doesn't keep. Two options: walk the rows twice (one pass for total and the shaped count, one pass to fill the cells) so no per-row box list is needed, or state the peak in the PR as a multiple of the layer. Please pick one and measure it.

Category: performance

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in #2906: the grid is made in two walks over the rows, one for the box they are all in and one to list each row's box, so no box is kept per row.

ds.push(line((f64::NAN, 3.0), (100.0, 200.0)), vec![]);
let cache = Cache::default();
for within in [
Extent::new(0.0, 0.0, 1.0, 1.0),
Extent::new(2500.0, 2500.0, 3500.0, 3200.0),
Extent::new(-1e9, -1e9, 1e9, 1e9),
Extent::new(39_000.0, 24_000.0, 39_500.0, 24_400.0),
Extent::new(1e7, 1e7, 1e7 + 1.0, 1e7 + 1.0),
Extent::new(100.0, 200.0, 100.0, 200.0),
] {
let found = cache.touching(&ds.features, &within);
let want = scanned(&ds, &within);
assert!(want.iter().all(|r| found.contains(r)), "{within:?}: {want:?} not all in {found:?}");
assert!(found.windows(2).all(|w| w[0] < w[1]));
assert!(found.iter().all(|&r| ds.features.geometry(r).is_some()));
}
// Few rows looked at for a small box, not every one.
assert!(cache.touching(&ds.features, &Extent::new(2500.0, 2500.0, 2600.0, 2600.0)).len() < 20);
}

#[test]
fn the_grid_follows_the_rows_edits() {
let mut ds = Dataset::new("lines", GeometryType::Polyline, vec![]);
for i in 0..100 {
let x = f64::from(i) * 10.0;
ds.push(line((x, 0.0), (x + 1.0, 1.0)), vec![]);
}
let cache = Cache::default();
let there = Extent::new(5000.0, 5000.0, 5001.0, 5001.0);
assert!(cache.touching(&ds.features, &there).is_empty());
let before = ds.features.clone();
ds.features.set_geometry(7, line((5000.5, 5000.5), (5000.6, 5000.6)));
assert_eq!(cache.touching(&ds.features, &there), [7]);
assert!(cache.touching(&before, &there).is_empty());
// Changed in place, with no other copy of the rows.
drop(before);
ds.features.set_geometry(7, line((0.0, 0.0), (1.0, 1.0)));
assert!(cache.touching(&ds.features, &there).is_empty());
}

#[test]
fn a_grid_with_no_width_or_rows_on_cell_edges_finds_them() {
// Every line on x = 100: the boxes' total has no width.
let mut ds = Dataset::new("lines", GeometryType::Polyline, vec![]);
for i in 0..200 {
ds.push(line((100.0, f64::from(i)), (100.0, f64::from(i) + 1.0)), vec![]);
}
let cache = Cache::default();
for within in [Extent::new(100.0, 50.5, 100.0, 50.6), Extent::new(99.0, 199.0, 101.0, 300.0), Extent::new(0.0, 0.0, 99.9, 500.0)] {
let found = cache.touching(&ds.features, &within);
assert!(scanned(&ds, &within).iter().all(|r| found.contains(r)), "{within:?}: {found:?}");
}
// Points exactly on the cells' edges (a 15 by 15 grid of 225 rows over 0..=14).
let mut ds = Dataset::new("points", GeometryType::Point, vec![]);
for i in 0..225 {
ds.push(Some(Geometry::Point(Coord::new(f64::from(i % 15), f64::from(i / 15)))), vec![]);
}
let cache = Cache::default();
for i in 0..225 {
let c = Coord::new(f64::from(i % 15), f64::from(i / 15));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Past u32::MAX rows this returns every row index, including rows with no shape. That breaks the documented contract on Layer::rows_touching ("never gives a row without a shape"). It has no visible effect today because held_places checks geometry(row) and the box for each candidate, and 4 billion rows can't be held in memory. Still, the doc and the code disagree. Either filter out the shapeless rows here (this needs the Features passed in, which touching could take), or reword the rows_touching doc to say that a layer past u32::MAX rows gives every row.

Category: quality

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in #2906: the rows_touching and Cache::touching docs now say that past u32::MAX rows every row is given, including rows without a shape. Its only caller checks each row's shape and box.

let within = Extent::new(c.x, c.y, c.x, c.y);
assert!(cache.touching(&ds.features, &within).contains(&(i as usize)), "{c:?}");
}
}

/// The rows `layer` gives for `within` whose box does meet it.
fn meeting(layer: &crate::Layer, within: &Extent) -> Vec<usize> {
let found = layer.rows_touching(within);
found.into_iter().filter(|&r| layer.dataset.features.geometry(r).is_some_and(|g| g.extent().intersects(within))).collect()
}

#[test]
fn a_layer_looks_up_its_rows_and_a_copy_makes_its_own_grid() {
let mut ds = Dataset::new("lines", GeometryType::Polyline, vec![]);
for i in 0..50 {
let x = f64::from(i) * 10.0;
ds.push(line((x, 0.0), (x + 1.0, 1.0)), vec![]);
}
let mut layer = crate::Layer::new(1, ds);
let near = Extent::new(200.5, 0.5, 200.6, 0.6);
assert_eq!(meeting(&layer, &near), [20]);
let copy = layer.clone();
layer.dataset.features.set_geometry(20, line((900.0, 900.0), (901.0, 901.0)));
layer.touch_geometry();
assert!(meeting(&layer, &near).is_empty());
assert_eq!(meeting(&layer, &Extent::new(900.0, 900.0, 900.5, 900.5)), [20]);
assert_eq!(meeting(&copy, &near), [20]);
}
}
2 changes: 1 addition & 1 deletion xtask/row-uses.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
# down: new code reads and changes rows through the accessors on `Features`
# (crates/data/src/row_access.rs). When a change lowers it, run `cargo xtask rows --update` and
# commit this file with it.
count = 769
count = 768
Loading