veloren/world/src/util/grid.rs

75 lines
1.9 KiB
Rust
Raw Normal View History

2019-08-24 13:23:42 +00:00
use vek::*;
pub struct Grid<T> {
cells: Vec<T>,
size: Vec2<i32>,
}
impl<T: Clone> Grid<T> {
pub fn new(default_cell: T, size: Vec2<i32>) -> Self {
Self {
cells: vec![default_cell; size.product() as usize],
size,
}
}
2019-08-24 22:57:55 +00:00
fn idx(&self, pos: Vec2<i32>) -> Option<usize> {
if pos.map2(self.size, |e, sz| e >= 0 && e < sz).reduce_and() {
Some((pos.y * self.size.x + pos.x) as usize)
} else {
None
}
2019-08-24 13:23:42 +00:00
}
pub fn size(&self) -> Vec2<i32> {
self.size
}
pub fn get(&self, pos: Vec2<i32>) -> Option<&T> {
2019-08-24 22:57:55 +00:00
self.cells.get(self.idx(pos)?)
2019-08-24 13:23:42 +00:00
}
pub fn get_mut(&mut self, pos: Vec2<i32>) -> Option<&mut T> {
2019-08-24 22:57:55 +00:00
let idx = self.idx(pos)?;
2019-08-24 13:23:42 +00:00
self.cells.get_mut(idx)
}
2019-08-24 22:57:55 +00:00
pub fn set(&mut self, pos: Vec2<i32>, cell: T) -> Option<()> {
let idx = self.idx(pos)?;
self.cells.get_mut(idx).map(|c| *c = cell)
2019-08-24 13:23:42 +00:00
}
pub fn iter(&self) -> impl Iterator<Item = (Vec2<i32>, &T)> + '_ {
2019-08-28 18:32:44 +00:00
let w = self.size.x;
self.cells
.iter()
.enumerate()
.map(move |(i, cell)| (Vec2::new(i as i32 % w, i as i32 / w), cell))
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = (Vec2<i32>, &mut T)> + '_ {
let w = self.size.x;
self.cells
.iter_mut()
.enumerate()
.map(move |(i, cell)| (Vec2::new(i as i32 % w, i as i32 / w), cell))
2019-08-24 22:57:55 +00:00
}
pub fn iter_area(
&self,
pos: Vec2<i32>,
size: Vec2<i32>,
) -> impl Iterator<Item = Option<(Vec2<i32>, &T)>> + '_ {
(0..size.x)
.map(move |x| {
(0..size.y).map(move |y| {
Some((
pos + Vec2::new(x, y),
&self.cells[self.idx(pos + Vec2::new(x, y))?],
))
})
2019-08-24 13:23:42 +00:00
})
.flatten()
}
}