More refactoring
This commit is contained in:
121
src/graphics.rs
Normal file
121
src/graphics.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
use crate::sprite::{Sprite, SpriteAtlas};
|
||||
|
||||
pub struct GraphicsBuf {
|
||||
buffer: [u8; 8192],
|
||||
sprites: [Sprite; 30],
|
||||
sprite_atlas: SpriteAtlas,
|
||||
}
|
||||
|
||||
impl GraphicsBuf {
|
||||
pub fn new() -> Self {
|
||||
let sprite_atlas = SpriteAtlas::new(include_bytes!("../sprites/sprites_atlas.bin"));
|
||||
|
||||
let mut sprites = [Sprite::new(); 30];
|
||||
|
||||
sprites[0].sprite_index = 94;
|
||||
sprites[0].x = 90;
|
||||
sprites[0].y = 30;
|
||||
sprites[0].visible = true;
|
||||
|
||||
GraphicsBuf {
|
||||
buffer: [0u8; 8192],
|
||||
sprites,
|
||||
sprite_atlas,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.buffer.iter_mut().for_each(|b| *b = 0);
|
||||
}
|
||||
|
||||
pub fn redraw(&mut self) {
|
||||
let mut gfx_buf = &mut self.buffer;
|
||||
|
||||
self.sprites.iter_mut().for_each(|s| {
|
||||
if s.visible {
|
||||
self.sprite_atlas.draw_sprite(
|
||||
s.sprite_index,
|
||||
s.x as u8,
|
||||
s.y as u8,
|
||||
s.flip,
|
||||
&mut gfx_buf,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
self.sprite_atlas
|
||||
.draw_string(10, 10, "Hello World!", &mut gfx_buf);
|
||||
|
||||
self.sprite_atlas.draw_textfield(
|
||||
10,
|
||||
20,
|
||||
110,
|
||||
10,
|
||||
"I think this font has a *lot* of 'character'! ;)",
|
||||
&mut gfx_buf,
|
||||
);
|
||||
|
||||
draw_bresenham_line(0, 0, 127, 0, &mut gfx_buf);
|
||||
draw_bresenham_line(0, 63, 128, 63, &mut gfx_buf);
|
||||
draw_bresenham_line(0, 0, 0, 63, &mut gfx_buf);
|
||||
draw_bresenham_line(127, 0, 127, 63, &mut gfx_buf);
|
||||
}
|
||||
|
||||
pub fn get_px_buffer(&self) -> &[u8; 8192] {
|
||||
&self.buffer
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_bresenham_line(x0: u8, y0: u8, x1: u8, y1: u8, gfx_buf: &mut [u8; 8192]) {
|
||||
let x0 = (x0 as i32).clamp(0, 127);
|
||||
let x1 = (x1 as i32).clamp(0, 127);
|
||||
let y0 = (y0 as i32).clamp(0, 63);
|
||||
let y1 = (y1 as i32).clamp(0, 63);
|
||||
|
||||
let mut dx = x1 - x0;
|
||||
let mut dy = y1 - y0;
|
||||
|
||||
let mut x = x0;
|
||||
let mut y = y0;
|
||||
|
||||
let mut err = 0;
|
||||
|
||||
let mut step_x = 1;
|
||||
let mut step_y = 1;
|
||||
|
||||
if dx < 0 {
|
||||
dx = -dx;
|
||||
step_x = -1;
|
||||
}
|
||||
|
||||
if dy < 0 {
|
||||
dy = -dy;
|
||||
step_y = -1;
|
||||
}
|
||||
|
||||
if dx > dy {
|
||||
for _ in 0..dx {
|
||||
gfx_buf[(y * 128 + x) as usize] = 1;
|
||||
|
||||
x += step_x;
|
||||
err += 2 * dy;
|
||||
|
||||
if err > dx {
|
||||
y += step_y;
|
||||
err -= 2 * dx;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for _ in 0..dy {
|
||||
gfx_buf[(y * 128 + x) as usize] = 1;
|
||||
|
||||
y += step_y;
|
||||
err += 2 * dx;
|
||||
|
||||
if err > dy {
|
||||
x += step_x;
|
||||
err -= 2 * dy;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user