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
use super::{VK_FORMATS, to_sk_format};
use crate::{
context::page::Page,
gpu::{RenderCache, RenderState::Resizing},
};
use ash::vk::Handle;
use skia_safe::{
Color, Image, Matrix, Paint, SurfaceProps,
canvas::SrcRectConstraint,
gpu::{self, backend_render_targets, direct_contexts, surfaces, vk},
};
use std::{ptr, sync::Arc};
use vulkano::{
Validated, VulkanError, VulkanLibrary, VulkanObject,
device::{
Device, DeviceCreateInfo, DeviceExtensions, DeviceOwned, Queue, QueueCreateInfo,
QueueFlags, physical::PhysicalDeviceType,
},
image::{ImageUsage, view::ImageView},
instance::{Instance, InstanceCreateFlags, InstanceCreateInfo},
render_pass::{Framebuffer, FramebufferCreateInfo, RenderPass},
swapchain::{
CompositeAlpha, Surface, Swapchain, SwapchainAcquireFuture, SwapchainCreateInfo,
SwapchainPresentInfo, acquire_next_image,
},
sync::{self, GpuFuture},
};
use winit::{dpi::PhysicalSize, event_loop::ActiveEventLoop, window::Window};
pub struct VulkanRenderer {
window: Arc<Window>,
cache: RenderCache, /* must be listed before backend to ensure proper
* drop order */
backend: VulkanBackend,
}
impl VulkanRenderer {
pub fn for_window(event_loop: &ActiveEventLoop, window: Arc<Window>) -> Self {
let instance = {
// SAFETY: Vulkan must be available since status check passed.
let library = VulkanLibrary::new().expect("Vulkan libraries not found on system");
let required_extensions = Surface::required_extensions(event_loop)
// SAFETY: Vulkan must be available since status check passed.
.expect("Failed to get required Vulkan extensions");
Instance::new(
library,
InstanceCreateInfo {
flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, // support MoltenVK
enabled_extensions: required_extensions,
..Default::default()
},
)
.unwrap_or_else(|_| {
panic!(
"Vulkan: could not create instance supporting: {:?}",
required_extensions
)
})
};
let device_extensions = DeviceExtensions {
khr_swapchain: true, /* we need a swapchain to manage repainting
* the window */
..DeviceExtensions::empty()
};
let surface = Surface::from_window(instance.clone(), window.clone())
// SAFETY: Surface creation only fails on driver bugs.
.expect("Vulkan: failed to create window surface");
// Collect the list of available devices & queues then select ‘best’ one
// for our needs
let (physical_device, queue_family_index) = instance
.enumerate_physical_devices()
// SAFETY: Vulkan must be available since status check passed.
.expect("Vulkan: failed to enumerate physical devices")
.filter(|p| {
// omit devices that don't support our swapchain requirement
p.supported_extensions().contains(&device_extensions)
})
.filter_map(|p| {
// for each device, find a graphics queue family that can handle
// our surface type and filter out any devices
// that don't have one
p.queue_family_properties()
.iter()
.enumerate()
.position(|(i, q)| {
q.queue_flags.intersects(QueueFlags::GRAPHICS)
&& p.surface_support(i as u32, &surface).unwrap_or(false)
// && p.presentation_support(_i as u32,
// event_loop).unwrap() // unreleased
})
.map(|i| (p, i as u32))
})
.min_by_key(|(p, _)| {
// Sort the list of acceptible devices/queues to try to find the
// fastest
match p.properties().device_type {
PhysicalDeviceType::DiscreteGpu => 0,
PhysicalDeviceType::IntegratedGpu => 1,
PhysicalDeviceType::VirtualGpu => 2,
PhysicalDeviceType::Cpu => 3,
PhysicalDeviceType::Other => 4,
_ => 5,
}
})
// SAFETY: Device creation failure indicates incompatible hardware.
.expect("Vulkan: no suitable physical device found");
// Use the physical device we selected to initialize a device with a
// single queue
let (device, mut queues) = Device::new(
physical_device.clone(),
DeviceCreateInfo {
enabled_extensions: device_extensions,
queue_create_infos: vec![QueueCreateInfo {
queue_family_index,
..Default::default()
}],
..Default::default()
},
)
// SAFETY: Device creation failure indicates incompatible hardware.
.expect("Vulkan: device initialization failed");
// SAFETY: Device creation failure indicates incompatible hardware.
let queue = queues.next().expect("Vulkan: device has no queues");
// Create a swapchain to manage frame buffers and vsync
let (swapchain, _images) = {
// inspect the window to determine the type of framebuffer needed
let surface = Surface::from_window(instance.clone(), window.clone())
// SAFETY: Surface/framebuffer creation only fails on driver bugs.
.expect("Vulkan: failed to create swapchain surface");
let surface_capabilities = physical_device
.surface_capabilities(&surface, Default::default())
// SAFETY: Swapchain setup failures indicate GPU driver issues.
.expect("Vulkan: failed to query surface capabilities");
// choose the first device format that is on the supported list
let device_formats = physical_device
.surface_formats(&surface, Default::default())
// SAFETY: Swapchain setup failures indicate GPU driver issues.
.expect("Vulkan: failed to query surface formats");
let (image_format, _) = device_formats.clone()
.into_iter()
.find(|(fmt, _)| VK_FORMATS.contains(fmt))
.unwrap_or_else(||
panic!(
"Vulkan: no format supported by Skia was found on device.\nSupported formats: {:?}\nDevice formats: {:?}",
VK_FORMATS,
device_formats
)
);
Swapchain::new(
device.clone(),
surface,
SwapchainCreateInfo {
image_format,
image_extent: window.inner_size().into(),
image_usage: ImageUsage::COLOR_ATTACHMENT,
min_image_count: surface_capabilities.min_image_count.max(2),
composite_alpha: surface_capabilities
.supported_composite_alpha
.into_iter()
.min_by_key(|mode| {
// prefer transparency (TODO: this should be
// dependent on window background…)
match mode {
CompositeAlpha::PostMultiplied => 1,
CompositeAlpha::PreMultiplied => 2,
CompositeAlpha::Opaque => 3,
_ => 3,
}
})
// SAFETY: Swapchain setup failures indicate GPU driver issues.
.expect("Vulkan: no composite alpha mode available"),
..Default::default()
},
)
// SAFETY: Swapchain setup failures indicate GPU driver issues.
.expect("Vulkan: failed to create swapchain")
};
Self {
window,
backend: VulkanBackend::new(queue, swapchain),
cache: RenderCache::default(),
}
}
pub fn resize(&mut self, size: PhysicalSize<u32>) {
self.cache.state = Resizing;
self.backend.swapchain_is_valid = false;
self.backend.prepare_swapchain(size);
}
pub fn draw(&mut self, page: Page, matrix: Matrix, props: SurfaceProps, matte: Color) {
let (clip, _) = matrix.map_rect(page.bounds);
let dpr = self.window.scale_factor() as f32;
if let Some(frame) = self.backend.render_frame(&self.window, &props, |canvas| {
// draw background (either use raster cache or set to window’s
// background color)
canvas.clear(Color::TRANSPARENT);
if let Some((image, src, dst)) = self.cache.validate(&page, matte, dpr, clip) {
canvas.draw_image_rect(
image,
Some((src, SrcRectConstraint::Strict)),
dst,
&Paint::default(),
);
} else {
canvas.clear(matte);
}
// draw newly added vector layers
canvas.scale((dpr, dpr)).clip_rect(clip, None, Some(true));
for pict in page.layers.iter().skip(self.cache.depth()) {
canvas.draw_picture(pict, Some(&matrix), None);
}
}) {
self.cache.update(frame, &page, matte, dpr, clip);
}
}
}
struct VulkanBackend {
framebuffers: Vec<Arc<Framebuffer>>,
render_pass: Arc<RenderPass>,
swapchain: Arc<Swapchain>,
swapchain_is_valid: bool,
last_render: Option<Box<dyn GpuFuture>>,
skia_ctx: gpu::DirectContext, /* must be listed before parent queue to
* ensure proper drop order */
queue: Arc<Queue>,
}
impl Drop for VulkanBackend {
fn drop(&mut self) {
self.skia_ctx.release_resources_and_abandon();
}
}
impl VulkanBackend {
fn new(queue: Arc<Queue>, swapchain: Arc<Swapchain>) -> Self {
let device = queue.device();
let instance = device.instance();
let library = instance.library();
// Define the layout of the framebuffers and their role in the graphics
// pipeline
let render_pass = vulkano::single_pass_renderpass!(
device.clone(),
attachments: {
canvas_img: {
format: swapchain.image_format(),
samples: 1, // no need for MSAA since we're rendering 1:1
load_op: DontCare, // don't clear framebuffers ahead of time
store_op: DontCare, // we don't need the bitmap back after display
},
},
pass: {
// the only attachment will be the bitmap rendered by skia
color: [canvas_img],
depth_stencil: {},
},
)
// SAFETY: Surface/framebuffer creation only fails on driver bugs.
.expect("Vulkan: failed to create render pass");
// Start with no framebuffers and flag that they need to be allocated
// before rendering
let framebuffers = vec![];
let swapchain_is_valid = false;
// Hold onto the previous GpuFuture so we can wait on its completion
// before the next frame
let last_render = Some(sync::now(device.clone()).boxed());
// Create a DirectContext that will let us use a surface & canvas to
// draw into framebuffers
let skia_ctx = unsafe {
let get_proc = |gpo| {
let get_device_proc_addr = instance.fns().v1_0.get_device_proc_addr;
match gpo {
vk::GetProcOf::Instance(instance, name) => {
let vk_instance = ash::vk::Instance::from_raw(instance as _);
library.get_instance_proc_addr(vk_instance, name)
}
vk::GetProcOf::Device(device, name) => {
let vk_device = ash::vk::Device::from_raw(device as _);
get_device_proc_addr(vk_device, name)
}
}
.map(|f| f as _)
.unwrap_or_else(|| {
println!("Vulkan: failed to resolve {}", gpo.name().to_string_lossy());
ptr::null()
})
};
direct_contexts::make_vulkan(
&vk::BackendContext::new(
instance.handle().as_raw() as _,
device.physical_device().handle().as_raw() as _,
device.handle().as_raw() as _,
(
queue.handle().as_raw() as _,
queue.queue_family_index() as usize,
),
&get_proc,
),
None,
)
// SAFETY: Vulkan must be available since status check passed.
.expect("Vulkan: Failed to create Skia direct context")
};
Self {
queue,
framebuffers,
render_pass,
swapchain,
swapchain_is_valid,
last_render,
skia_ctx,
}
}
fn prepare_swapchain(&mut self, size: PhysicalSize<u32>) {
// Only regenerate the swapchain/framebuffers if we've flagged that it's
// necessary
if size.width > 0 && size.height > 0 && !self.swapchain_is_valid {
let (new_swapchain, new_images) = self
.swapchain
.recreate(SwapchainCreateInfo {
image_extent: size.into(),
..self.swapchain.create_info()
})
// SAFETY: Swapchain setup failures indicate GPU driver issues.
.expect("failed to recreate swapchain");
self.swapchain = new_swapchain;
self.framebuffers = new_images
.iter()
.map(|image| {
Framebuffer::new(
self.render_pass.clone(),
FramebufferCreateInfo {
attachments: vec![
ImageView::new_default(image.clone())
// SAFETY: Surface/framebuffer creation only fails on driver bugs.
.expect("Vulkan: failed to create image view"),
],
..Default::default()
},
)
// SAFETY: Surface/framebuffer creation only fails on driver bugs.
.expect("Vulkan: failed to create framebuffer")
})
.collect();
self.swapchain_is_valid = true;
}
}
fn render_frame<F>(&mut self, window: &Window, props: &SurfaceProps, f: F) -> Option<Image>
where
F: FnOnce(&skia_safe::Canvas),
{
// make sure the framebuffers match the current window size
self.prepare_swapchain(self.swapchain.image_extent().into());
self.get_next_frame().map(|(image_index, acquire_future)| {
// pull the appropriate framebuffer and create a skia Surface that
// renders to it
let framebuffer = self.framebuffers[image_index as usize].clone();
let mut surface = self.surface_for_framebuffer(framebuffer.clone(), props);
// pass the suface's canvas to the user-provided callback
f(surface.canvas());
// save a copy of the bitmap for the cache
let image = surface.image_snapshot();
// display the result
self.flush_framebuffer(window, image_index, acquire_future);
image
})
}
fn get_next_frame(&mut self) -> Option<(u32, SwapchainAcquireFuture)> {
// Request the next framebuffer and a GpuFuture for the render pass
let (image_index, suboptimal, acquire_future) =
match acquire_next_image(self.swapchain.clone(), None).map_err(Validated::unwrap) {
Ok(r) => r,
Err(VulkanError::OutOfDate) => {
self.swapchain_is_valid = false;
return None;
}
Err(e) => panic!("failed to acquire next image: {e}"),
};
match suboptimal {
// If the request was successful but suboptimal, schedule a
// swapchain recreation
true => {
self.swapchain_is_valid = false;
None
}
// otherwise proceed with this frame
false => Some((image_index, acquire_future)),
}
}
fn surface_for_framebuffer(
&mut self,
framebuffer: Arc<Framebuffer>,
props: &SurfaceProps,
) -> skia_safe::Surface {
let [width, height] = framebuffer.extent();
let image_access = &framebuffer.attachments()[0];
let image_object = image_access.image().handle().as_raw();
let format = image_access.format();
let (vk_format, color_type) = to_sk_format(&format)
.unwrap_or_else(|| panic!("Vulkan: unsupported color format {:?}", format));
let image_info = &unsafe {
vk::ImageInfo::new(
image_object as _,
vk::Alloc::default(),
vk::ImageTiling::OPTIMAL,
vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL,
vk_format,
1,
None,
None,
None,
None,
)
};
let render_target = &backend_render_targets::make_vk(
(
width
.try_into()
// SAFETY: Window dimensions should fit in i32.
.expect("Vulkan: framebuffer width overflow"),
height
.try_into()
// SAFETY: Window dimensions should fit in i32.
.expect("Vulkan: framebuffer height overflow"),
),
image_info,
);
surfaces::wrap_backend_render_target(
&mut self.skia_ctx,
render_target,
gpu::SurfaceOrigin::TopLeft,
color_type,
None,
Some(props),
)
// SAFETY: Surface/framebuffer creation only fails on driver bugs.
.expect("Vulkan: failed to create render target surface")
}
fn flush_framebuffer(
&mut self,
window: &Window,
image_index: u32,
acquire_future: SwapchainAcquireFuture,
) {
// flush the canvas's contents to the framebuffer
self.skia_ctx.flush_and_submit();
self.skia_ctx.free_gpu_resources();
// reclaim leftover resources from the last frame
if let Some(ref mut last) = self.last_render {
last.cleanup_finished();
}
// let winit know that rendering is complete
window.pre_present_notify();
// send the framebuffer to the gpu and display it on screen
let Some(last_render) = self.last_render.take() else {
return;
};
let future = last_render
.join(acquire_future)
.then_swapchain_present(
self.queue.clone(),
SwapchainPresentInfo::swapchain_image_index(self.swapchain.clone(), image_index),
)
.then_signal_fence_and_flush();
match future.map_err(Validated::unwrap) {
Ok(future) => {
self.last_render = Some(future.boxed());
}
Err(VulkanError::OutOfDate) => {
let device = self.queue.device();
self.last_render = Some(sync::now(device.clone()).boxed());
self.swapchain_is_valid = false;
}
Err(e) => {
panic!("Vulkan: swapchain flush failed: {e}");
}
};
}
}