made a game

made a snake game and rewrote some rendering stuff again
This commit is contained in:
FantasyPvP
2023-10-02 00:56:18 +01:00
parent f0ee584c87
commit bf9c9be88d
19 changed files with 532 additions and 241 deletions
-1
View File
@@ -3,7 +3,6 @@ pub mod fs;
pub mod gdt;
pub mod interrupts;
pub mod memory;
//pub mod render;
pub mod serial;
pub mod tasks;
pub mod sysinit;
+26 -9
View File
@@ -42,24 +42,30 @@ impl ColorCode {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
struct ScreenChar {
character: u8,
colour: ColorCode,
pub struct ScreenChar {
pub character: u8,
pub colour: ColorCode,
}
impl ScreenChar {
fn null() -> ScreenChar {
pub fn null() -> ScreenChar {
ScreenChar {
character: 0u8,
colour: ColorCode::new(Color::White, Color::Black),
}
}
fn white(character: u8) -> ScreenChar {
pub fn white(character: u8) -> ScreenChar {
ScreenChar {
character,
colour: ColorCode::new(Color::White, Color::Black),
}
}
pub fn new(character: u8, colour: ColorCode) -> ScreenChar {
ScreenChar {
character,
colour,
}
}
}
pub const BUFFER_HEIGHT: usize = 25;
@@ -92,19 +98,26 @@ lazy_static! {
impl Renderer {
// EXTERNAL API : for use by standard library and other parts of the kernel
pub fn render_frame(&mut self, frame: [[char; BUFFER_WIDTH]; BUFFER_HEIGHT]) { // renders the given frame to the app buffer
pub fn render_frame(&mut self, frame: [[ScreenChar; BUFFER_WIDTH]; BUFFER_HEIGHT]) { // renders the given frame to the app buffer
let mut processed_frame: [[ScreenChar; BUFFER_WIDTH]; BUFFER_HEIGHT] = [[ScreenChar::null(); BUFFER_WIDTH]; BUFFER_HEIGHT];
for (i, row) in frame.iter().enumerate() {
for (j, col) in row.iter().enumerate() {
processed_frame[i][j] = match self.special_char(*col) {
Some(c) => ScreenChar::white(c as u8),
None => ScreenChar::white(*col as u8)
processed_frame[i][j] = match self.special_char(col.character as char) {
Some(c) => ScreenChar::new(c as u8, col.colour),
None => *col,
};
}
}
self.app_buffer = processed_frame;
self.internal_render();
}
pub fn terminal_mode_force(&mut self) { // THIS SHOULD ONLY BE USED WHEN THE KERNEL PANICS
// TODO: find a way to make this function kernel only
self.application_mode = false;
self.internal_render();
}
pub fn application_mode(&mut self) -> Result<(), ()> {
@@ -132,11 +145,13 @@ impl Renderer {
}
pub fn write_char(&mut self, ch: u8, col: Option<ColorCode>) { // default colour if no colour is selected for character
if self.application_mode { return; };
self.write_byte(ch, col);
self.internal_render();
}
pub fn write_string(&mut self, string: &str, col: Option<ColorCode>) {
if self.application_mode { return; };
for ch in string.chars() {
match self.special_char(ch) {
Some(c) => self.write_byte(c, col),
@@ -150,6 +165,7 @@ impl Renderer {
}
pub fn backspace(&mut self) -> Result<(), ()> {
if self.application_mode { return Ok(()); };
loop {
if self.internal_backspace()? {
@@ -163,6 +179,7 @@ impl Renderer {
pub fn clear(&mut self) { // clears the screen and all scroll-back
if self.application_mode { return; };
self.term_buffer = vec![[ScreenChar::null(); BUFFER_WIDTH]; BUFFER_HEIGHT];
self.internal_render();
}
@@ -1,4 +1,4 @@
/*
pub mod thread_switch;
@@ -12,4 +12,4 @@ pub struct Thread {
stack_pointer: Option<VirtAddr>,
stack_bounds: Option<StackBounds>,
}
*/
+1
View File
@@ -14,6 +14,7 @@ pub trait Application {
pub enum Error {
UnknownCommand(String),
CommandFailed(String),
ApplicationError(String),
EmptyCommand,
}
+154
View File
@@ -0,0 +1,154 @@
use alloc::string::String;
use alloc::vec::Vec;
use lazy_static::lazy_static;
use crate::kernel::render::{BUFFER_HEIGHT, BUFFER_WIDTH, RENDERER, ScreenChar};
use crate::println;
use spin::Mutex;
/// TODO: get a working implementation for CLI apps
/// elements can be created using their from_str() method
/// you can then render the element to the current frame using the render() method
/// the position of the element by passing a tuple (x,y) to render()
///
/// nothing will appear on the screen until the frame is actually rendered by
/// the render_frame method on the renderer
///
pub type Frame = [ [ ScreenChar; BUFFER_WIDTH ]; BUFFER_HEIGHT];
#[derive(Clone)]
pub struct Element {
frame: Vec<Vec<char>>,
dimensions: (u8, u8)
}
impl Element {
pub fn from_str(elemstr: String) -> Self {
let mut element = Element { frame: Vec::<Vec<char>>::new(), dimensions: (0, 0) };
for line in elemstr.split("\n") {
let mut ln = Vec::<char>::new();
for col in line.chars() {
ln.push(col)
};
element.frame.push(ln);
}
for row in element.clone().frame {
let n = row.len();
if n > element.dimensions.0 as usize {
element.dimensions.0 = n as u8;
}
}
element
}
pub fn generate(frame: Vec::<Vec<char>>, dims: (u8, u8)) -> Self {
Element { frame, dimensions: dims }
}
pub fn render(&mut self, pos: (u8, u8)) { // x,y
for (i, row) in self.frame.iter().enumerate() {
for (j, col) in row.iter().enumerate() {
//println!("{} {} {}", i, j, col);
FRAMEGEN.lock().frame[i + pos.1 as usize][j + pos.0 as usize] = ScreenChar::white(*col as u8);
};
}
FRAMEGEN.lock().render_frame();
}
}
#[derive(Clone)]
pub struct ColouredElement {
frame: Vec<Vec<ScreenChar>>,
dimensions: (u8, u8)
}
impl ColouredElement {
pub fn from_str(elemstr: String) -> Self {
let mut element = ColouredElement { frame: Vec::<Vec<ScreenChar>>::new(), dimensions: (0, 0) };
for line in elemstr.split("\n") {
let mut ln = Vec::<ScreenChar>::new();
for col in line.chars() {
ln.push(ScreenChar::white(col as u8))
};
element.frame.push(ln);
}
for row in element.clone().frame {
let n = row.len();
if n > element.dimensions.0 as usize {
element.dimensions.0 = n as u8;
}
}
element
}
pub fn generate(frame: Vec::<Vec<ScreenChar>>, dims: (u8, u8)) -> Self {
ColouredElement { frame, dimensions: dims }
}
pub fn render(&mut self, pos: (u8, u8)) -> Result<(), ()> { // x,y
// this block returns an error if any characters will be drawn out of the bounds of the screen
if self.dimensions.0 + pos.0 > BUFFER_WIDTH as u8 {
return Err(());
} else if self.dimensions.1 + pos.1 > BUFFER_HEIGHT as u8 {
return Err(());
} else if self.frame.len() != self.dimensions.1 as usize {
return Err(())
} else if self.frame.iter().map(|r| r.len()).max().ok_or_else(|| ())? > self.dimensions.0 as usize {
return Err(())
}
for (i, row) in self.frame.iter().enumerate() {
for (j, col) in row.iter().enumerate() {
//println!("{} {} {}", i, j, col);
FRAMEGEN.lock().frame[i + pos.1 as usize][j + pos.0 as usize] = *col;
};
}
FRAMEGEN.lock().render_frame();
Ok(())
}
}
#[derive(Clone, Copy)]
pub struct FrameGen {
frame: Frame,
}
impl FrameGen {
pub fn render_frame(&self) {
RENDERER.lock().render_frame(self.frame)
}
fn new() -> Self {
let mut frame: [[ScreenChar; BUFFER_WIDTH]; BUFFER_HEIGHT] = [[ScreenChar::null(); BUFFER_WIDTH]; BUFFER_HEIGHT];
Self { frame: Frame::from(frame) }
}
fn set_frame(&mut self, frame: Frame) {
self.frame = frame;
}
pub fn get_frame(&self) -> &[ [ ScreenChar; BUFFER_WIDTH ]; BUFFER_HEIGHT] {
&self.frame
}
}
lazy_static! {
pub static ref FRAMEGEN: Mutex<FrameGen> = Mutex::new(FrameGen::new() );
}
impl core::fmt::Display for FrameGen {
fn fmt(&self, _: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
println!(" ");
for row in &self.frame {
println!("{}", row.iter().map(|c| c.character as char ).collect::<String>());
};
Ok(())
}
}
+14 -137
View File
@@ -1,9 +1,9 @@
use crate::{
kernel::render::{RENDERER, BUFFER_WIDTH, BUFFER_HEIGHT, ColorCode},
kernel::render::{RENDERER, self},
kernel::tasks::keyboard::KEYBOARD,
};
use alloc::{boxed::Box, string::{String, ToString}, vec::Vec};
use alloc::string::String;
pub use crate::{print, println, serial_print, serial_println};
pub use crate::kernel::render::Color;
@@ -45,112 +45,6 @@ impl Screen {
}
/// TODO: get a working implementation for CLI apps
/// elements can be created using their from_str() method
/// you can then render the element to the current frame using the render() method
/// the position of the element by passing a tuple (x,y) to render()
///
/// nothing will appear on the screen until the frame is actually rendered by
/// the render_frame method on the renderer
///
pub type Frame = [ [ char; BUFFER_WIDTH ]; BUFFER_HEIGHT];
#[derive(Clone)]
pub struct Element {
frame: Vec<Vec<char>>,
dimensions: (u8, u8)
}
impl Element {
pub fn from_str(elemstr: String) -> Self {
let mut element = Element { frame: Vec::<Vec<char>>::new(), dimensions: (0, 0) };
for line in elemstr.split("\n") {
let mut ln = Vec::<char>::new();
for col in line.chars() {
ln.push(col)
};
element.frame.push(ln);
}
for row in element.clone().frame {
let n = row.len();
if n > element.dimensions.0 as usize {
element.dimensions.0 = n as u8;
}
}
element
}
pub fn render(&mut self, pos: (u8, u8)) { // x,y
for (i, row) in self.frame.iter().enumerate() {
for (j, col) in row.iter().enumerate() {
println!("{} {} {}", i, j, col);
FRAMEGEN.lock().frame[i + pos.1 as usize][j + pos.0 as usize] = *col;
};
}
}
}
lazy_static! {
pub static ref FRAMEGEN: Mutex<FrameGen> = Mutex::new(FrameGen::new() );
}
#[derive(Clone, Copy)]
pub struct FrameGen {
frame: Frame,
}
impl FrameGen {
pub fn render_frame(&self) {
RENDERER.lock().render_frame(self.frame)
}
fn new() -> Self {
let mut frame: [[char; BUFFER_WIDTH]; BUFFER_HEIGHT] = [[' '; BUFFER_WIDTH]; BUFFER_HEIGHT];
for i in 0..BUFFER_WIDTH {
frame[0][i] = "┌──────────────────────────────────────────────────────────────────────────────┐".chars().collect::<Vec<char>>()[i];
frame[BUFFER_HEIGHT -1][i] = "└──────────────────────────────────────────────────────────────────────────────┘".chars().collect::<Vec<char>>()[i];
}
for j in 1..BUFFER_HEIGHT -1 {
for i in 0..BUFFER_WIDTH {
frame[j][i] = "│ │".chars().collect::<Vec<char>>()[i];
}
}
Self { frame: Frame::from(frame) }
}
pub fn get_frame(&self) -> &[ [ char; BUFFER_WIDTH ]; BUFFER_HEIGHT] {
&self.frame
}
}
impl core::fmt::Display for FrameGen {
fn fmt(&self, _: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
println!(" ");
for row in &self.frame {
println!("{}", row.iter().collect::<String>());
};
Ok(())
}
}
#[macro_export]
macro_rules! println_log {
() => ($crate::print_log!("/n"));
@@ -173,43 +67,26 @@ macro_rules! print {
($($arg:tt)*) => ($crate::std::io::_print(format_args!($($arg)*)));
}
#[macro_export]
macro_rules! printerr {
($($arg:tt)*) => ($crate::std::io::_printerr(format_args!($($arg)*)));
}
#[doc(hidden)]
pub fn _print(args: core::fmt::Arguments) {
use core::fmt::Write;
use x86_64::instructions::interrupts;
render::write(args, (Color::White, Color::Black));
}
interrupts::without_interrupts(|| {
let mut writer = RENDERER.lock();
writer.write_fmt(args).unwrap();
//WRITER.lock().write_fmt(args).unwrap();
//writer.col_code = crate::kernel::render2::ColorCode::new(Color::White, Color::Black);
});
#[doc(hidden)]
pub fn _printerr(args: core::fmt::Arguments) {
render::write(args, (Color::Yellow, Color::Black));
}
#[doc(hidden)]
pub fn _log(args: core::fmt::Arguments) {
use core::fmt::Write;
use x86_64::instructions::interrupts;
interrupts::without_interrupts(|| {
let mut writer = RENDERER.lock();
writer.write_fmt(args).unwrap();
//writer.col_code = crate::kernel::render2::ColorCode::new(Color::Yellow, Color::Black);
//WRITER.lock().write_fmt(args).unwrap();
});
render::write(args, (Color::White, Color::Black));
}
pub fn write(args: core::fmt::Arguments, cols: (Color, Color)) {
crate::kernel::render::write(args, cols);
}
pub fn mkfs() {
use crate::kernel::fs;
fs::mkfs();
println!("{:?}", *(fs::FILESYSTEM.lock()));
pub fn write(args: core::fmt::Arguments, color: (Color, Color)) {
render::write(args, color);
}
+1
View File
@@ -3,6 +3,7 @@ pub mod random;
pub mod application;
pub mod tasks;
pub mod os;
pub mod frame;
// this is where the standard library for the operating system will be defined