1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
use crate::{
config::{PIXEL_BUFFER_HEIGHT, PIXEL_BUFFER_WIDTH},
sim::materials::MaterialId,
};
#[derive(Clone, Copy)]
pub struct Cell {
pub material: MaterialId,
pub flags: u8,
}
impl Cell {
pub fn void() -> Cell {
Cell {
material: MaterialId::Void,
flags: 0,
}
}
pub fn from_material(material: MaterialId) -> Cell {
Cell { material, flags: 0 }
}
}
pub struct Board {
pub size_x: u32,
pub size_y: u32,
pub cells: Vec<Cell>,
}
impl Board {
pub fn index_to_position(&self, idx: usize) -> (i32, i32) {
let y = idx / self.size_x as usize;
let x = idx % self.size_x as usize;
let board_x = x as i32 - self.size_x as i32 / 2;
let board_y = y as i32 - self.size_x as i32 / 2;
return (board_x, board_y);
}
pub fn set_cell_at_position(&mut self, x: i32, y: i32, c: Cell) {
// TODO: option?
let idx = self.position_to_index(x, y).unwrap();
self.cells[idx] = c;
}
pub fn cell_at_position(&self, x: i32, y: i32) -> Option<Cell> {
Some(self.cells[self.position_to_index(x, y)?])
}
pub fn position_to_index(&self, x: i32, y: i32) -> Option<usize> {
let board_x = x + self.size_x as i32 / 2;
let board_y = y + self.size_y as i32 / 2;
let on_board = board_x >= 0
&& board_x < self.size_x as i32
&& board_y >= 0
&& board_y < self.size_y as i32;
if !on_board {
return None;
}
return Some((board_y * self.size_x as i32 + board_x) as usize);
}
pub fn empty() -> Board {
let size_x = PIXEL_BUFFER_WIDTH * 2;
let size_y = PIXEL_BUFFER_HEIGHT * 2;
let cells: Vec<Cell> = vec![Cell::void(); (size_x * size_y) as usize];
Board {
size_x,
size_y,
cells,
}
}
}
|