pub(crate) mod exchange_layer;
use crate::viewer::exchange_layer::{ExchangeLayer, UpdateHook};
use chrono::Local;
use minifb::{Window, WindowOptions};
#[cfg(feature = "view_shot")]
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::thread;
use std::thread::JoinHandle;
pub struct ArrayViewer<const W: usize, const H: usize> {
ptr: usize,
exchange_layer: Arc<ExchangeLayer>,
}
impl<const W: usize, const H: usize> ArrayViewer<W, H> {
pub fn new(ptr: usize) -> Self {
Self {
ptr,
exchange_layer: Arc::from(ExchangeLayer::new()),
}
}
pub fn run(&self, window_options: Option<WindowOptions>) -> JoinHandle<()> {
let exchange_layer = self.exchange_layer.clone();
let ptr = self.ptr;
thread::spawn(move || {
let running = &exchange_layer.is_running;
let target_fps = &exchange_layer.target_fps;
let fps = &exchange_layer.fps;
let ptr = ptr as *const u32;
let pixels = unsafe { std::slice::from_raw_parts(ptr, W * H) };
let mut window = Window::new("starting...", W, H, window_options.unwrap_or_default())
.expect("无法创建窗口");
window.set_target_fps(target_fps.load(Ordering::Relaxed));
let mut time = Local::now();
let mut get_fps = move || -> usize {
let now = Local::now();
let interval = now - time;
time = now;
let nanos = interval.num_nanoseconds().unwrap_or(i64::MAX);
(1_000_000_000 / nanos) as usize
};
running.store(true, Ordering::Relaxed);
let mut hook_cache: Option<UpdateHook> = None;
let mut hook_epoch = 0usize;
while window.is_open() && running.load(Ordering::Relaxed) {
let epoch = exchange_layer.hook_epoch.load(Ordering::Relaxed);
if epoch != hook_epoch {
match exchange_layer.update_hook.try_lock() {
Ok(mut guard) => {
hook_cache = guard.take();
hook_epoch = exchange_layer.hook_epoch.load(Ordering::Relaxed);
}
Err(_) => { }
}
}
if let Some(ref hook) = hook_cache {
hook.call(&mut window);
}
exchange_layer.apply_to_window(&mut window);
window
.update_with_buffer(pixels, W, H)
.expect("窗口更新失败");
let current_fps = get_fps();
fps.store(current_fps, Ordering::Relaxed);
exchange_layer.update_from_window(&mut window);
}
running.store(false, Ordering::Relaxed);
})
}
pub fn fps(&self) -> usize {
self.exchange_layer.fps.load(Ordering::Relaxed)
}
pub fn get_exchange_layer(&self) -> Arc<ExchangeLayer> {
self.exchange_layer.clone()
}
#[cfg(feature = "view_shot")]
pub fn view_shot<P: AsRef<Path>>(&self, path: P) -> Result<(), Box<dyn std::error::Error>> {
let pixels = unsafe { std::slice::from_raw_parts(self.ptr as *const u32, W * H) };
let mut img = image::RgbaImage::new(W as u32, H as u32);
for (i, &pixel) in pixels.iter().enumerate() {
let x = (i % W) as u32;
let y = (i / W) as u32;
let a = ((pixel >> 24) & 0xFF) as u8;
let r = ((pixel >> 16) & 0xFF) as u8;
let g = ((pixel >> 8) & 0xFF) as u8;
let b = (pixel & 0xFF) as u8;
img.put_pixel(x, y, image::Rgba([r, g, b, a]));
}
img.save(path)?;
Ok(())
}
}