Struct SpatialGrid

pub struct SpatialGrid { /* private fields */ }

Implementations§

§

impl SpatialGrid

pub fn new(cell_size: f64, capacity: usize) -> Result<SpatialGrid, SpatialError>

pub fn insert(&mut self, id: u64, point: [f64; 2]) -> Result<(), SpatialError>

Move or insert atomically. Invalid positions preserve any previous location.

pub fn remove(&mut self, id: u64) -> bool

pub fn query( &self, min: [f64; 2], max: [f64; 2], ) -> Result<Vec<u64>, SpatialError>

Inclusive axis-aligned point query with stable ascending IDs and exact filtering. Returns every match. Use Self::query_into for bounded, reusable output.

pub fn query_into( &self, min: [f64; 2], max: [f64; 2], out: &mut [u64], ) -> Result<SpatialQueryReport, SpatialError>

Query into a caller-provided buffer without allocating.

Uses the same inclusive bounds, exact point filtering and ascending ID order as Self::query. Writes the smallest matching IDs to out[..report.written], leaving the rest untouched. out.len() limits output, not query work: all matching points in the visited cells are counted in report.total, even when out is empty. Check SpatialQueryReport::is_truncated before treating the output as complete.

Returns SpatialError::Invalid for reversed bounds, nonfinite coordinates or coordinates outside the grid’s cell range, and SpatialError::QueryTooLarge for bounds spanning more than 4096 cells. On error, out is unchanged, including when it has zero length.

The buffer doubles as a bounded max-heap during traversal, so retaining each match takes at most logarithmic work in the buffer length; only the written prefix is sorted afterward. No scratch allocation is needed.

use ferravex_engine::spatial::SpatialGrid;

let mut grid = SpatialGrid::new(1.0, 3)?;
grid.insert(30, [-1.0, 0.0])?;
grid.insert(10, [1.0, 0.0])?;
grid.insert(20, [0.0, 0.0])?;
let mut ids = [0; 2];
let report = grid.query_into([-1.0, 0.0], [1.0, 0.0], &mut ids)?;
assert_eq!(&ids[..report.written], &[10, 20]);
assert_eq!(report.total, 3);
assert!(report.is_truncated());

pub fn query_radius_into( &self, center: [f64; 2], radius: f64, out: &mut [SpatialMatch], ) -> Result<SpatialQueryReport, SpatialError>

Inclusive circular point query, ranked by squared distance then ID.

Equivalent to Self::query_nearest_into with k = out.len(). All points inside the circle are counted, even with empty output. Retains the closest out.len() matches, writes only out[..report.written], and leaves the tail untouched. Inspect SpatialQueryReport::is_truncated for omitted points. See Self::query_nearest_into for numeric, work and error bounds.

use ferravex_engine::spatial::{SpatialGrid, SpatialMatch};
let mut grid = SpatialGrid::new(1.0, 3)?;
grid.insert(1, [2.0, 2.0])?; // In the bounding square, outside the circle.
grid.insert(2, [2.0, 0.0])?; // Exactly on the inclusive boundary.
grid.insert(9, [0.0, 0.0])?;
let mut out = [SpatialMatch::default(); 3];
let report = grid.query_radius_into([0.0; 2], 2.0, &mut out)?;
assert_eq!((report.written, report.total), (2, 2));
assert!(!report.is_truncated());
assert_eq!((out[0].id, out[1].id), (9, 2));
assert_eq!(out[2], SpatialMatch::default());

pub fn query_nearest_into( &self, center: [f64; 2], radius: f64, k: usize, out: &mut [SpatialMatch], ) -> Result<SpatialQueryReport, SpatialError>

Select at most k nearest points within an inclusive, bounded circle.

Every candidate in the circle’s bounding cells is examined before the final selection is returned; a farther, lower ID cannot hide a closer point. Results are ordered by ascending squared distance, then ascending ID. Writes min(k, out.len(), total) results, preserving the unwritten tail. total counts all circle matches, including those omitted by either k or storage capacity. k == 0 or empty output is count-only, with the same validation and traversal as a query that writes results.

The caller buffer serves as a bounded max-heap; no query allocation or whole-grid scan occurs. Work is bounded by 4096 bounding cells, their occupants (at most the grid’s point capacity), logarithmic heap work per match, and an in-place sort of the written prefix. A small k does not reduce candidate traversal. Choose cell size and radius together.

§Numeric limits and errors

Returns SpatialError::Invalid for nonfinite centers, negative/nonfinite radius, an overflowing radius * radius, or bounding coordinates center +/- radius that are nonfinite or outside the existing i32 cell range. The bounding square is never silently clipped. Returns SpatialError::QueryTooLarge if that square spans more than 4096 cells, even for an empty grid, k == 0, or empty output. All errors leave the entire caller buffer unchanged.

Circle filtering compares dx * dx + dy * dy <= radius * radius without an epsilon. Overflowing candidate distances are outside a valid radius and are omitted. When the radius square is subnormal or underflows, the comparison instead uses radius-normalized deltas to avoid admitting the square’s corners. A zero radius matches only equal stored coordinates (including signed zero). Returned squared distances still use ordinary f64 arithmetic: underflow/rounding ties are resolved by ID. These are floating-point geometric tests, not exact real arithmetic.

§Tower-target recipe

Store eligible targets, update their positions on executed simulation ticks, and remove expired IDs. This recipe selects from stored point data without duplicating positions. The accepted target ID can then be kept by a projectile independently of later queries. Faction, visibility and game-specific eligibility belong to the caller; filtering a truncated prefix afterward may miss an eligible target farther away.

use ferravex_engine::spatial::{SpatialError, SpatialGrid, SpatialMatch};

fn main() -> Result<(), SpatialError> {
    let mut targets = SpatialGrid::new(4.0, 64)?;
    targets.insert(1, [6.0, 0.0])?;
    targets.insert(90, [1.0, 1.0])?;
    targets.insert(91, [2.0, 0.0])?;
    targets.insert(90, [1.0, 0.0])?; // Move on an executed tick.
    targets.remove(91); // Despawn before selecting a target.

    let tower = [0.0, 0.0];
    let mut nearest = [SpatialMatch::default(); 1];
    let report = targets.query_nearest_into(tower, 8.0, 1, &mut nearest)?;
    assert_eq!(report.total, 2);
    assert!(report.is_truncated()); // One intentionally omitted target.
    if let Some(target) = nearest[..report.written].first() {
        let accepted_target_id = target.id;
        let aim_delta = [target.point[0] - tower[0], target.point[1] - tower[1]];
        assert_eq!((accepted_target_id, aim_delta), (90, [1.0, 0.0]));
        assert_eq!(target.distance_squared, 1.0);
    }
    Ok(())
}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.