forked from bwasty/vulkan-tutorial-rs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
11_render_passes.rs
458 lines (387 loc) · 15.4 KB
/
11_render_passes.rs
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
#[macro_use]
extern crate vulkano;
#[macro_use]
extern crate vulkano_shader_derive;
extern crate vulkano_win;
extern crate winit;
use std::sync::Arc;
use std::collections::HashSet;
use winit::{EventsLoop, WindowBuilder, Window, dpi::LogicalSize, Event, WindowEvent};
use vulkano_win::VkSurfaceBuild;
use vulkano::instance::{
Instance,
InstanceExtensions,
ApplicationInfo,
Version,
layers_list,
PhysicalDevice,
Features
};
use vulkano::instance::debug::{DebugCallback, MessageTypes};
use vulkano::device::{Device, DeviceExtensions, Queue};
use vulkano::swapchain::{
Surface,
Capabilities,
ColorSpace,
SupportedPresentModes,
PresentMode,
Swapchain,
CompositeAlpha,
};
use vulkano::format::Format;
use vulkano::image::{ImageUsage, swapchain::SwapchainImage};
use vulkano::sync::SharingMode;
use vulkano::pipeline::{
GraphicsPipeline,
vertex::BufferlessDefinition,
viewport::Viewport,
};
use vulkano::framebuffer::{
RenderPassAbstract,
};
const WIDTH: u32 = 800;
const HEIGHT: u32 = 600;
const VALIDATION_LAYERS: &[&str] = &[
"VK_LAYER_LUNARG_standard_validation"
];
/// Required device extensions
fn device_extensions() -> DeviceExtensions {
DeviceExtensions {
khr_swapchain: true,
.. vulkano::device::DeviceExtensions::none()
}
}
#[cfg(all(debug_assertions))]
const ENABLE_VALIDATION_LAYERS: bool = true;
#[cfg(not(debug_assertions))]
const ENABLE_VALIDATION_LAYERS: bool = false;
struct QueueFamilyIndices {
graphics_family: i32,
present_family: i32,
}
impl QueueFamilyIndices {
fn new() -> Self {
Self { graphics_family: -1, present_family: -1 }
}
fn is_complete(&self) -> bool {
self.graphics_family >= 0 && self.present_family >= 0
}
}
#[allow(unused)]
struct HelloTriangleApplication {
instance: Arc<Instance>,
debug_callback: Option<DebugCallback>,
events_loop: EventsLoop,
surface: Arc<Surface<Window>>,
physical_device_index: usize, // can't store PhysicalDevice directly (lifetime issues)
device: Arc<Device>,
graphics_queue: Arc<Queue>,
present_queue: Arc<Queue>,
swap_chain: Arc<Swapchain<Window>>,
swap_chain_images: Vec<Arc<SwapchainImage<Window>>>,
render_pass: Arc<RenderPassAbstract + Send + Sync>,
}
impl HelloTriangleApplication {
pub fn initialize() -> Self {
let instance = Self::create_instance();
let debug_callback = Self::setup_debug_callback(&instance);
let (events_loop, surface) = Self::create_surface(&instance);
let physical_device_index = Self::pick_physical_device(&instance, &surface);
let (device, graphics_queue, present_queue) = Self::create_logical_device(
&instance, &surface, physical_device_index);
let (swap_chain, swap_chain_images) = Self::create_swap_chain(&instance, &surface, physical_device_index,
&device, &graphics_queue, &present_queue);
let render_pass = Self::create_render_pass(&device, swap_chain.format());
Self::create_graphics_pipeline(&device, swap_chain.dimensions());
Self {
instance,
debug_callback,
events_loop,
surface,
physical_device_index,
device,
graphics_queue,
present_queue,
swap_chain,
swap_chain_images,
render_pass,
}
}
fn create_instance() -> Arc<Instance> {
if ENABLE_VALIDATION_LAYERS && !Self::check_validation_layer_support() {
println!("Validation layers requested, but not available!")
}
let supported_extensions = InstanceExtensions::supported_by_core()
.expect("failed to retrieve supported extensions");
println!("Supported extensions: {:?}", supported_extensions);
let app_info = ApplicationInfo {
application_name: Some("Hello Triangle".into()),
application_version: Some(Version { major: 1, minor: 0, patch: 0 }),
engine_name: Some("No Engine".into()),
engine_version: Some(Version { major: 1, minor: 0, patch: 0 }),
};
let required_extensions = Self::get_required_extensions();
if ENABLE_VALIDATION_LAYERS && Self::check_validation_layer_support() {
Instance::new(Some(&app_info), &required_extensions, VALIDATION_LAYERS.iter().map(|s| *s))
.expect("failed to create Vulkan instance")
} else {
Instance::new(Some(&app_info), &required_extensions, None)
.expect("failed to create Vulkan instance")
}
}
fn check_validation_layer_support() -> bool {
let layers: Vec<_> = layers_list().unwrap().map(|l| l.name().to_owned()).collect();
VALIDATION_LAYERS.iter()
.all(|layer_name| layers.contains(&layer_name.to_string()))
}
fn get_required_extensions() -> InstanceExtensions {
let mut extensions = vulkano_win::required_extensions();
if ENABLE_VALIDATION_LAYERS {
// TODO!: this should be ext_debug_utils (_report is deprecated), but that doesn't exist yet in vulkano
extensions.ext_debug_report = true;
}
extensions
}
fn setup_debug_callback(instance: &Arc<Instance>) -> Option<DebugCallback> {
if !ENABLE_VALIDATION_LAYERS {
return None;
}
let msg_types = MessageTypes {
error: true,
warning: true,
performance_warning: true,
information: false,
debug: true,
};
DebugCallback::new(&instance, msg_types, |msg| {
println!("validation layer: {:?}", msg.description);
}).ok()
}
fn pick_physical_device(instance: &Arc<Instance>, surface: &Arc<Surface<Window>>) -> usize {
PhysicalDevice::enumerate(&instance)
.position(|device| Self::is_device_suitable(surface, &device))
.expect("failed to find a suitable GPU!")
}
fn is_device_suitable(surface: &Arc<Surface<Window>>, device: &PhysicalDevice) -> bool {
let indices = Self::find_queue_families(surface, device);
let extensions_supported = Self::check_device_extension_support(device);
let swap_chain_adequate = if extensions_supported {
let capabilities = surface.capabilities(*device)
.expect("failed to get surface capabilities");
!capabilities.supported_formats.is_empty() &&
capabilities.present_modes.iter().next().is_some()
} else {
false
};
indices.is_complete() && extensions_supported && swap_chain_adequate
}
fn check_device_extension_support(device: &PhysicalDevice) -> bool {
let available_extensions = DeviceExtensions::supported_by_device(*device);
let device_extensions = device_extensions();
available_extensions.intersection(&device_extensions) == device_extensions
}
fn choose_swap_surface_format(available_formats: &[(Format, ColorSpace)]) -> (Format, ColorSpace) {
// NOTE: the 'preferred format' mentioned in the tutorial doesn't seem to be
// queryable in Vulkano (no VK_FORMAT_UNDEFINED enum)
*available_formats.iter()
.find(|(format, color_space)|
*format == Format::B8G8R8A8Unorm && *color_space == ColorSpace::SrgbNonLinear
)
.unwrap_or_else(|| &available_formats[0])
}
fn choose_swap_present_mode(available_present_modes: SupportedPresentModes) -> PresentMode {
if available_present_modes.mailbox {
PresentMode::Mailbox
} else if available_present_modes.immediate {
PresentMode::Immediate
} else {
PresentMode::Fifo
}
}
fn choose_swap_extent(capabilities: &Capabilities) -> [u32; 2] {
if let Some(current_extent) = capabilities.current_extent {
return current_extent
} else {
let mut actual_extent = [WIDTH, HEIGHT];
actual_extent[0] = capabilities.min_image_extent[0]
.max(capabilities.max_image_extent[0].min(actual_extent[0]));
actual_extent[1] = capabilities.min_image_extent[1]
.max(capabilities.max_image_extent[1].min(actual_extent[1]));
actual_extent
}
}
fn create_swap_chain(
instance: &Arc<Instance>,
surface: &Arc<Surface<Window>>,
physical_device_index: usize,
device: &Arc<Device>,
graphics_queue: &Arc<Queue>,
present_queue: &Arc<Queue>,
) -> (Arc<Swapchain<Window>>, Vec<Arc<SwapchainImage<Window>>>) {
let physical_device = PhysicalDevice::from_index(&instance, physical_device_index).unwrap();
let capabilities = surface.capabilities(physical_device)
.expect("failed to get surface capabilities");
let surface_format = Self::choose_swap_surface_format(&capabilities.supported_formats);
let present_mode = Self::choose_swap_present_mode(capabilities.present_modes);
let extent = Self::choose_swap_extent(&capabilities);
let mut image_count = capabilities.min_image_count + 1;
if capabilities.max_image_count.is_some() && image_count > capabilities.max_image_count.unwrap() {
image_count = capabilities.max_image_count.unwrap();
}
let image_usage = ImageUsage {
color_attachment: true,
.. ImageUsage::none()
};
let indices = Self::find_queue_families(&surface, &physical_device);
let sharing: SharingMode = if indices.graphics_family != indices.present_family {
vec![graphics_queue, present_queue].as_slice().into()
} else {
graphics_queue.into()
};
let (swap_chain, images) = Swapchain::new(
device.clone(),
surface.clone(),
image_count,
surface_format.0, // TODO: color space?
extent,
1, // layers
image_usage,
sharing,
capabilities.current_transform,
CompositeAlpha::Opaque,
present_mode,
true, // clipped
None,
).expect("failed to create swap chain!");
(swap_chain, images)
}
fn create_render_pass(device: &Arc<Device>, color_format: Format) -> Arc<RenderPassAbstract + Send + Sync> {
Arc::new(single_pass_renderpass!(device.clone(),
attachments: {
color: {
load: Clear,
store: Store,
format: color_format,
samples: 1,
}
},
pass: {
color: [color],
depth_stencil: {}
}
).unwrap())
}
fn create_graphics_pipeline(
device: &Arc<Device>,
swap_chain_extent: [u32; 2],
) {
#[allow(unused)]
mod vertex_shader {
#[derive(VulkanoShader)]
#[ty = "vertex"]
#[path = "src/bin/09_shader_base.vert"]
struct Dummy;
}
#[allow(unused)]
mod fragment_shader {
#[derive(VulkanoShader)]
#[ty = "fragment"]
#[path = "src/bin/09_shader_base.frag"]
struct Dummy;
}
let vert_shader_module = vertex_shader::Shader::load(device.clone())
.expect("failed to create vertex shader module!");
let frag_shader_module = fragment_shader::Shader::load(device.clone())
.expect("failed to create fragment shader module!");
let dimensions = [swap_chain_extent[0] as f32, swap_chain_extent[1] as f32];
let viewport = Viewport {
origin: [0.0, 0.0],
dimensions,
depth_range: 0.0 .. 1.0,
};
let _pipeline_builder = Arc::new(GraphicsPipeline::start()
.vertex_input(BufferlessDefinition {})
.vertex_shader(vert_shader_module.main_entry_point(), ())
.triangle_list()
.primitive_restart(false)
.viewports(vec![viewport]) // NOTE: also sets scissor to cover whole viewport
.fragment_shader(frag_shader_module.main_entry_point(), ())
.depth_clamp(false)
// NOTE: there's an outcommented .rasterizer_discard() in Vulkano...
.polygon_mode_fill() // = default
.line_width(1.0) // = default
.cull_mode_back()
.front_face_clockwise()
// NOTE: no depth_bias here, but on pipeline::raster::Rasterization
.blend_pass_through() // = default
);
}
fn find_queue_families(surface: &Arc<Surface<Window>>, device: &PhysicalDevice) -> QueueFamilyIndices {
let mut indices = QueueFamilyIndices::new();
// TODO: replace index with id to simplify?
for (i, queue_family) in device.queue_families().enumerate() {
if queue_family.supports_graphics() {
indices.graphics_family = i as i32;
}
if surface.is_supported(queue_family).unwrap() {
indices.present_family = i as i32;
}
if indices.is_complete() {
break;
}
}
indices
}
fn create_logical_device(
instance: &Arc<Instance>,
surface: &Arc<Surface<Window>>,
physical_device_index: usize,
) -> (Arc<Device>, Arc<Queue>, Arc<Queue>) {
let physical_device = PhysicalDevice::from_index(&instance, physical_device_index).unwrap();
let indices = Self::find_queue_families(&surface, &physical_device);
let families = [indices.graphics_family, indices.present_family];
use std::iter::FromIterator;
let unique_queue_families: HashSet<&i32> = HashSet::from_iter(families.iter());
let queue_priority = 1.0;
let queue_families = unique_queue_families.iter().map(|i| {
(physical_device.queue_families().nth(**i as usize).unwrap(), queue_priority)
});
// NOTE: the tutorial recommends passing the validation layers as well
// for legacy reasons (if ENABLE_VALIDATION_LAYERS is true). Vulkano handles that
// for us internally.
let (device, mut queues) = Device::new(physical_device, &Features::none(),
&device_extensions(), queue_families)
.expect("failed to create logical device!");
let graphics_queue = queues.next().unwrap();
let present_queue = queues.next().unwrap_or_else(|| graphics_queue.clone());
(device, graphics_queue, present_queue)
}
fn create_surface(instance: &Arc<Instance>) -> (EventsLoop, Arc<Surface<Window>>) {
let events_loop = EventsLoop::new();
let surface = WindowBuilder::new()
.with_title("Vulkan")
.with_dimensions(LogicalSize::new(f64::from(WIDTH), f64::from(HEIGHT)))
.build_vk_surface(&events_loop, instance.clone())
.expect("failed to create window surface!");
(events_loop, surface)
}
#[allow(unused)]
fn main_loop(&mut self) {
loop {
let mut done = false;
self.events_loop.poll_events(|ev| {
match ev {
Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => done = true,
_ => ()
}
});
if done {
return;
}
}
}
}
fn main() {
let mut _app = HelloTriangleApplication::initialize();
// app.main_loop();
}