1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
use {
    super::{
        display::{Display, DisplayError, ResolverPool},
        driver::{
            device::{Device, DeviceInfoBuilder},
            swapchain::{Swapchain, SwapchainInfoBuilder},
            DriverError, Surface,
        },
        frame::FrameContext,
        graph::RenderGraph,
        pool::hash::HashPool,
    },
    ash::vk,
    log::{debug, error, info, trace, warn},
    std::{
        fmt::{Debug, Formatter},
        sync::Arc,
        time::{Duration, Instant},
    },
    winit::{
        event::{Event, WindowEvent},
        monitor::MonitorHandle,
        window::{Fullscreen, Window, WindowBuilder},
    },
};

/// Function type for selection of swapchain surface image format.
pub type SelectSurfaceFormatFn = dyn FnOnce(&[vk::SurfaceFormatKHR]) -> vk::SurfaceFormatKHR;

/// Describes a screen mode for display.
pub enum FullscreenMode {
    /// A display mode which retains other operating system windows behind the current window.
    Borderless,

    /// Seems to be the only way for stutter-free rendering on Nvidia + Win10.
    Exclusive,
}

/// Pumps an operating system event loop in order to handle input and other events
/// while drawing to the screen, continuously.
#[derive(Debug)]
pub struct EventLoop {
    /// Provides access to the current graphics device.
    pub device: Arc<Device>,

    display: Display,
    event_loop: winit::event_loop::EventLoop<()>,
    swapchain: Swapchain,

    /// Provides access to the current operating system window.
    pub window: Window,
}

impl EventLoop {
    /// Specifies an event loop.
    #[allow(clippy::new_ret_no_self)]
    pub fn new() -> EventLoopBuilder {
        Default::default()
    }

    /// Current window height, in pixels.
    pub fn height(&self) -> u32 {
        self.window.inner_size().height
    }

    /// Begins running a windowed event loop, providing `frame_fn` with a context of the current
    /// frame.
    pub fn run<FrameFn>(mut self, mut frame_fn: FrameFn) -> Result<(), DisplayError>
    where
        FrameFn: FnMut(FrameContext),
    {
        let mut events = Vec::new();
        let mut will_exit = false;
        let mut last_swapchain_err = None;
        let mut run_result = Ok(());

        // Use the same delta-time smoothing as Kajiya; but start it off with a reasonable
        // guess so the following updates are even smoother
        const STANDARD_REFRESH_RATE_MHZ: u32 = 60_000;
        let refresh_rate = (self
            .window
            .fullscreen()
            .map(|mode| match mode {
                Fullscreen::Exclusive(mode) => mode.refresh_rate_millihertz(),
                Fullscreen::Borderless(Some(monitor)) => monitor
                    .video_modes()
                    .next()
                    .map(|mode| mode.refresh_rate_millihertz())
                    .unwrap_or(STANDARD_REFRESH_RATE_MHZ),
                _ => STANDARD_REFRESH_RATE_MHZ,
            })
            .unwrap_or(STANDARD_REFRESH_RATE_MHZ)
            .clamp(STANDARD_REFRESH_RATE_MHZ, STANDARD_REFRESH_RATE_MHZ << 2)
            / 1_000) as f32;
        let mut last_frame = Instant::now();
        let mut dt_filtered = 1.0 / refresh_rate;
        last_frame -= Duration::from_secs_f32(dt_filtered);

        debug!("first frame dt: {}", dt_filtered);

        self.window.set_visible(true);

        self.event_loop
            .run(|event, window| {
                match event {
                    Event::WindowEvent {
                        event: WindowEvent::CloseRequested,
                        ..
                    } => {
                        window.exit();
                    }
                    Event::WindowEvent {
                        event: WindowEvent::Focused(false),
                        ..
                    } => self.window.set_cursor_visible(true),
                    Event::WindowEvent {
                        event: WindowEvent::Resized(size),
                        ..
                    } => {
                        let mut swapchain_info = self.swapchain.info();
                        swapchain_info.width = size.width;
                        swapchain_info.height = size.height;
                        self.swapchain.set_info(swapchain_info);
                    }
                    Event::AboutToWait => {
                        self.window.request_redraw();
                        return;
                    }
                    _ => {}
                }

                if !matches!(
                    event,
                    Event::WindowEvent {
                        event: WindowEvent::RedrawRequested,
                        ..
                    }
                ) {
                    events.push(event);
                    return;
                }

                trace!("🟥🟩🟦 Event::RedrawRequested");
                profiling::scope!("Frame");

                if !events.is_empty() {
                    trace!("received {} events", events.len(),);
                }

                let now = Instant::now();

                // Filter the frame time before passing it to the application and renderer.
                // Fluctuations in frame rendering times cause stutter in animations,
                // and time-dependent effects (such as motion blur).
                //
                // Should applications need unfiltered delta time, they can calculate
                // it themselves, but it's good to pass the filtered time so users
                // don't need to worry about it.
                {
                    profiling::scope!("Calculate dt");

                    let dt_duration = now - last_frame;
                    last_frame = now;

                    let dt_raw = dt_duration.as_secs_f32();
                    dt_filtered = dt_filtered + (dt_raw - dt_filtered) / 10.0;
                };

                // Note: Errors when acquiring swapchain images are not considered fatal
                match self.swapchain.acquire_next_image() {
                    Err(err) => {
                        if last_swapchain_err == Some(err) {
                            // Generally ignore repeated errors as the window may take some time to get
                            // back to a workable state
                            debug!("Unable to acquire swapchain image: {err:?}");
                        } else {
                            // The error has changed - this may happen during some window events
                            warn!("Unable to acquire swapchain image: {err:?}");
                            last_swapchain_err = Some(err);
                        }
                    }
                    Ok(swapchain_image) => {
                        last_swapchain_err = None;

                        let height = swapchain_image.info.height;
                        let width = swapchain_image.info.width;
                        let mut render_graph = RenderGraph::new();
                        let swapchain_image = render_graph.bind_node(swapchain_image);

                        {
                            profiling::scope!("Frame callback");

                            frame_fn(FrameContext {
                                device: &self.device,
                                dt: dt_filtered,
                                height,
                                render_graph: &mut render_graph,
                                events: &events,
                                swapchain_image,
                                width,
                                window: &self.window,
                                will_exit: &mut will_exit,
                            });

                            if will_exit {
                                window.exit();
                                return;
                            }
                        }

                        let elapsed = Instant::now() - now;

                        trace!(
                            "✅✅✅ render graph construction: {} μs ({}% load)",
                            elapsed.as_micros(),
                            ((elapsed.as_secs_f32() / refresh_rate) * 100.0) as usize,
                        );

                        match self.display.resolve_image(render_graph, swapchain_image) {
                            Err(err) => {
                                // This is considered a fatal error and will be thrown back to the
                                // caller
                                error!("Unable to resolve swapchain image: {err}");
                                run_result = Err(err);
                                window.exit();
                            }
                            Ok(swapchain_image) => {
                                self.window.pre_present_notify();
                                self.swapchain.present_image(swapchain_image, 0, 0);

                                profiling::finish_frame!();
                            }
                        }
                    }
                }

                events.clear();
            })
            .map_err(|err| {
                error!("Unable to run event loop: {err}");

                DisplayError::Driver(DriverError::Unsupported)
            })?;

        run_result?;

        self.window.set_visible(false);

        Ok(())
    }

    /// Current window width, in pixels.
    pub fn width(&self) -> u32 {
        self.window.inner_size().width
    }

    /// Current window.
    pub fn window(&self) -> &Window {
        &self.window
    }
}

impl AsRef<winit::event_loop::EventLoop<()>> for EventLoop {
    fn as_ref(&self) -> &winit::event_loop::EventLoop<()> {
        &self.event_loop
    }
}

/// Builder for `EventLoop`.
pub struct EventLoopBuilder {
    cmd_buf_count: usize,
    device_info: DeviceInfoBuilder,
    event_loop: winit::event_loop::EventLoop<()>,
    resolver_pool: Option<Box<dyn ResolverPool>>,
    surface_format_fn: Option<Box<SelectSurfaceFormatFn>>,
    swapchain_info: SwapchainInfoBuilder,
    window: WindowBuilder,
}

impl Debug for EventLoopBuilder {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str("EventLoopBuilder")
    }
}

impl Default for EventLoopBuilder {
    fn default() -> Self {
        Self {
            cmd_buf_count: 5,
            device_info: DeviceInfoBuilder::default(),
            event_loop: winit::event_loop::EventLoop::new().expect("Unable to build event loop"),
            resolver_pool: None,
            surface_format_fn: None,
            swapchain_info: SwapchainInfoBuilder::default(),
            window: Default::default(),
        }
    }
}

impl EventLoopBuilder {
    /// Returns the list of all the monitors available on the system.
    pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> {
        self.event_loop.available_monitors()
    }

    /// Specifies the number of in-flight command buffers, which should be greater
    /// than or equal to the desired swapchain image count.
    ///
    /// More command buffers mean less time waiting for previously submitted frames to complete, but
    /// more memory in use.
    ///
    /// Generally a value of one or two greater than desired image count produces the smoothest
    /// animation.
    pub fn command_buffer_count(mut self, cmd_buf_count: usize) -> Self {
        self.cmd_buf_count = cmd_buf_count;
        self
    }

    /// A function to select the desired swapchain surface image format.
    ///
    /// By default linear color space will be selected unless it is not available.
    pub fn desired_surface_format<F>(mut self, surface_format_fn: F) -> Self
    where
        F: 'static + FnOnce(&[vk::SurfaceFormatKHR]) -> vk::SurfaceFormatKHR,
    {
        let surface_format_fn = Box::new(surface_format_fn);
        self.surface_format_fn = Some(surface_format_fn);
        self
    }

    /// The desired, but not guaranteed, number of images that will be in the created swapchain.
    ///
    /// More images introduces more display lag, but smoother animation.
    pub fn desired_swapchain_image_count(mut self, desired_swapchain_image_count: u32) -> Self {
        self.swapchain_info = self
            .swapchain_info
            .desired_image_count(desired_swapchain_image_count);
        self
    }

    /// Set to `true` to enable vsync in exclusive fullscreen video modes.
    pub fn sync_display(mut self, sync_display: bool) -> Self {
        self.swapchain_info = self.swapchain_info.sync_display(sync_display);
        self
    }

    /// Sets up fullscreen mode. In addition, decorations are set to `false` and maximized is set to
    /// `true`.
    ///
    /// # Note
    ///
    /// There are additional options offered by `winit` which can be accessed using the `window`
    /// function.
    pub fn fullscreen_mode(mut self, mode: FullscreenMode) -> Self {
        let inner_size;
        self.window = self
            .window
            .with_decorations(false)
            .with_maximized(true)
            .with_fullscreen(Some(match mode {
                FullscreenMode::Borderless => {
                    info!("Using borderless fullscreen");

                    inner_size = None;

                    Fullscreen::Borderless(None)
                }
                FullscreenMode::Exclusive => {
                    if let Some(video_mode) =
                        self.event_loop.primary_monitor().and_then(|monitor| {
                            let monitor_size = monitor.size();
                            monitor.video_modes().find(|mode| {
                                let mode_size = mode.size();

                                // Don't pick a mode which has greater resolution than the monitor is
                                // currently using: it causes a panic on x11 in winit
                                mode_size.height <= monitor_size.height
                                    && mode_size.width <= monitor_size.width
                            })
                        })
                    {
                        info!(
                            "Using {}x{} {}bpp @ {}hz exclusive fullscreen",
                            video_mode.size().width,
                            video_mode.size().height,
                            video_mode.bit_depth(),
                            video_mode.refresh_rate_millihertz() / 1_000
                        );

                        inner_size = Some(video_mode.size());

                        Fullscreen::Exclusive(video_mode)
                    } else {
                        warn!("Using borderless fullscreen");

                        inner_size = None;

                        Fullscreen::Borderless(None)
                    }
                }
            }));

        if let Some(inner_size) = inner_size.or_else(|| {
            self.event_loop
                .primary_monitor()
                .map(|monitor| monitor.size())
        }) {
            self.window = self.window.with_inner_size(inner_size);
        }

        self
    }

    /// Enables Vulkan graphics debugging layers.
    ///
    /// _NOTE:_ Any valdation warnings or errors will cause the current thread to park itself after
    /// describing the error using the `log` crate. This makes it easy to attach a debugger and see
    /// what is causing the issue directly.
    ///
    /// ## Platform-specific
    ///
    /// **macOS:** Has no effect.
    pub fn debug(mut self, debug: bool) -> Self {
        self.device_info = self.device_info.debug(debug);
        self
    }

    /// Returns the primary monitor of the system.
    ///
    /// Returns `None` if it can't identify any monitor as a primary one.
    ///
    /// ## Platform-specific
    ///
    /// **Wayland:** Always returns `None`.
    pub fn primary_monitor(&self) -> Option<MonitorHandle> {
        self.event_loop.primary_monitor()
    }

    /// Allows for specification of a custom pool implementation.
    ///
    /// This pool will hold leases for Vulkan objects needed by [`Display`].
    pub fn resolver_pool(mut self, pool: Box<dyn ResolverPool>) -> Self {
        self.resolver_pool = Some(pool);
        self
    }

    /// Allows deeper customization of the window, if needed.
    pub fn window<WindowFn>(mut self, window_fn: WindowFn) -> Self
    where
        WindowFn: FnOnce(WindowBuilder) -> WindowBuilder,
    {
        self.window = window_fn(self.window);
        self
    }

    /// Sets up "windowed" mode, which is the opposite of fullscreen.
    ///
    /// # Note
    ///
    /// There are additional options offered by `winit` which can be accessed using the `window`
    /// function.
    pub fn window_mode(mut self) -> Self {
        self.window = self.window.with_fullscreen(None);
        self
    }
}

impl EventLoopBuilder {
    /// Builds a new `EventLoop`.
    pub fn build(mut self) -> Result<EventLoop, DriverError> {
        // Create an operating system window via Winit
        let window = self.window;

        #[cfg(not(target_os = "macos"))]
        let window = window.with_visible(false);

        let window = window.build(&self.event_loop).map_err(|err| {
            warn!("{err}");

            DriverError::Unsupported
        })?;
        let (width, height) = {
            let inner_size = window.inner_size();
            (inner_size.width, inner_size.height)
        };
        self.swapchain_info = self.swapchain_info.width(width).height(height);

        // Load the GPU driver (thin Vulkan device and swapchain smart pointers)
        let device_info = self.device_info.build();
        let device = Arc::new(Device::create_display_window(device_info, &window)?);

        // TODO: Select a better index
        let queue_family_index = 0;

        // Create a display that is cached using the given pool implementation
        let pool = self
            .resolver_pool
            .unwrap_or_else(|| Box::new(HashPool::new(&device)));
        let display = Display::new(&device, pool, self.cmd_buf_count, queue_family_index)?;

        let surface = Surface::create(&device, &window)?;
        let surface_formats = Surface::formats(&surface)?;

        if surface_formats.is_empty() {
            warn!("invalid surface formats");

            return Err(DriverError::Unsupported);
        }

        for surface in &surface_formats {
            debug!(
                "surface: {:#?} ({:#?})",
                surface.format, surface.color_space
            );
        }

        let surface_format_fn = self
            .surface_format_fn
            .unwrap_or_else(|| Box::new(Surface::linear_or_default));
        let surface_format = surface_format_fn(&surface_formats);
        let swapchain = Swapchain::new(
            &device,
            surface,
            self.swapchain_info.surface(surface_format),
        )?;

        info!(
            "Window dimensions: {}x{} ({}x scale)",
            width,
            height,
            window.scale_factor() as f32,
        );

        Ok(EventLoop {
            device,
            display,
            event_loop: self.event_loop,
            swapchain,
            window,
        })
    }
}