softbuffer/examples/winit.rs

67 lines
2.1 KiB
Rust
Raw Normal View History

use std::num::NonZeroU32;
2022-01-15 08:17:17 -06:00
use winit::event::{Event, WindowEvent};
use winit::event_loop::{ControlFlow, EventLoop};
use winit::window::WindowBuilder;
fn main() {
let event_loop = EventLoop::new();
let window = WindowBuilder::new().build(&event_loop).unwrap();
#[cfg(target_arch = "wasm32")]
{
use winit::platform::web::WindowExtWebSys;
web_sys::window()
.unwrap()
.document()
.unwrap()
.body()
.unwrap()
.append_child(&window.canvas())
.unwrap();
}
let context = unsafe { softbuffer::Context::new(&window) }.unwrap();
let mut surface = unsafe { softbuffer::Surface::new(&context, &window) }.unwrap();
2022-01-15 08:17:17 -06:00
event_loop.run(move |event, _, control_flow| {
*control_flow = ControlFlow::Wait;
match event {
Event::RedrawRequested(window_id) if window_id == window.id() => {
2022-01-15 08:17:17 -06:00
let (width, height) = {
let size = window.inner_size();
2022-01-15 08:17:17 -06:00
(size.width, size.height)
};
surface
.resize(
NonZeroU32::new(width).unwrap(),
NonZeroU32::new(height).unwrap(),
)
.unwrap();
let mut buffer = surface.buffer_mut().unwrap();
for y in 0..height {
for x in 0..width {
let red = x % 255;
let green = y % 255;
let blue = (x * y) % 255;
let index = y as usize * width as usize + x as usize;
buffer[index] = blue | (green << 8) | (red << 16);
}
}
buffer.present().unwrap();
2022-01-15 08:17:17 -06:00
}
Event::WindowEvent {
event: WindowEvent::CloseRequested,
2022-01-16 08:59:29 -06:00
window_id,
} if window_id == window.id() => {
2022-01-15 08:17:17 -06:00
*control_flow = ControlFlow::Exit;
2022-01-16 08:59:29 -06:00
}
2022-01-15 08:17:17 -06:00
_ => {}
}
});
2022-01-16 08:59:29 -06:00
}