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
73
74
75
76
77
78
79
80
81
|
pub use colour::Colour;
pub type Point = geometry::Point<i32>;
pub type Dimensions = geometry::Dimensions<u32>;
pub type Rect = geometry::Rect<i32, u32>;
pub use geometry::HasDimensions;
pub struct Buffer {
array: Vec<Colour>,
dimensions: Dimensions,
}
impl Buffer {
pub const ZERO: Buffer = Buffer { array: Vec::new(), dimensions: Dimensions::ZERO };
pub fn new(dimensions: Dimensions) -> Self {
let array = vec![Colour::BLACK; dimensions.area_usize()];
Self { array, dimensions }
}
pub fn new_with_fill(dimensions: Dimensions, colour: Colour) -> Self {
let array = vec![colour; dimensions.area_usize()];
Self { array, dimensions }
}
pub fn fill(&mut self, colour: Colour) {
self.array.iter_mut().for_each(|c| *c = colour);
}
pub fn copy_into(&mut self, coords: Point, other: &Buffer) {
let self_rect = Rect::from(self.dimensions);
let other_rect = Rect::construct(coords, other.dimensions);
let intersection = self_rect.intersect(other_rect);
if intersection.dimensions().is_zero() { return }
// Find where the origin of the intersection rect sits within both buffers.
let other_point = intersection.origin - coords;
let self_point = intersection.origin;
let mut other_i = (other.width() as usize * other_point.y as usize) + other_point.x as usize;
let mut self_i = (self.width() as usize * self_point.y as usize) + self_point.x as usize;
let inter_width = intersection.width() as usize;
let other_width = other.width() as usize;
let self_width = self.width() as usize;
let other_slice = other.as_slice();
let self_slice = self.as_mut_slice();
for _ in 0..intersection.height() {
let self_row = &mut self_slice[self_i .. self_i+inter_width];
let other_row = &other_slice[other_i .. other_i+inter_width];
self_row.copy_from_slice(other_row);
other_i += other_width;
self_i += self_width;
}
}
pub fn resize(&mut self, dimensions: Dimensions) {
self.array.resize(dimensions.area_usize(), Colour::BLACK);
self.dimensions = dimensions;
}
pub fn as_rows(&self) -> std::slice::ChunksExact<Colour> {
self.array.chunks_exact(self.dimensions.width as usize)
}
pub fn as_slice(&self) -> &[Colour] {
&self.array
}
pub fn as_mut_slice(&mut self) -> &mut [Colour] {
&mut self.array
}
pub fn as_u32_slice(&self) -> &[u32] {
unsafe { std::mem::transmute::<&[Colour], &[u32]>(&self.array) }
}
}
impl HasDimensions<u32> for Buffer {
fn dimensions(&self) -> Dimensions { self.dimensions }
}
impl std::ops::Index<usize> for Buffer {
type Output = Colour;
fn index(&self, i: usize) -> &Colour { &self.array[i] }
}
impl std::ops::IndexMut<usize> for Buffer {
fn index_mut(&mut self, i: usize) -> &mut Colour { &mut self.array[i] }
}
|