1use anyhow::{Result, anyhow};
2use futures;
3use std::sync::Arc;
4use winit::event::{Event, WindowEvent};
5use winit::event_loop::{ControlFlow, EventLoop};
6use winit::window::{Window as WinitWindow, WindowBuilder};
7use wgpu::Instance;
8
9pub struct Window {
11 window: Arc<WinitWindow>,
12 surface: wgpu::Surface<'static>,
13 device: wgpu::Device,
14 queue: wgpu::Queue,
15 config: Option<wgpu::SurfaceConfiguration>,
16 surface_format: wgpu::TextureFormat,
17 surface_caps: wgpu::SurfaceCapabilities,
18}
19
20pub struct Application {
22 event_loop: Option<EventLoop<()>>,
23 windows: Vec<Window>,
24}
25
26impl Application {
28 pub fn new() -> Result<Self> {
30 Ok(Self {
31 event_loop: Some(EventLoop::new()?),
32 windows: Vec::new(),
33 })
34 }
35
36 pub fn create_window(&mut self, title: &str, width: u32, height: u32) -> Result<()> {
38 if let Some(event_loop) = self.event_loop.as_ref() {
39 let window = WindowBuilder::new()
40 .with_title(title)
41 .with_inner_size(winit::dpi::LogicalSize::new(width, height))
42 .build(event_loop)?;
43
44 let window_arc = Arc::new(window);
46
47 let instance = Instance::default();
49 let surface = unsafe {
53 let static_ref: &Arc<WinitWindow> = &window_arc;
55 let static_ref_ptr = static_ref as *const Arc<WinitWindow>;
56 &*static_ref_ptr
57 };
58 let surface = instance.create_surface(surface)?;
59 let adapter = futures::executor::block_on(instance.request_adapter(
60 &wgpu::RequestAdapterOptions {
61 power_preference: wgpu::PowerPreference::default(),
62 compatible_surface: Some(&surface),
63 force_fallback_adapter: false,
64 },
65 )).ok_or_else(|| anyhow::anyhow!("Failed to find an appropriate adapter"))?;
66
67 let (device, queue) = futures::executor::block_on(adapter.request_device(
68 &wgpu::DeviceDescriptor {
69 required_features: wgpu::Features::empty(),
70 required_limits: wgpu::Limits::default(),
71 label: Some("Device"),
72 },
73 None,
74 ))?;
75
76 let surface_caps = surface.get_capabilities(&adapter);
77 let surface_format = surface_caps.formats.iter()
78 .copied()
79 .find(|f| f.is_srgb())
80 .unwrap_or(surface_caps.formats[0]);
81
82 self.windows.push(Window {
85 window: window_arc,
86 surface,
87 device,
88 queue,
89 config: None,
90 surface_format,
91 surface_caps,
92 });
93 }
94
95 Ok(())
96 }
97
98 pub fn run(mut self) -> Result<()> {
100 let event_loop = self.event_loop.take().expect("Event loop already taken");
101
102 event_loop.run(move |event, target| {
103 target.set_control_flow(ControlFlow::Wait);
104
105 match event {
106 Event::WindowEvent { event, window_id } => {
107 match event {
108 WindowEvent::CloseRequested => {
109 target.set_control_flow(ControlFlow::WaitUntil(std::time::Instant::now()));
111 },
112 WindowEvent::Resized(new_size) => {
113 for window in &mut self.windows {
115 if window.window.id() == window_id {
116 if new_size.width > 0 && new_size.height > 0 {
118 let config = wgpu::SurfaceConfiguration {
120 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
121 format: window.surface_format,
122 width: new_size.width,
123 height: new_size.height,
124 present_mode: window.surface_caps.present_modes[0],
125 alpha_mode: window.surface_caps.alpha_modes[0],
126 view_formats: vec![],
127 desired_maximum_frame_latency: 2,
128 };
129
130 window.surface.configure(&window.device, &config);
132 window.config = Some(config);
133 window.window.request_redraw();
134 }
135 }
136 }
137 },
138 WindowEvent::RedrawRequested => {
139 for window in &mut self.windows {
141 if window.window.id() == window_id {
142 if let Err(err) = window.render() {
143 eprintln!("Error during rendering: {:?}", err);
144 }
145 }
146 }
147 },
148 _ => {},
149 }
150 },
151 Event::AboutToWait => {
153 for window in &self.windows {
155 window.window.request_redraw();
156 }
157 },
158 _ => {},
159 } }).map_err(|e| anyhow!("Event loop error: {:?}", e))
160 }
161}
162
163impl Window {
165 pub fn render(&mut self) -> Result<()> {
167 if self.config.is_none() {
169 let window_size = self.window.inner_size();
170
171 if window_size.width > 0 && window_size.height > 0 {
173 let config = wgpu::SurfaceConfiguration {
174 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
175 format: self.surface_format,
176 width: window_size.width,
177 height: window_size.height,
178 present_mode: self.surface_caps.present_modes[0],
179 alpha_mode: self.surface_caps.alpha_modes[0],
180 view_formats: vec![],
181 desired_maximum_frame_latency: 2,
182 };
183
184 self.surface.configure(&self.device, &config);
186 self.config = Some(config);
187 } else {
188 return Ok(());
190 }
191 }
192
193 let output = match self.surface.get_current_texture() {
195 Ok(output) => output,
196 Err(wgpu::SurfaceError::Outdated) | Err(wgpu::SurfaceError::Lost) => {
197 if let Some(config) = &self.config {
199 self.surface.configure(&self.device, config);
200 }
201 return Ok(());
202 },
203 Err(err) => return Err(err.into()),
204 };
205
206 let view = output.texture.create_view(&wgpu::TextureViewDescriptor::default());
207
208 let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
209 label: Some("Render Encoder"),
210 });
211
212 {
214 let render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
215 label: Some("Render Pass"),
216 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
217 view: &view,
218 resolve_target: None,
219 ops: wgpu::Operations {
220 load: wgpu::LoadOp::Clear(wgpu::Color {
221 r: 0.1,
222 g: 0.2,
223 b: 0.3,
224 a: 1.0,
225 }),
226 store: wgpu::StoreOp::Store,
227 },
228 })],
229 depth_stencil_attachment: None,
230 timestamp_writes: None,
231 occlusion_query_set: None,
232 });
233 drop(render_pass);
235 }
236
237 self.queue.submit(std::iter::once(encoder.finish()));
238 output.present();
239
240 Ok(())
241 }
242}