diff --git a/Cargo.toml b/Cargo.toml index c9c2a7b15a..a781bc0d70 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -64,7 +64,7 @@ image = { version = "0.24.0", default-features = false, features = ["png"] } simple_logger = { version = "2.1.0", default_features = false } [target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dev-dependencies] -softbuffer = "0.2.0" +softbuffer = "0.3.0" [target.'cfg(target_os = "android")'.dependencies] # Coordinate the next winit release with android-ndk-rs: https://github.com/rust-windowing/winit/issues/1995 diff --git a/examples/util/fill.rs b/examples/util/fill.rs index 79a127013c..e08f92247a 100644 --- a/examples/util/fill.rs +++ b/examples/util/fill.rs @@ -11,31 +11,67 @@ use winit::window::Window; #[cfg(not(any(target_os = "android", target_os = "ios")))] pub(super) fn fill_window(window: &Window) { - use softbuffer::GraphicsContext; + use softbuffer::{Context, Surface}; use std::cell::RefCell; use std::collections::HashMap; + use std::num::NonZeroU32; use winit::window::WindowId; + /// The graphics context used to draw to a window. + struct GraphicsContext { + /// The global softbuffer context. + context: Context, + + /// The hash map of window IDs to surfaces. + surfaces: HashMap, + } + + impl GraphicsContext { + fn new(w: &Window) -> Self { + Self { + context: unsafe { Context::new(w) }.expect("Failed to create a softbuffer context"), + surfaces: HashMap::new(), + } + } + + fn surface(&mut self, w: &Window) -> &mut Surface { + self.surfaces.entry(w.id()).or_insert_with(|| { + unsafe { Surface::new(&self.context, w) } + .expect("Failed to create a softbuffer surface") + }) + } + } + thread_local! { /// A static, thread-local map of graphics contexts to open windows. - static GC: RefCell> = RefCell::new(HashMap::new()); + static GC: RefCell> = RefCell::new(None); } GC.with(|gc| { // Either get the last context used or create a new one. let mut gc = gc.borrow_mut(); - let context = gc.entry(window.id()).or_insert_with(|| unsafe { - GraphicsContext::new(window, window) - .expect("Failed to create a softbuffer graphics context") - }); + let surface = gc + .get_or_insert_with(|| GraphicsContext::new(window)) + .surface(window); // Fill a buffer with a solid color. - const LIGHT_GRAY: u32 = 0xFFD3D3D3; + const DARK_GRAY: u32 = 0xFF181818; let size = window.inner_size(); - let buffer = vec![LIGHT_GRAY; size.width as usize * size.height as usize]; - // Draw the buffer to the window. - context.set_buffer(&buffer, size.width as u16, size.height as u16); + surface + .resize( + NonZeroU32::new(size.width).expect("Width must be greater than zero"), + NonZeroU32::new(size.height).expect("Height must be greater than zero"), + ) + .expect("Failed to resize the softbuffer surface"); + + let mut buffer = surface + .buffer_mut() + .expect("Failed to get the softbuffer buffer"); + buffer.fill(DARK_GRAY); + buffer + .present() + .expect("Failed to present the softbuffer buffer"); }) }