use minifb::{Window, WindowOptions};
use crate::error::{Error, Result};
use crate::render::Canvas;
pub struct RenderWindow {
window: Window,
width: usize,
height: usize,
target_fps: usize,
}
impl std::fmt::Debug for RenderWindow {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RenderWindow")
.field("width", &self.width)
.field("height", &self.height)
.field("target_fps", &self.target_fps)
.finish_non_exhaustive()
}
}
impl RenderWindow {
pub fn new(title: &str, width: usize, height: usize, target_fps: usize) -> Result<Self> {
let mut window = Window::new(
title,
width,
height,
WindowOptions {
resize: false,
scale_mode: minifb::ScaleMode::AspectRatioStretch,
..WindowOptions::default()
},
)
.map_err(|e| Error::MissingDependency(format!("failed to create window: {e}")))?;
if target_fps > 0 {
window.set_target_fps(target_fps);
}
Ok(Self {
window,
width,
height,
target_fps,
})
}
pub fn show(&mut self, canvas: &Canvas) -> Result<()> {
let buffer = canvas.pixels_argb32();
self.window
.update_with_buffer(&buffer, self.width, self.height)
.map_err(|e| Error::MissingDependency(format!("window update failed: {e}")))?;
Ok(())
}
#[must_use]
pub fn is_open(&self) -> bool {
self.window.is_open()
}
#[must_use]
pub const fn target_fps(&self) -> usize {
self.target_fps
}
}