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
use {
    crate::graphics::vulkan_api::RenderDevice,
    anyhow::{bail, Context, Result},
    ash::{vk, vk::Handle},
    ccthw_ash_instance::{PhysicalDeviceFeatures, VulkanInstance},
    glfw::{ClientApiHint, WindowEvent, WindowHint, WindowMode},
    std::sync::{mpsc::Receiver, Arc},
};

/// All resources required for running a single-windowed GLFW application which
/// renders graphics using Vulkan.
///
/// GlfwWindow derefs as a raw GLFW window handle so application state can
/// configure the window however is convenient.
pub struct GlfwWindow {
    window_pos: (i32, i32),
    window_size: (i32, i32),
    window_handle: glfw::Window,

    /// The receiver for the Window's events.
    pub(super) event_receiver: Option<Receiver<(f64, WindowEvent)>>,

    /// The GLFW library instance.
    pub(super) glfw: glfw::Glfw,
}

impl GlfwWindow {
    /// Create a new GLFW window.
    ///
    /// The window starts in "windowed" mode and can be toggled into fullscreen
    /// or resized by the application.
    ///
    /// # Params
    ///
    /// * `window_title` - The title shown on the window's top bar.
    pub fn new(window_title: impl AsRef<str>) -> Result<Self> {
        let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS)?;

        if !glfw.vulkan_supported() {
            bail!("Vulkan isn't supported by glfw on this platform!");
        }

        glfw.window_hint(WindowHint::ClientApi(ClientApiHint::NoApi));
        glfw.window_hint(WindowHint::ScaleToMonitor(true));

        let (window_handle, event_receiver) = glfw
            .create_window(
                1366,
                768,
                window_title.as_ref(),
                WindowMode::Windowed,
            )
            .context("Creating the GLFW Window failed!")?;

        Ok(Self {
            window_pos: window_handle.get_pos(),
            window_size: window_handle.get_size(),
            event_receiver: Some(event_receiver),
            window_handle,
            glfw,
        })
    }

    /// Toggle application fullscreen.
    ///
    /// If the window is currently windowed then swap to fullscreen using
    /// whatever the primary monitor advertises as the primary video mode.
    ///
    /// If the window is currently fullscreen, then swap to windowed and
    /// restore the window's previous size and location.
    pub fn toggle_fullscreen(&mut self) -> Result<()> {
        let is_fullscreen =
            self.window_handle.with_window_mode(|mode| match mode {
                WindowMode::Windowed => false,
                WindowMode::FullScreen(_) => true,
            });

        if is_fullscreen {
            // Switch to windowed mode.
            let (x, y) = self.window_pos;
            let (w, h) = self.window_size;
            self.window_handle.set_monitor(
                WindowMode::Windowed,
                x,
                y,
                w as u32,
                h as u32,
                None,
            );
        } else {
            // Switch to fullscreen mode.
            // Record the size and position of the non-fullscreen window
            // before switching modes.
            self.window_size = self.window_handle.get_size();
            self.window_pos = self.window_handle.get_pos();
            let window = &mut self.window_handle;
            self.glfw.with_primary_monitor_mut(
                |_, monitor_opt| -> Result<()> {
                    let monitor = monitor_opt
                        .context("Unable to determine the primary monitor!")?;
                    let video_mode = monitor
                        .get_video_mode()
                        .context("Unable to get a primary video mode for the primary monitor!")?;
                    window.set_monitor(
                        WindowMode::FullScreen(monitor),
                        0,
                        0,
                        video_mode.width,
                        video_mode.height,
                        Some(video_mode.refresh_rate),
                    );
                    Ok(())
                },
            )?;
        }
        Ok(())
    }

    /// Create a render device with no additional instanc extensions or layers.
    ///
    /// # Params
    ///
    /// * `features` - The physical device features required by the application.
    ///
    /// # Safety
    ///
    /// The application is responsible for synchronizing access to all Vulkan
    /// resources and destroying the render device at exit.
    pub unsafe fn create_default_render_device(
        &self,
        physical_device_features: PhysicalDeviceFeatures,
    ) -> Result<Arc<RenderDevice>> {
        self.create_render_device(&[], &[], physical_device_features)
    }

    /// Create a render device for the application.
    ///
    /// # Params
    ///
    /// * `instance_extensions` - Any extensions to enable when creating the
    ///   instance. Extensions for the swapchain on the current platform are
    ///   added automatically and do not need to be provided.
    /// * `instance_layers` - Any additional layers to provide. The khronos
    ///   validation layer is added automatically when debug assertions are
    ///   enabled.
    /// * `features` - The physical device features required by the application.
    ///
    /// # Safety
    ///
    /// The application is responsible for synchronizing access to all Vulkan
    /// resources and destroying the render device at exit.
    pub unsafe fn create_render_device(
        &self,
        instance_extensions: &[String],
        instance_layers: &[String],
        features: PhysicalDeviceFeatures,
    ) -> Result<Arc<RenderDevice>> {
        let instance =
            self.create_vulkan_instance(instance_extensions, instance_layers)?;

        let surface = {
            let mut surface_handle: u64 = 0;
            let result =
                vk::Result::from_raw(self.window_handle.create_window_surface(
                    instance.ash().handle().as_raw() as usize,
                    std::ptr::null(),
                    &mut surface_handle,
                ) as i32);
            if result != vk::Result::SUCCESS {
                bail!("Unable to create a Vulkan SurfaceKHR with GLFW!");
            }
            vk::SurfaceKHR::from_raw(surface_handle)
        };

        let device = RenderDevice::new(instance, features, surface)
            .context("Unable to create the render device!")?;

        log::debug!("{}", device);

        Ok(Arc::new(device))
    }

    /// Create a Vulkan instance with extensions and layers configured to
    /// such that it can present swapchain frames to the window.
    ///
    /// # Params
    ///
    /// * `instance_extensions` - Any extensions to enable when creating the
    ///   instance. Extensions for the swapchain on the current platform are
    ///   added automatically and do not need to be provided.
    /// * `instance_layers` - Any additional layers to provide. The khronos
    ///   validation layer is added automatically when debug assertions are
    ///   enabled.
    ///
    /// # Safety
    ///
    /// The application is responsible for synchronizing access to all Vulkan
    /// resources and destroying the Vulkan instance at exit.
    pub unsafe fn create_vulkan_instance(
        &self,
        instance_extensions: &[String],
        instance_layers: &[String],
    ) -> Result<VulkanInstance> {
        let mut all_instance_extensions =
            self.glfw.get_required_instance_extensions().context(
                "Cannot get the required instance extensions for this platform",
            )?;
        all_instance_extensions.extend_from_slice(instance_extensions);

        let mut all_layers = instance_layers.to_vec();
        if cfg!(debug_assertions) {
            all_layers.push("VK_LAYER_KHRONOS_validation".to_owned());
        }

        unsafe {
            VulkanInstance::new(&all_instance_extensions, &all_layers)
                .context("Error createing the Vulkan instance!")
        }
    }
}

impl std::ops::Deref for GlfwWindow {
    type Target = glfw::Window;

    fn deref(&self) -> &Self::Target {
        &self.window_handle
    }
}

impl std::ops::DerefMut for GlfwWindow {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.window_handle
    }
}