use std::{ num::NonZeroU32, sync::{Arc, mpsc::Sender}, thread::JoinHandle, time::{Duration, Instant}, }; use softbuffer::{Context, Surface}; use winit::{ application::ApplicationHandler, dpi::PhysicalSize, event::WindowEvent, event_loop::OwnedDisplayHandle, window::Window, }; use crate::{ Ppu, SystemHandle, system::{SCREEN_AREA, SCREEN_HEIGHT, SCREEN_WIDTH}, }; #[derive(Copy, Clone, Debug, PartialEq)] enum WindowFrameMessage { Wait(Duration), Stop, } struct WindowFrame { window: Arc, surface: Surface>, tx: Sender, driver: JoinHandle<()>, } pub struct Screen { frame: Option, context: Context, framebuffer: [u32; SCREEN_AREA], ppu: Arc, handle: Arc, scale: u8, width: u32, height: u32, } impl Screen { pub fn new( context: Context, ppu: Arc, handle: Arc, ) -> Self { Self { frame: None, context, framebuffer: [0u32; SCREEN_AREA], ppu, handle, scale: 2, width: 0, height: 0, } } fn resize(&mut self, width: u32, height: u32) { if let Some(frame) = self.frame.as_mut() { frame .surface .resize( NonZeroU32::new(width).unwrap(), NonZeroU32::new(height).unwrap(), ) .unwrap(); } self.width = width; self.height = height; } } impl ApplicationHandler for Screen { fn resumed(&mut self, el: &winit::event_loop::ActiveEventLoop) { let winattr = Window::default_attributes() .with_title("beautiful pixels") .with_inner_size(PhysicalSize::new( self.scale as u32 * SCREEN_WIDTH as u32, self.scale as u32 * SCREEN_HEIGHT as u32, )) .with_resizable(false); let window = Arc::new(el.create_window(winattr).unwrap()); let surface = Surface::new(&self.context, Arc::clone(&window)).unwrap(); let window_clone = Arc::clone(&window); let (tx, rx) = std::sync::mpsc::channel(); let driver = std::thread::spawn(move || { loop { println!("waiting in driver"); match rx.recv().unwrap() { WindowFrameMessage::Stop => return, WindowFrameMessage::Wait(d) => { println!("Got request to wait for {d:?}"); std::thread::sleep(d); window_clone.request_redraw(); } } } }); self.frame = Some(WindowFrame { window, surface, tx, driver, }); } fn window_event( &mut self, el: &winit::event_loop::ActiveEventLoop, wid: winit::window::WindowId, ev: winit::event::WindowEvent, ) { const FPS: usize = 60; let fps_ms = FPS as f32 / 1000.0; match ev { WindowEvent::Resized(size) => { self.resize(size.width, size.height); } WindowEvent::RedrawRequested => { let start = Instant::now(); let frame = if let Some(sur) = self.frame.as_mut() { sur } else { eprintln!("resized window with no surface?"); return; }; println!("Drawing PPU={:?}", Arc::as_ptr(&self.ppu)); self.ppu.draw(&mut self.framebuffer); // Let the game thread know that we're in VBlank self.handle.vblank(); print!("DRAW "); for back in self.ppu.background().iter().take(8) { print!("{back:02X} "); } println!(""); self.ppu.print_background(); let mut buffer = frame.surface.buffer_mut().unwrap(); let width = buffer.width().get() as usize; for (buffer_idx, px) in buffer.iter_mut().enumerate() { let buffer_x = buffer_idx / width; let buffer_y = buffer_idx % width; let framebuffer_x = (buffer_x / self.scale as usize).max(SCREEN_WIDTH - 1); let framebuffer_y = (buffer_y / self.scale as usize).max(SCREEN_HEIGHT - 1); let framebuffer_idx = framebuffer_y * SCREEN_WIDTH + framebuffer_x; *px = self.framebuffer[framebuffer_idx.min(SCREEN_AREA - 1)]; } buffer.present().unwrap(); let took = start.elapsed(); let wait = Duration::from_secs_f32(fps_ms) - took; //frame.tx.send(WindowFrameMessage::Wait(wait)).unwrap(); std::thread::sleep(wait); frame.window.request_redraw(); println!("Sent!"); } WindowEvent::CloseRequested => { std::process::exit(0); } ev => (), } } } #[inline(always)] pub fn greay32(k: u8) -> u32 { k as u32 | (k as u32) << 8 | (k as u32) << 16 } #[inline(always)] pub fn color32(r: u8, g: u8, b: u8) -> u32 { b as u32 | (g as u32) << 8 | (r as u32) << 16 }