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
//! Wrapper around a pixel buffer.
use vek::{Extent2, Vec2};
/// Simple wrapper around a pixel buffer that can be passed around to rendering calls.
pub struct Canvas<'a> {
/// Size of the canvas in pixels.
pub(crate) size: Extent2<usize>,
/// Reference to the pixel buffer.
pub(crate) buffer: &'a mut [u32],
}
impl<'a> Canvas<'a> {
/// Set a pixel on the buffer at the coordinate passed.
///
/// If the coordinate is out of bounds nothing will be done.
///
/// This is quite a slow operation because it needs to calculate the index of the coordinate, if setting multiple pixels it might be more efficient to create a sprite from them.
#[inline]
pub fn set_pixel(&mut self, position: Vec2<f64>, color: u32) {
if position.x < 0.0
|| position.y < 0.0
|| position.x >= self.size.w as f64
|| position.y >= self.size.h as f64
{
return;
}
let index = position.x as usize + position.y as usize * self.size.w;
if index < self.buffer.len() {
self.buffer[index] = color;
}
}
/// Fill the canvas with a single color.
#[inline]
pub fn fill(&mut self, color: u32) {
self.buffer.fill(color);
}
/// Get the raw buffer of pixels.
#[inline]
pub fn raw_buffer(&mut self) -> &mut [u32] {
self.buffer
}
/// Width in pixels.
#[inline]
pub fn width(&self) -> usize {
self.size.w
}
/// Height in pixels.
#[inline]
pub fn height(&self) -> usize {
self.size.h
}
/// Size in pixels.
#[inline]
pub fn size(&self) -> Extent2<usize> {
self.size
}
}