mod ppu; use std::{ rc::Rc, sync::{ Arc, atomic::AtomicU32, mpsc::{Receiver, Sender}, }, }; use softbuffer::Context; use winit::event_loop::EventLoop; use crate::Screen; pub(crate) use ppu::Ppu; pub const SCREEN_WIDTH: usize = 240; pub const SCREEN_HEIGHT: usize = 160; pub const SCREEN_AREA: usize = SCREEN_WIDTH * SCREEN_HEIGHT; pub enum GfxMsg {} pub enum CtlMsg {} pub struct Handle { gfx: Sender, ctl: Receiver, ppu: Arc, vblank: Arc, } impl Handle { pub fn ppu(&self) -> Arc { Arc::clone(&self.ppu) } pub fn wait_vblank(&self) { atomic_wait::wait(&self.vblank, 0); } } pub struct SystemHandle { gfx: Receiver, ctl: Sender, vblank: Arc, } impl SystemHandle { pub fn vblank(&self) { atomic_wait::wake_all(&*self.vblank); } } pub struct System { eventloop: EventLoop<()>, screen: Option, ppu: Arc, handle: Arc, } impl System { pub fn new() -> (Self, Handle) { let el = EventLoop::new().unwrap(); el.set_control_flow(winit::event_loop::ControlFlow::Poll); let ppu = Arc::new(Ppu::new()); let (handle, user_handle) = Self::handles(Arc::clone(&ppu)); ( Self { eventloop: el, screen: None, ppu: user_handle.ppu(), handle: Arc::new(handle), }, user_handle, ) } pub fn initialize_screen(&mut self) { let ctx = Context::new(self.eventloop.owned_display_handle()).unwrap(); self.screen = Some(Screen::new( ctx, Arc::clone(&self.ppu), Arc::clone(&self.handle), )); } fn handles(ppu: Arc) -> (SystemHandle, Handle) { let (gfx_tx, gfx_rx) = std::sync::mpsc::channel(); let (ctl_tx, ctl_rx) = std::sync::mpsc::channel(); let vblank = Arc::new(AtomicU32::new(0)); ( SystemHandle { gfx: gfx_rx, ctl: ctl_tx, vblank: Arc::clone(&vblank), }, Handle { gfx: gfx_tx, ctl: ctl_rx, ppu, vblank, }, ) } pub fn run(self) { let System { eventloop, screen, ppu: _, handle, } = self; match screen { None => eprintln!("Cannot run! the screen is not initialized!"), Some(mut screen) => eventloop.run_app(&mut screen).unwrap(), } } }