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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
|
#![deny(unsafe_code)]
use crate::error::*;
use std::cell::RefCell;
use std::collections::{ BTreeMap, BTreeSet, HashSet };
use std::ffi::{ c_void, CStr };
use vulkanalia::{ Device, Entry, Instance, Version };
use vulkanalia::bytecode::Bytecode;
use vulkanalia::loader::{ LibloadingLoader, LIBRARY };
use vulkanalia::vk::{ self, Handle, HasBuilder,
ApplicationInfo, InstanceCreateInfo,
DeviceV1_0, EntryV1_0, InstanceV1_0,
ExtDebugUtilsExtensionInstanceCommands,
KhrSurfaceExtensionInstanceCommands,
KhrSwapchainExtensionDeviceCommands };
use winit::dpi::LogicalSize;
use winit::application::ApplicationHandler;
use winit::event::WindowEvent;
use winit::event_loop::{ ActiveEventLoop, EventLoop };
use winit::window::{ Window, WindowAttributes, WindowId };
mod error;
const VULKAN_FIRST_PORTABILITY_VERSION: Version = Version::new(1, 3, 216);
// TODO: use VK_KHR_swapchain_maintenance1 to put a fence on the presentation
// operation. doing that will remove the requirement that we have more
// simultaneous frames than images.
const N_SIMULTANEOUS_FRAMES: usize = 5;
enum Acceptable<T> {
Accepted(T),
Rejected(String),
}
impl<T> Acceptable<T> {
#[allow(unused)]
fn is_accepted(&self) -> bool {
if let Acceptable::Accepted(_) = self { true } else { false }
}
#[allow(unused)]
fn is_rejected(&self) -> bool {
if let Acceptable::Rejected(_) = self { true } else { false }
}
#[allow(unused)]
fn unwrap(self) -> T {
if let Acceptable::Accepted(result) = self {
result
} else {
panic!("Unwrapped a rejected Acceptable.");
}
}
fn require(self) -> Result<T> {
match self {
Acceptable::Accepted(value) => Ok(value),
Acceptable::Rejected(message) => Err(Error { message }),
}
}
}
#[derive(Debug)]
struct QueueFamilyIndices {
graphics: u32,
presentation: u32,
}
struct Surreality {
// The "window" is the usual operating-system concept of a window; it's
// provided by winit, and may be X11, Wayland, or some more curious thing.
// The way we initialize Vulkan requires us to have at least one of these;
// we could have more, but for now, we don't.
window: RefCell<Option<Window>>,
// The Vulkan "entry" is the part of the Vulkan library ecosystem that's
// responsible for finding and loading the other parts. Once we have the
// instance, the entry is never directly used again, but we retain it
// because doing otherwise would segfault.
entry: RefCell<Option<Entry>>,
// The Vulkan "instance" is the bulk of the Vulkan library, with most of
// the high-level responsibilities around lifecycle management.
instance: RefCell<Option<Instance>>,
// The debug messager is a Vulkan object representing our callback which
// Vulkan uses to tell us things.
//
// Vulkan spells "messager" as "messenger", but this is absurd
// over-formality and we don't indulge it.
debug_messager: RefCell<Option<vk::DebugUtilsMessengerEXT>>,
// The Vulkan "surface" is the destination that rendering happens into.
// It is connected to the window but distinct from it.
surface: RefCell<Option<vk::SurfaceKHR>>,
// The Vulkan "device" is the abstraction for a GPU. A physical one is the
// actual GPU, and a logical one is our connection to it. We pick a physical
// device during initialization, but only the logical one is used later, so
// it's all we track. We'll be referencing the logical device a lot, so we
// follow Vulkan's lead and let it have a short variable name.
device: RefCell<Option<Device>>,
// Vulkan has a first-class concept of command queues. We have two of
// them, one for graphics drawing commands and one for presentation.
//
// While these are often the same queue, there is no guarantee of that;
// sometimes there's no queue family that supports both operations together.
// For simplicity's sake we treat them as if they're separate, though the
// handles will alias each other when the initialization logic was able to
// find a family that does both.
//
// Yes, this means the compiler has to deal with pointer aliasing
// concerns, which have a tendency to defeat optimizations.
graphics_queue: RefCell<Option<vk::Queue>>,
presentation_queue: RefCell<Option<vk::Queue>>,
window_dressing: RefCell<Option<WindowDressing>>,
frame_index: usize,
}
// Of the various Vulkan graphics objects, the WindowDressing consists of
// the ones which need to be regenerated or modified when the window changes
// in certain ways, such as resizing.
#[derive(Debug)]
struct WindowDressing {
swapchain: Swapchain,
render_pass: vk::RenderPass,
pipeline: vk::Pipeline,
pipeline_layout: vk::PipelineLayout,
framebuffers: Vec<vk::Framebuffer>,
command_pool: vk::CommandPool,
command_buffers: Vec<vk::CommandBuffer>,
concurrency: Concurrency,
}
// A swapchain is the generalized facility that is used to implement
// double buffering, triple buffering, rendering passes that feed into each
// other, and other things of that nature. It's a first-class thing but for
// now, we use at most one of it. We also support running without one.
#[derive(Debug)]
struct Swapchain {
swapchain: vk::SwapchainKHR,
images: Vec<vk::Image>,
image_views: Vec<vk::ImageView>,
format: vk::Format,
extent: vk::Extent2D,
}
#[derive(Debug)]
struct Concurrency {
image_available_semaphores: Vec<vk::Semaphore>,
rendering_finished_semaphores: Vec<vk::Semaphore>,
// Okay, the lifetime management on the fences is really subtle. There is
// one fence for each frame, and frame_fences holds the authoritative
// reference to it.
//
// There is one entry in image_fences for each image. The number of images
// is not directly related to the number of frames; it will likely be
// larger, but may be smaller or the same. At the start of execution, the
// entries are all nulls. Each time an image is acquired from the swapchain,
// the corresponding entry in image_fences is overwritten with a duplicate
// of the frame fence. This happens during rendering of the frame, so the
// frame fence is in the "signaled" state. It will be reset right before
// submitting the queue, then signaled again when the submission completes.
frame_fences: Vec<vk::Fence>,
image_fences: Vec<vk::Fence>,
}
// These structs exist for use in function calling, to remove the potential
// for accidentally passing or returning one boolean as if it's another.
struct EnablePortability(bool);
struct EnableValidation(bool);
struct EnableSwapchain(bool);
impl Surreality {
fn new() -> Self {
Surreality {
window: RefCell::new(None),
entry: RefCell::new(None),
instance: RefCell::new(None),
debug_messager: RefCell::new(None),
surface: RefCell::new(None),
device: RefCell::new(None),
graphics_queue: RefCell::new(None),
presentation_queue: RefCell::new(None),
window_dressing: RefCell::new(None),
frame_index: 0,
}
}
fn init(&mut self, event_loop: &ActiveEventLoop) -> Result<()> {
let window = Self::init_window(event_loop)?;
// There are a few Vulkan features (in the informal sense of
// "feature") that we want to be able to run both with and without.
// The enable_* values, here and below, are wrapped booleans that describe
// those choices.
//
// These are only used to communicate between initialization
// phases; we don't keep them around after that.
let (entry, instance, debug_messager,
enable_portability, enable_validation)
= Self::init_vulkan(&window)?;
let surface = Self::init_surface(&window, &instance)?;
let (physical_device, device,
indices, graphics_queue, presentation_queue,
enable_swapchain)
= Self::init_vulkan_device(&instance, &surface,
enable_validation, enable_portability)?;
if enable_swapchain.0 {
let swapchain = Self::init_swapchain(
&window, &instance, &surface, &physical_device, &device,
&indices)?;
let render_pass = Surreality::init_render_pass(&device,
&swapchain.format)?;
let (pipeline_layout, pipeline)
= Self::init_pipeline(&device, &swapchain.extent,
&render_pass)?;
let framebuffers = Self::init_framebuffers(
&device, &swapchain.extent, &swapchain.image_views,
&render_pass)?;
let (command_pool, command_buffers)
= Self::init_commands(&device, &swapchain.extent, &framebuffers,
&render_pass, &pipeline, &indices)?;
let concurrency = Self::init_concurrency(&device, &swapchain.images)?;
*self.window_dressing.get_mut() = Some(WindowDressing {
swapchain,
render_pass,
pipeline,
pipeline_layout,
framebuffers,
command_pool,
command_buffers,
concurrency,
});
}
*self.window.get_mut() = Some(window);
*self.entry.get_mut() = Some(entry);
*self.instance.get_mut() = Some(instance);
*self.debug_messager.get_mut() = debug_messager;
*self.surface.get_mut() = Some(surface);
*self.device.get_mut() = Some(device);
*self.graphics_queue.get_mut() = Some(graphics_queue);
*self.presentation_queue.get_mut() = Some(presentation_queue);
Ok(())
}
fn init_window(event_loop: &ActiveEventLoop) -> Result<Window> {
// Notice that we do this before having a Vulkan instance. The window is
// actually a parameter needed to create the instance; see
// init_vulkan(), below.
let window_attributes = WindowAttributes::default()
.with_title("Love, Curiosity, Justice")
.with_inner_size(LogicalSize::new(1024, 768));
Ok(event_loop.create_window(window_attributes)?)
}
#[allow(unsafe_code)]
fn init_vulkan(window: &Window)
-> Result<(Entry, Instance, Option<vk::DebugUtilsMessengerEXT>,
EnablePortability, EnableValidation)>
{
let enable_validation = cfg!(feature = "vulkan-validation")
|| cfg!(debug_assertions);
// Okay, so, a Vulkan "entry" is a small set of functions which are used
// to dynamically load all the rest of Vulkan. It's our responsibility to
// know how to load the entry, then it will take care of the rest. At
// least, that's the theory, but also see flake.nix for all the
// FHS-centric assumptions it makes that we have to correct.
//
// Anyway, Vulkanalia offers an integration with libloading, which is a
// crate that wraps POSIX dlopen(). We use that; it's enabled by
// Vulkanalia's "libloading" feature.
let loader = unsafe { LibloadingLoader::new(LIBRARY) }?;
let entry = unsafe { Entry::new(loader) }?;
// Since there's a lot of factors going into our instance creation
// request, we'll build up the parameters mutably.
let mut flags = vk::InstanceCreateFlags::empty();
let mut extensions = Vec::new();
let mut layers = Vec::new();
// Before we go any further, use Vulkan's introspection to list off
// what's available.
let mut available_extensions = HashSet::new();
for extension in
unsafe { entry.enumerate_instance_extension_properties(None) }?
{
available_extensions.insert(extension.extension_name);
}
let available_extensions = available_extensions;
let mut available_layers = HashSet::new();
for layer in unsafe { entry.enumerate_instance_layer_properties() }? {
available_layers.insert(layer.layer_name);
}
let available_layers = available_layers;
// There are certain extensions which are required by the nature of our
// windowing system. Happily, vulanaklia knows how to deal with that based
// on the type of window we give it.
//
// This is possible because of an integration between Vulkanalia and
// winit, which is enabled by Vulkanalia's "window" feature.
for extension in vulkanalia::window::get_required_instance_extensions(
window)
{
extensions.push(extension.as_ptr());
}
// Deal with Vulkan's thing about opting in to non-conforming
// implementations.
let enable_portability = if entry.version()?
>= VULKAN_FIRST_PORTABILITY_VERSION
{
if cfg!(target_os = "macos") {
// Vulkan on the Mac is not fully conforming.
extensions.push(
vk::KHR_GET_PHYSICAL_DEVICE_PROPERTIES2_EXTENSION.name.as_ptr());
extensions.push(
vk::KHR_PORTABILITY_ENUMERATION_EXTENSION.name.as_ptr());
flags.insert(vk::InstanceCreateFlags::ENUMERATE_PORTABILITY_KHR);
EnablePortability(true)
} else {
EnablePortability(false)
}
} else {
EnablePortability(false)
};
// Request the LunarG validation layer, when appropriate.
let validation_layer_name = vk::ExtensionName::from_bytes(
b"VK_LAYER_KHRONOS_validation");
let enable_validation = if enable_validation {
if available_layers.contains(&validation_layer_name) {
layers.push(validation_layer_name.as_ptr());
EnableValidation(true)
} else {
eprintln!("Vulkan validation requested at build time, \
but no validation layer available.");
EnableValidation(false)
}
} else {
EnableValidation(false)
};
// Request the debug extension. This is the first of three bits of code
// that deal with this, and has the resonsibility of making sure the
// extension is in the list we ask for.
let debug_extension_name = vk::EXT_DEBUG_UTILS_EXTENSION.name;
if available_extensions.contains(&debug_extension_name) {
extensions.push(debug_extension_name.as_ptr());
} else {
eprintln!("Vulkan debug extension not available; \
this may mean other messages don't show up.");
}
let application_info = ApplicationInfo::builder()
.application_name(b"Surreality\0")
.application_version(vk::make_version(1, 0, 0))
.engine_name(b"Surreality\0")
.engine_version(vk::make_version(1, 0, 0))
.api_version(vk::make_version(1, 0, 0));
// Deceptively, this DOES get mutated later, but Vulkanalia doesn't see
// it that way.
let instance_create_info = InstanceCreateInfo::builder()
.application_info(&application_info)
.flags(flags)
.enabled_extension_names(&extensions)
.enabled_layer_names(&layers);
// Configure the debug extension. This is the middle of three bits of
// code that deal with this, and has the responsibility of making sure
// the callback will be available during instance creation and
// destruction, which is done in a special way that doesn't rely on having
// a messager, since there can't be one for those steps.
let debug_info = if available_extensions.contains(&debug_extension_name) {
let mut debug_info = vk::DebugUtilsMessengerCreateInfoEXT::builder()
.message_severity(vk::DebugUtilsMessageSeverityFlagsEXT::all())
.message_type(vk::DebugUtilsMessageTypeFlagsEXT::GENERAL
| vk::DebugUtilsMessageTypeFlagsEXT::VALIDATION
| vk::DebugUtilsMessageTypeFlagsEXT::PERFORMANCE)
.user_callback(Some(debug_messager_callback));
// Please notice that the reference we pass here will escape Rust's
// lifetime checking, since push_next() casts it to a pointer. We don't
// get nearly as strong a safety guarantee as one might hope (and as [1]
// naively reassures us we do). If we did, the thing we're doing would
// actually be forbidden!
//
// [1] https://kylemayes.github.io/vulkanalia/
instance_create_info.push_next(&mut debug_info);
Some(debug_info)
} else { None };
let instance = unsafe {
// We're promising that every struct referenced here is still alive.
// Since it's all pointers, that's... not a thing we statically know. Be
// aware. Only you can prevent segfaults.
entry.create_instance(&instance_create_info, None)
}?;
// Configure the debug extension. This is the last of three bits of code
// that deal with this, and has the responsibility of asking the instance,
// which now exists, to create the debug messager.
let debug_messager = if let Some(debug_info) = debug_info {
#[allow(unsafe_code)]
Some(unsafe {
instance.create_debug_utils_messenger_ext(&debug_info, None)
}?)
} else {
None
};
Ok((entry, instance, debug_messager,
enable_portability, enable_validation))
}
// TODO this is so short that it can likely be eliminated
#[allow(unsafe_code)]
fn init_surface(window: &Window, instance: &Instance)
-> Result<vk::SurfaceKHR>
{
// Conveniently, Vulkanalia's "window" feature allows it to get the
// platform-specific stuff directly out of winit for us. This wrapper does
// not correspond 1:1 to a Vulkan function; rather, it picks the Vulkan
// function from the appropriate platform-specific extension.
//
// The reason it takes the window twice is that that first one is
// actually there to reference the display (in the x11 sense of "display"
// meaning the connection to the windowing system).
let surface = unsafe {
vulkanalia::window::create_surface(&instance, &window, &window)
}?;
Ok(surface)
}
#[allow(unsafe_code)]
fn init_vulkan_device(instance: &Instance, surface: &vk::SurfaceKHR,
enable_validation: EnableValidation,
enable_portability: EnablePortability)
-> Result<(vk::PhysicalDevice, Device, QueueFamilyIndices, vk::Queue,
vk::Queue, EnableSwapchain)>
{
let (physical_device, indices)
= Self::pick_vulkan_device(instance, surface)?;
// We enumerate the device extensions here so they can inform
// configuration. We already did this in score_vulkan_device(), but here
// it is again.
let mut available_extensions = HashSet::new();
for extension in unsafe {
instance.enumerate_device_extension_properties(physical_device, None)
}? {
available_extensions.insert(extension.extension_name);
}
let available_extensions = available_extensions;
// Old versions of Vulkan want layers to be enabled at the device
// level as well. Newer ones will ignore this and just use the instance
// layers.
let features = vk::PhysicalDeviceFeatures::builder();
let mut extensions = Vec::new();
let mut layers = Vec::new();
let validation_layer_name = vk::ExtensionName::from_bytes(
b"VK_LAYER_KHRONOS_validation");
if enable_validation.0 {
// It's not concerning if this isn't supported, because device
// layers are ignored on recent versions, they're purely historical.
if available_extensions.contains(&validation_layer_name) {
layers.push(validation_layer_name.as_ptr());
}
}
let portability_extension_name = vk::ExtensionName::from_bytes(
b"VK_KHR_portability_subset");
if enable_portability.0 {
// This is untested, since the only scenario where it would come up
// is on a Mac, which we don't actually support. Sorry, and good luck.
if available_extensions.contains(&portability_extension_name) {
extensions.push(portability_extension_name.as_ptr());
}
}
let swapchain_extension_name = vk::KHR_SWAPCHAIN_EXTENSION.name;
let enable_swapchain = if available_extensions.contains(
&swapchain_extension_name)
{
// It's important that we not call the swapchain extension
// functions until we've verified the extension is supported. To
// emphasize that, we do it on a separate line.
//
// We've done this check once already, in scoring, and now here
// we are discarding its results a second time. We'll do it for the
// third and last time in swapchain creation.
if let Acceptable::Accepted(_) = Self::find_device_swapchain_features(
&instance, &surface, &physical_device)?
{
extensions.push(swapchain_extension_name.as_ptr());
EnableSwapchain(true)
} else {
EnableSwapchain(false)
}
} else {
EnableSwapchain(false)
};
// We have one or more queue family indices; we don't know a priori
// how many, because it's possible some of them are the same. We only
// want to create one queue per distinct family, so we find the unique
// indices...
let mut unique_queue_family_indices = BTreeSet::new();
unique_queue_family_indices.insert(indices.graphics);
unique_queue_family_indices.insert(indices.presentation);
// ... then add a queue create info struct for each.
let mut queues = Vec::new();
for index in unique_queue_family_indices {
// Passing the priorities vector also implicitly sets the count of
// how many queues we are creating within the family. This nicety is
// one of the fun things Vulkanalia's builders do for us.
queues.push(vk::DeviceQueueCreateInfo::builder()
.queue_family_index(index)
.queue_priorities(&[1.0]));
}
let device_info = vk::DeviceCreateInfo::builder()
.queue_create_infos(&queues)
.enabled_layer_names(&layers)
.enabled_extension_names(&extensions)
.enabled_features(&features);
let device = unsafe {
instance.create_device(physical_device, &device_info, None)
}?;
// So, this is a little confusing. Queues are found in queue families.
// The family has an index within the device, and the queue has an index
// within the family. We computed the family index above, and when we
// created the device we told it to create just a single queue in that
// family. Now we pass both indices to find the actual queue object.
let graphics_queue = unsafe {
device.get_device_queue(indices.graphics, 0)
};
let presentation_queue = unsafe {
device.get_device_queue(indices.presentation, 0)
};
Ok((physical_device, device,
indices, graphics_queue, presentation_queue,
enable_swapchain))
}
#[allow(unsafe_code)]
fn init_swapchain(window: &Window, instance: &Instance,
surface: &vk::SurfaceKHR,
physical_device: &vk::PhysicalDevice, device: &Device,
indices: &QueueFamilyIndices)
-> Result<Swapchain>
{
let (capabilities, formats, presentation_modes)
= Self::find_device_swapchain_features(
instance, surface, physical_device)?.require()?;
let format = Self::pick_surface_format(&formats)?;
let presentation_mode
= Self::pick_presentation_mode(&presentation_modes)?;
let extent = Self::pick_image_extent(window, capabilities)?;
let mut image_count = capabilities.min_image_count + 1;
if capabilities.max_image_count != 0 {
image_count
= image_count.clamp(0, capabilities.max_image_count);
}
let mut unique_queue_family_indices = BTreeSet::new();
unique_queue_family_indices.insert(indices.graphics);
unique_queue_family_indices.insert(indices.presentation);
// If there's only one queue, we use exclusive sharing mode, which
// will allow things to work without locks. Otherwise we use concurrent
// mode.
let (ordered_indices, sharing_mode)
= if unique_queue_family_indices.len() < 2
{
(vec![indices.graphics], vk::SharingMode::EXCLUSIVE)
} else {
(vec![indices.graphics, indices.presentation],
vk::SharingMode::CONCURRENT)
};
let swapchain_info = vk::SwapchainCreateInfoKHR::builder()
.surface(*surface)
.min_image_count(image_count)
.image_format(format.format)
.image_color_space(format.color_space)
.image_extent(extent)
.image_array_layers(1)
.image_usage(vk::ImageUsageFlags::COLOR_ATTACHMENT)
.image_sharing_mode(sharing_mode)
.queue_family_indices(&ordered_indices)
.pre_transform(capabilities.current_transform)
.composite_alpha(vk::CompositeAlphaFlagsKHR::OPAQUE)
.present_mode(presentation_mode)
.clipped(true)
.old_swapchain(vk::SwapchainKHR::null());
let swapchain = unsafe {
device.create_swapchain_khr(&swapchain_info, None)
}?;
let images = unsafe {
device.get_swapchain_images_khr(swapchain)
}?;
let mut image_views = Vec::new();
for image in &images {
let components = vk::ComponentMapping::builder()
.r(vk::ComponentSwizzle::IDENTITY)
.g(vk::ComponentSwizzle::IDENTITY)
.b(vk::ComponentSwizzle::IDENTITY)
.a(vk::ComponentSwizzle::IDENTITY);
let subresource_range = vk::ImageSubresourceRange::builder()
.aspect_mask(vk::ImageAspectFlags::COLOR)
.base_mip_level(0)
.level_count(1)
.base_array_layer(0)
.layer_count(1);
let view_info = vk::ImageViewCreateInfo::builder()
.image(*image)
.view_type(vk::ImageViewType::_2D)
.format(format.format)
.components(components)
.subresource_range(subresource_range);
let view = unsafe {
device.create_image_view(&view_info, None)
}?;
image_views.push(view);
}
Ok(Swapchain {
swapchain, images, image_views,
format: format.format,
extent
})
}
#[allow(unsafe_code)]
fn init_render_pass(device: &Device, format: &vk::Format)
-> Result<vk::RenderPass>
{
let color_attachment
= vk::AttachmentDescription::builder()
.format(*format)
.samples(vk::SampleCountFlags::_1)
.load_op(vk::AttachmentLoadOp::CLEAR)
.store_op(vk::AttachmentStoreOp::STORE)
.stencil_load_op(vk::AttachmentLoadOp::DONT_CARE)
.stencil_store_op(vk::AttachmentStoreOp::DONT_CARE)
.initial_layout(vk::ImageLayout::UNDEFINED)
.final_layout(vk::ImageLayout::PRESENT_SRC_KHR);
let color_attachment_reference
= vk::AttachmentReference::builder()
.attachment(0)
.layout(vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL);
let subpass_attachments = [color_attachment_reference];
let subpass = vk::SubpassDescription::builder()
.pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS)
.color_attachments(&subpass_attachments);
let dependency
= vk::SubpassDependency::builder()
.src_subpass(vk::SUBPASS_EXTERNAL)
.src_stage_mask(
vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT)
.src_access_mask(vk::AccessFlags::empty())
.dst_subpass(0)
.dst_stage_mask(
vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT)
.dst_access_mask(vk::AccessFlags::COLOR_ATTACHMENT_WRITE);
let render_attachments = [color_attachment];
let subpasses = [subpass];
let dependencies = [dependency];
let render_pass_info = vk::RenderPassCreateInfo::builder()
.attachments(&render_attachments)
.subpasses(&subpasses)
.dependencies(&dependencies);
let render_pass = unsafe {
device.create_render_pass(&render_pass_info, None)
}?;
Ok(render_pass)
}
#[allow(unsafe_code)]
fn init_pipeline(device: &Device, extent: &vk::Extent2D,
render_pass: &vk::RenderPass)
-> Result<(vk::PipelineLayout, vk::Pipeline)>
{
let vertex_binary = include_bytes!(
concat!(env!("OUT_DIR"), "/shader.vert.spv"));
let fragment_binary = include_bytes!(
concat!(env!("OUT_DIR"), "/shader.frag.spv"));
let vertex_module
= Self::load_spirv_shader_module(device, vertex_binary)?;
let fragment_module
= Self::load_spirv_shader_module(device, fragment_binary)?;
let vertex_stage_info = vk::PipelineShaderStageCreateInfo::builder()
.stage(vk::ShaderStageFlags::VERTEX)
.module(vertex_module)
.name(b"main\0");
let fragment_stage_info = vk::PipelineShaderStageCreateInfo::builder()
.stage(vk::ShaderStageFlags::FRAGMENT)
.module(fragment_module)
.name(b"main\0");
let vertex_input_state_info
= vk::PipelineVertexInputStateCreateInfo::builder();
let input_assembly_state_info
= vk::PipelineInputAssemblyStateCreateInfo::builder()
.topology(vk::PrimitiveTopology::TRIANGLE_LIST)
.primitive_restart_enable(false);
let viewport = vk::Viewport::builder()
.x(0.0)
.y(0.0)
.width(extent.width as f32)
.height(extent.height as f32)
.min_depth(0.0)
.max_depth(1.0);
let viewports = [viewport];
let scissor = vk::Rect2D::builder()
.offset(vk::Offset2D { x: 0, y: 0 })
.extent(*extent);
let scissor_list = [scissor];
let viewport_state_info = vk::PipelineViewportStateCreateInfo::builder()
.viewports(&viewports)
.scissors(&scissor_list);
let rasterizer_state_info
= vk::PipelineRasterizationStateCreateInfo::builder()
.depth_clamp_enable(false)
.rasterizer_discard_enable(false)
.polygon_mode(vk::PolygonMode::FILL)
.line_width(1.0)
.cull_mode(vk::CullModeFlags::BACK)
.front_face(vk::FrontFace::CLOCKWISE)
.depth_bias_enable(false);
let multisample_state_info
= vk::PipelineMultisampleStateCreateInfo::builder()
.sample_shading_enable(false)
.rasterization_samples(vk::SampleCountFlags::_1);
let blend_attachment_info
= vk::PipelineColorBlendAttachmentState::builder()
.color_write_mask(vk::ColorComponentFlags::all())
.blend_enable(false)
.src_color_blend_factor(vk::BlendFactor::ONE)
.dst_color_blend_factor(vk::BlendFactor::ZERO)
.color_blend_op(vk::BlendOp::ADD)
.src_alpha_blend_factor(vk::BlendFactor::ONE)
.dst_alpha_blend_factor(vk::BlendFactor::ZERO)
.alpha_blend_op(vk::BlendOp::ADD);
let blend_attachments = [blend_attachment_info];
let blend_info = vk::PipelineColorBlendStateCreateInfo::builder()
.logic_op_enable(false)
.logic_op(vk::LogicOp::COPY)
.attachments(&blend_attachments)
.blend_constants([0.0, 0.0, 0.0, 0.0]);
let pipeline_layout_info = vk::PipelineLayoutCreateInfo::builder();
let pipeline_layout = unsafe {
device.create_pipeline_layout(&pipeline_layout_info, None)
}?;
let stages = [vertex_stage_info, fragment_stage_info];
let pipeline_info
= vk::GraphicsPipelineCreateInfo::builder()
.stages(&stages)
.vertex_input_state(&vertex_input_state_info)
.input_assembly_state(&input_assembly_state_info)
.viewport_state(&viewport_state_info)
.rasterization_state(&rasterizer_state_info)
.multisample_state(&multisample_state_info)
.color_blend_state(&blend_info)
.layout(pipeline_layout)
.render_pass(*render_pass)
.subpass(0);
let pipeline = unsafe {
device.create_graphics_pipelines(vk::PipelineCache::null(),
&[pipeline_info], None)
}?.0[0];
unsafe {
device.destroy_shader_module(vertex_module, None);
device.destroy_shader_module(fragment_module, None);
};
Ok((pipeline_layout, pipeline))
}
#[allow(unsafe_code)]
fn init_framebuffers(device: &Device, extent: &vk::Extent2D,
swapchain_image_views: &Vec<vk::ImageView>,
render_pass: &vk::RenderPass)
-> Result<Vec<vk::Framebuffer>>
{
let mut framebuffers = Vec::new();
for image_view in swapchain_image_views {
let attachments = [*image_view];
let framebuffer_info = vk::FramebufferCreateInfo::builder()
.render_pass(*render_pass)
.attachments(&attachments)
.width(extent.width)
.height(extent.height)
.layers(1);
let framebuffer = unsafe {
device.create_framebuffer(&framebuffer_info, None)
}?;
framebuffers.push(framebuffer);
}
Ok(framebuffers)
}
#[allow(unsafe_code)]
fn init_commands(device: &Device,
extent: &vk::Extent2D,
framebuffers: &Vec<vk::Framebuffer>,
render_pass: &vk::RenderPass,
pipeline: &vk::Pipeline,
indices: &QueueFamilyIndices)
-> Result<(vk::CommandPool, Vec<vk::CommandBuffer>)>
{
// We call this one last time. It's kind of a problem.
let command_pool_info = vk::CommandPoolCreateInfo::builder()
.flags(vk::CommandPoolCreateFlags::empty())
.queue_family_index(indices.graphics);
let command_pool = unsafe {
device.create_command_pool(&command_pool_info, None)
}?;
let command_buffer_allocation_info
= vk::CommandBufferAllocateInfo::builder()
.command_pool(command_pool)
.level(vk::CommandBufferLevel::PRIMARY)
.command_buffer_count(framebuffers.len() as u32);
let command_buffers = unsafe {
device.allocate_command_buffers(&command_buffer_allocation_info)
}?;
for (index, framebuffer) in framebuffers.iter().enumerate() {
let command_buffer = command_buffers[index];
let inheritance_info = vk::CommandBufferInheritanceInfo::builder();
let command_buffer_begin_info
= vk::CommandBufferBeginInfo::builder()
.flags(vk::CommandBufferUsageFlags::empty())
.inheritance_info(&inheritance_info);
unsafe {
device.begin_command_buffer(command_buffer,
&command_buffer_begin_info)
}?;
let render_area = vk::Rect2D::builder()
.offset(vk::Offset2D::default())
.extent(*extent);
let clear_value = vk::ClearValue {
color: vk::ClearColorValue {
float32: [0.0, 0.0, 0.0, 1.0]
}
};
let clear_values = [clear_value];
let begin_pass_info = vk::RenderPassBeginInfo::builder()
.render_pass(*render_pass)
.framebuffer(*framebuffer)
.render_area(render_area)
.clear_values(&clear_values);
unsafe {
device.cmd_begin_render_pass(command_buffer, &begin_pass_info,
vk::SubpassContents::INLINE)
};
unsafe {
device.cmd_bind_pipeline(command_buffer,
vk::PipelineBindPoint::GRAPHICS,
*pipeline)
};
unsafe { device.cmd_draw(command_buffer, 3, 1, 0, 0) };
unsafe { device.cmd_end_render_pass(command_buffer) };
unsafe { device.end_command_buffer(command_buffer) }?;
}
Ok((command_pool, command_buffers))
}
#[allow(unsafe_code)]
fn init_concurrency(device: &Device,
swapchain_images: &Vec<vk::Image>)
-> Result<Concurrency>
{
let semaphore_info = vk::SemaphoreCreateInfo::builder();
let fence_info = vk::FenceCreateInfo::builder()
.flags(vk::FenceCreateFlags::SIGNALED);
let mut image_available_semaphores = Vec::new();
let mut rendering_finished_semaphores = Vec::new();
let mut frame_fences = Vec::new();
for _ in 0 .. N_SIMULTANEOUS_FRAMES {
image_available_semaphores.push(unsafe {
device.create_semaphore(&semaphore_info, None)
}?);
rendering_finished_semaphores.push(unsafe {
device.create_semaphore(&semaphore_info, None)
}?);
frame_fences.push(unsafe {
device.create_fence(&fence_info, None)
}?);
}
let mut image_fences = Vec::new();
for _ in 0 .. swapchain_images.len() {
image_fences.push(vk::Fence::null());
}
Ok(Concurrency {
image_available_semaphores,
rendering_finished_semaphores,
frame_fences,
image_fences: image_fences,
})
}
// To Vulkan, a "physical" device is the actual GPU, and a "logical"
// device is per-process state that represents a connection to the GPU.
// Before we can create a logical device, we must choose which physical
// device to connect it to.
#[allow(unsafe_code)]
fn pick_vulkan_device(instance: &Instance, surface: &vk::SurfaceKHR)
-> Result<(vk::PhysicalDevice, QueueFamilyIndices)>
{
let mut best_device = None;
let mut best_score = None;
let mut best_indices = None;
let mut rejected = BTreeMap::new();
for device in unsafe { instance.enumerate_physical_devices() }? {
match Self::score_vulkan_device(instance, surface, &device)? {
Acceptable::Accepted((new_score, new_indices)) => {
if let Some(old_score) = best_score {
if new_score > old_score {
best_device = Some(device);
best_score = Some(new_score);
best_indices = Some(new_indices);
}
} else {
best_device = Some(device);
best_score = Some(new_score);
best_indices = Some(new_indices);
}
}
Acceptable::Rejected(reason) => {
let properties = unsafe {
instance.get_physical_device_properties(device)
};
let name = properties.device_name.to_string_lossy().into_owned();
rejected.insert(properties.device_id, (name, reason));
}
}
}
if let (Some(device), Some(indices)) = (best_device, best_indices) {
Ok((device, indices))
} else if rejected.is_empty() {
Err(Error {
message: "The system has no GPUs of any kind.".to_string()
})
} else {
for (_, (name, reason)) in rejected {
eprintln!("Can't run on {} because: {}", name, reason);
}
Err(Error {
message: "The system has GPUs, but none are acceptable (see above)."
.to_string()
})
}
}
// We're doing two tasks: Quantifying how strongly we prefer a device, and
// deciding whether it's acceptable at all. If it's unacceptable, it's
// possible there will be no acceptable devices, and in that case our caller
// will want to print explanations, but otherwise it'll want to be quiet. So
// the outer Result is whether we successfully evaluated the device, and the
// inner Acceptable is whether we approve of it.
//
// In the event that we find the device acceptable, we also return the
// queue family indices we'd be using if we ultimately go with it. While
// this is not strictly necessary, it's better to return them from here
// than to recompute them later on the assumption it'll work out the same.
#[allow(unsafe_code)]
fn score_vulkan_device(instance: &Instance, surface: &vk::SurfaceKHR,
physical_device: &vk::PhysicalDevice)
-> Result<Acceptable<(u64, QueueFamilyIndices)>>
{
// Not all devices support graphics, and not all devices support
// presenting to any given surface. We check whether this one is suitable
// by looking up the indices of the queue families we would use. If we
// ultimately use this device, we'll need these, so we make sure to return
// them.
let indices = match Self::find_device_queue_family_indices(
instance, surface, physical_device)?
{
Acceptable::Rejected(rationale) => {
return Ok(Acceptable::Rejected(rationale));
}
Acceptable::Accepted(indices) => indices
};
// At this point we know the device meets our high-level requirements,
// so it's just a question of scoring.
let properties = unsafe {
instance.get_physical_device_properties(*physical_device)
};
let mut score = 0;
if properties.device_type == vk::PhysicalDeviceType::DISCRETE_GPU {
// If the user has a fancy GPU, they prefer it.
score += 128;
} else if properties.device_type
== vk::PhysicalDeviceType::INTEGRATED_GPU
{
// It's still hardware rendering.
score += 96;
} else if properties.device_type == vk::PhysicalDeviceType::VIRTUAL_GPU {
// Whatever it is, the user went to some trouble to set it up.
score += 64;
} else if properties.device_type == vk::PhysicalDeviceType::CPU {
// Software rendering is slow, but at least it's a known quantity.
score += 32;
}
// If it's none of those, we don't have enough information to know if
// that's good or bad, so we assume it's bad.
// Some of our scoring will depend on what extensions the device
// supports, so we enumerate those.
let mut available_extensions = HashSet::new();
for extension in unsafe {
instance.enumerate_device_extension_properties(*physical_device, None)
}? {
available_extensions.insert(extension.extension_name);
}
let available_extensions = available_extensions;
if available_extensions.contains(&vk::KHR_SWAPCHAIN_EXTENSION.name) {
// Double buffering is both quite a nice feature to have, and a good
// indicator that this is a "real" graphics card rather than some
// trivial weird thing.
//
// With that said, however, it only counts if we're able to actually
// use it on the surface we have. Let's find out...
if let Acceptable::Accepted(_) = Self::find_device_swapchain_features(
instance, surface, physical_device)?
{
// We don't count it for enough points to override a device type
// bracket, but it's good for a lot within the bracket.
score += 16;
}
// This isn't disqualifying, so we don't worry about tracking the
// rationale. We'll deal with that later, if the device actually gets
// selected.
}
Ok(Acceptable::Accepted((score, indices)))
}
#[allow(unsafe_code)]
fn find_device_queue_family_indices(instance: &Instance,
surface: &vk::SurfaceKHR,
device: &vk::PhysicalDevice)
-> Result<Acceptable<QueueFamilyIndices>>
{
// We need a queue family that supports graphics drawing commands, and a
// queue family that supports presentation commands. These may or may not
// be the same family.
let mut graphics = None;
let mut presentation = None;
for (index, queue_family) in (unsafe {
instance.get_physical_device_queue_family_properties(*device)
}).into_iter().enumerate() {
if graphics.is_none()
&& queue_family.queue_flags.contains(vk::QueueFlags::GRAPHICS)
{
graphics = Some(index as u32);
}
if presentation.is_none() && unsafe {
instance.get_physical_device_surface_support_khr(
*device, index as u32, *surface)
}? {
presentation = Some(index as u32);
}
}
if let Some(graphics) = graphics {
if let Some(presentation) = presentation {
Ok(Acceptable::Accepted(QueueFamilyIndices {
graphics, presentation
}))
} else {
Ok(Acceptable::Rejected(
"Doesn't support presenting to our window.".to_string()))
}
} else {
Ok(Acceptable::Rejected("Doesn't support graphics.".to_string()))
}
}
// We expect our caller to have already verified that the device supports
// the swapchain extension.
#[allow(unsafe_code)]
fn find_device_swapchain_features(instance: &Instance,
surface: &vk::SurfaceKHR,
physical_device: &vk::PhysicalDevice)
-> Result<Acceptable<(vk::SurfaceCapabilitiesKHR,
Vec<vk::SurfaceFormatKHR>,
Vec<vk::PresentModeKHR>)>>
{
let capabilities = unsafe {
instance.get_physical_device_surface_capabilities_khr(
*physical_device, *surface)
}?;
let formats = unsafe {
instance.get_physical_device_surface_formats_khr(
*physical_device, *surface)
}?;
let presentation_modes = unsafe {
instance.get_physical_device_surface_present_modes_khr(
*physical_device, *surface)
}?;
if formats.is_empty() {
Ok(Acceptable::Rejected("No matching surface formats.".to_string()))
} else if presentation_modes.is_empty() {
Ok(Acceptable::Rejected("No matching presentation modes.".to_string()))
} else {
Ok(Acceptable::Accepted((capabilities, formats, presentation_modes)))
}
}
fn pick_surface_format(available_formats: &Vec<vk::SurfaceFormatKHR>)
-> Result<vk::SurfaceFormatKHR>
{
for format in available_formats {
if format.format == vk::Format::B8G8R8A8_SRGB
&& format.color_space == vk::ColorSpaceKHR::SRGB_NONLINEAR
{
return Ok(format.clone());
}
}
return Ok(available_formats[0].clone());
}
fn pick_presentation_mode(_available_modes: &Vec<vk::PresentModeKHR>)
-> Result<vk::PresentModeKHR>
{
// It's guaranteed to have this one.
return Ok(vk::PresentModeKHR::FIFO);
}
fn pick_image_extent(window: &Window,
capabilities: vk::SurfaceCapabilitiesKHR)
-> Result<vk::Extent2D>
{
if capabilities.current_extent.width != u32::MAX
&& capabilities.current_extent.height != u32::MAX
{
Ok(capabilities.current_extent)
} else {
let window_size = window.inner_size();
let width = window_size.width
.clamp(capabilities.min_image_extent.width,
capabilities.max_image_extent.width);
let height = window_size.height
.clamp(capabilities.min_image_extent.height,
capabilities.max_image_extent.height);
Ok(vk::Extent2D::builder().width(width).height(height).build())
}
}
#[allow(unsafe_code)]
fn load_spirv_shader_module(device: &Device, binary: &[u8])
-> Result<vk::ShaderModule>
{
let bytecode = Bytecode::new(binary)?;
let module_info = vk::ShaderModuleCreateInfo::builder()
.code(bytecode.code())
.code_size(bytecode.code_size());
let module = unsafe {
device.create_shader_module(&module_info, None)
}?;
Ok(module)
}
#[allow(unsafe_code)]
fn render(&mut self, window_id: WindowId) -> Result<()> {
if let Some(window) = self.window.borrow().as_ref()
&& window_id == window.id()
{
let device = self.device.borrow();
let device = device.as_ref().unwrap();
let graphics_queue = self.graphics_queue.borrow();
let graphics_queue = graphics_queue.as_ref().unwrap();
let presentation_queue = self.presentation_queue.borrow();
let presentation_queue = presentation_queue.as_ref().unwrap();
let mut window_dressing = self.window_dressing.borrow_mut();
let window_dressing = window_dressing.as_mut().unwrap();
let swapchain = &window_dressing.swapchain.swapchain;
let command_buffers = &window_dressing.command_buffers;
let frame_index = self.frame_index;
let concurrency = &mut window_dressing.concurrency;
let image_available_semaphore
= &concurrency.image_available_semaphores[frame_index];
let rendering_finished_semaphore
= &concurrency.rendering_finished_semaphores[frame_index];
let frame_fence = &concurrency.frame_fences[frame_index];
unsafe { device.wait_for_fences(&[*frame_fence], true, u64::MAX) }?;
let image_index = unsafe {
device.acquire_next_image_khr(*swapchain, u64::MAX,
*image_available_semaphore,
vk::Fence::null())
}?.0 as usize;
let image_fence = &concurrency.image_fences[image_index];
if !image_fence.is_null() {
unsafe { device.wait_for_fences(&[*image_fence], true, u64::MAX) }?;
}
concurrency.image_fences[image_index] = *frame_fence;
let first_semaphores = [*image_available_semaphore];
let second_semaphores = [*rendering_finished_semaphore];
let wait_stages = [vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT];
let command_buffers = [command_buffers[image_index]];
let submit_info = vk::SubmitInfo::builder()
.wait_semaphores(&first_semaphores)
.wait_dst_stage_mask(&wait_stages)
.command_buffers(&command_buffers)
.signal_semaphores(&second_semaphores);
unsafe { device.reset_fences(&[*frame_fence]) }?;
unsafe {
device.queue_submit(*graphics_queue,
&[submit_info],
*frame_fence)
}?;
let swapchains = [*swapchain];
let image_indices = [image_index as u32];
let present_info = vk::PresentInfoKHR::builder()
.wait_semaphores(&second_semaphores)
.swapchains(&swapchains)
.image_indices(&image_indices);
unsafe {
device.queue_present_khr(*presentation_queue, &present_info)
}?;
self.frame_index = (frame_index + 1) % N_SIMULTANEOUS_FRAMES;
}
Ok(())
}
}
impl Drop for Surreality {
#[allow(unsafe_code)]
fn drop(&mut self) {
if let Some(device) = self.device.replace(None) {
unsafe { device.device_wait_idle() }.unwrap();
if let Some(window_dressing) = self.window_dressing.replace(None) {
let concurrency = window_dressing.concurrency;
let swapchain = window_dressing.swapchain;
for semaphore in concurrency.image_available_semaphores {
unsafe { device.destroy_semaphore(semaphore, None) };
}
for semaphore in concurrency.rendering_finished_semaphores {
unsafe { device.destroy_semaphore(semaphore, None) };
}
for fence in concurrency.frame_fences {
unsafe { device.destroy_fence(fence, None) };
}
unsafe {
device.destroy_command_pool(window_dressing.command_pool, None)
};
for framebuffer in window_dressing.framebuffers {
unsafe { device.destroy_framebuffer(framebuffer, None) };
}
unsafe {
device.destroy_pipeline(window_dressing.pipeline, None)
};
unsafe {
device.destroy_render_pass(window_dressing.render_pass, None)
};
unsafe {
device.destroy_pipeline_layout(
window_dressing.pipeline_layout, None)
};
for view in swapchain.image_views {
unsafe { device.destroy_image_view(view, None) };
}
unsafe { device.destroy_swapchain_khr(swapchain.swapchain, None) };
}
unsafe { device.destroy_device(None) };
}
if let Some(instance) = self.instance.replace(None) {
if let Some(surface) = self.surface.replace(None) {
unsafe { instance.destroy_surface_khr(surface, None) };
}
// Everything but the instance itself should already be destroyed,
// before we destroy the debug messager. The special hook to get debug
// messages while destroying the instance itself only applies to the
// instance and the messager, so if we were to destroy anything we
// shouldn't after this point, we'd miss out on diagnostics.
if let Some(debug_messager) = self.debug_messager.replace(None) {
unsafe {
instance.destroy_debug_utils_messenger_ext(debug_messager, None);
}
}
unsafe { instance.destroy_instance(None) };
}
}
}
impl ApplicationHandler for Surreality {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
ignore_errors(move || {
self.init(event_loop)?;
Ok(())
});
}
fn window_event(&mut self, event_loop: &ActiveEventLoop,
window_id: WindowId, event: WindowEvent)
{
match event {
WindowEvent::RedrawRequested => {
if !event_loop.exiting() {
if let Err(e) = self.render(window_id) {
eprintln!("Error: {}", e);
}
}
}
WindowEvent::CloseRequested => {
event_loop.exit();
}
_ => { }
}
}
}
fn main() -> std::process::ExitCode {
let body: fn() -> Result<()> = || {
let event_loop = EventLoop::new()?;
let mut surreality = Surreality::new();
event_loop.run_app(&mut surreality)?;
Ok(())
};
match body() {
Ok(()) => std::process::ExitCode::SUCCESS,
Err(e) => {
eprintln!("Error: {}", e);
std::process::ExitCode::from(1)
}
}
}
#[allow(unsafe_code)]
extern "system" fn debug_messager_callback(
severity: vk::DebugUtilsMessageSeverityFlagsEXT,
flags: vk::DebugUtilsMessageTypeFlagsEXT,
data: *const vk::DebugUtilsMessengerCallbackDataEXT,
_context: *mut c_void) -> vk::Bool32
{
// Vulkan sends us everything, it's up to us to apply any filtering we
// want. The thing about this is that games need to be debuggable by end
// users, to diagnose compatibility issues and weird configurations, so we
// still want SOMETHING even when we're built in release mode.
//
// For now, we'll see if we can get away without providing runtime config
// stuff for diagnostics. We set the threshold pretty high in release mode,
// on the theory that our own diagnostics should be sufficient.
//
// Making this strategy work does rely on us actually checking error
// conditions and reporting them in useful ways, so that we only need
// Vulkan's messages for things we truly couldn't have anticipated. We do
// not take a more-is-better approach to diagnostics; the ideal would be to
// provide all the crucial information, and nothing else.
let threshold = if cfg!(feature = "vulkan-validation")
|| cfg!(debug_assertions)
{
vk::DebugUtilsMessageSeverityFlagsEXT::WARNING
} else {
vk::DebugUtilsMessageSeverityFlagsEXT::ERROR
};
if severity >= threshold {
let data = unsafe { *data };
let text = unsafe { CStr::from_ptr(data.message) }.to_string_lossy();
let label = if severity >= vk::DebugUtilsMessageSeverityFlagsEXT::ERROR {
"error"
} else if severity >= vk::DebugUtilsMessageSeverityFlagsEXT::WARNING {
"warning"
} else if severity >= vk::DebugUtilsMessageSeverityFlagsEXT::INFO {
"informational message"
} else {
"message of unknown, very minor significance"
};
eprintln!("Vulkan {}: {} (flags {:?})", label, text, flags);
}
// A return value of true would tell the validation layer we're unhappy
// with it, for the sake of conformance testing. We're not a conformance
// test so anything it does is fine with us.
vk::FALSE
}
|