gfx_backend_vulkan/
physical_device.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
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
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
use ash::{
    extensions::{khr::DrawIndirectCount, khr::Swapchain, nv::MeshShader},
    version::{DeviceV1_0, InstanceV1_0},
    vk,
};

#[cfg(unix)]
use ash::extensions::khr::ExternalMemoryFd;

use hal::{
    adapter,
    device::{CreationError, OutOfMemory},
    display, external_memory, format, image,
    pso::PatchSize,
    queue, DescriptorLimits, DownlevelProperties, DynamicStates, ExternalMemoryLimits, Features,
    Limits, PhysicalDeviceProperties,
};

use std::{ffi::CStr, fmt, mem, ptr, sync::Arc};

use crate::{
    conv, info, native, Backend, Device, DeviceExtensionFunctions, ExtensionFn, Queue, QueueFamily,
    RawDevice, RawInstance, Version,
};

/// Aggregate of the `vk::PhysicalDevice*Features` structs used by `gfx`.
#[derive(Debug, Default)]
pub struct PhysicalDeviceFeatures {
    core: vk::PhysicalDeviceFeatures,
    vulkan_1_2: Option<vk::PhysicalDeviceVulkan12Features>,
    descriptor_indexing: Option<vk::PhysicalDeviceDescriptorIndexingFeaturesEXT>,
    mesh_shader: Option<vk::PhysicalDeviceMeshShaderFeaturesNV>,
    imageless_framebuffer: Option<vk::PhysicalDeviceImagelessFramebufferFeaturesKHR>,
}

// This is safe because the structs have `p_next: *mut c_void`, which we null out/never read.
unsafe impl Send for PhysicalDeviceFeatures {}
unsafe impl Sync for PhysicalDeviceFeatures {}

impl PhysicalDeviceFeatures {
    /// Add the members of `self` into `info.enabled_features` and its `p_next` chain.
    fn add_to_device_create_builder<'a>(
        &'a mut self,
        mut info: vk::DeviceCreateInfoBuilder<'a>,
    ) -> vk::DeviceCreateInfoBuilder<'a> {
        info = info.enabled_features(&self.core);

        if let Some(ref mut feature) = self.vulkan_1_2 {
            info = info.push_next(feature);
        }
        if let Some(ref mut feature) = self.descriptor_indexing {
            info = info.push_next(feature);
        }
        if let Some(ref mut feature) = self.mesh_shader {
            info = info.push_next(feature);
        }
        if let Some(ref mut feature) = self.imageless_framebuffer {
            info = info.push_next(feature);
        }

        info
    }

    /// Create a `PhysicalDeviceFeatures` that will be used to create a logical device.
    ///
    /// `requested_features` should be the same as what was used to generate `enabled_extensions`.
    fn from_extensions_and_requested_features(
        api_version: Version,
        enabled_extensions: &[&'static CStr],
        requested_features: Features,
        supports_vulkan12_imageless_framebuffer: bool,
    ) -> PhysicalDeviceFeatures {
        // This must follow the "Valid Usage" requirements of [`VkDeviceCreateInfo`](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkDeviceCreateInfo.html).
        let features = requested_features;
        PhysicalDeviceFeatures {
            // vk::PhysicalDeviceFeatures is a struct composed of Bool32's while
            // Features is a bitfield so we need to map everything manually
            core: vk::PhysicalDeviceFeatures::builder()
                .robust_buffer_access(features.contains(Features::ROBUST_BUFFER_ACCESS))
                .full_draw_index_uint32(features.contains(Features::FULL_DRAW_INDEX_U32))
                .image_cube_array(features.contains(Features::IMAGE_CUBE_ARRAY))
                .independent_blend(features.contains(Features::INDEPENDENT_BLENDING))
                .geometry_shader(features.contains(Features::GEOMETRY_SHADER))
                .tessellation_shader(features.contains(Features::TESSELLATION_SHADER))
                .sample_rate_shading(features.contains(Features::SAMPLE_RATE_SHADING))
                .dual_src_blend(features.contains(Features::DUAL_SRC_BLENDING))
                .logic_op(features.contains(Features::LOGIC_OP))
                .multi_draw_indirect(features.contains(Features::MULTI_DRAW_INDIRECT))
                .draw_indirect_first_instance(
                    features.contains(Features::DRAW_INDIRECT_FIRST_INSTANCE),
                )
                .depth_clamp(features.contains(Features::DEPTH_CLAMP))
                .depth_bias_clamp(features.contains(Features::DEPTH_BIAS_CLAMP))
                .fill_mode_non_solid(features.contains(Features::NON_FILL_POLYGON_MODE))
                .depth_bounds(features.contains(Features::DEPTH_BOUNDS))
                .wide_lines(features.contains(Features::LINE_WIDTH))
                .large_points(features.contains(Features::POINT_SIZE))
                .alpha_to_one(features.contains(Features::ALPHA_TO_ONE))
                .multi_viewport(features.contains(Features::MULTI_VIEWPORTS))
                .sampler_anisotropy(features.contains(Features::SAMPLER_ANISOTROPY))
                .texture_compression_etc2(features.contains(Features::FORMAT_ETC2))
                .texture_compression_astc_ldr(features.contains(Features::FORMAT_ASTC_LDR))
                .texture_compression_bc(features.contains(Features::FORMAT_BC))
                .occlusion_query_precise(features.contains(Features::PRECISE_OCCLUSION_QUERY))
                .pipeline_statistics_query(features.contains(Features::PIPELINE_STATISTICS_QUERY))
                .vertex_pipeline_stores_and_atomics(
                    features.contains(Features::VERTEX_STORES_AND_ATOMICS),
                )
                .fragment_stores_and_atomics(
                    features.contains(Features::FRAGMENT_STORES_AND_ATOMICS),
                )
                .shader_tessellation_and_geometry_point_size(
                    features.contains(Features::SHADER_TESSELLATION_AND_GEOMETRY_POINT_SIZE),
                )
                .shader_image_gather_extended(
                    features.contains(Features::SHADER_IMAGE_GATHER_EXTENDED),
                )
                .shader_storage_image_extended_formats(
                    features.contains(Features::SHADER_STORAGE_IMAGE_EXTENDED_FORMATS),
                )
                .shader_storage_image_multisample(
                    features.contains(Features::SHADER_STORAGE_IMAGE_MULTISAMPLE),
                )
                .shader_storage_image_read_without_format(
                    features.contains(Features::SHADER_STORAGE_IMAGE_READ_WITHOUT_FORMAT),
                )
                .shader_storage_image_write_without_format(
                    features.contains(Features::SHADER_STORAGE_IMAGE_WRITE_WITHOUT_FORMAT),
                )
                .shader_uniform_buffer_array_dynamic_indexing(
                    features.contains(Features::SHADER_UNIFORM_BUFFER_ARRAY_DYNAMIC_INDEXING),
                )
                .shader_sampled_image_array_dynamic_indexing(
                    features.contains(Features::SHADER_SAMPLED_IMAGE_ARRAY_DYNAMIC_INDEXING),
                )
                .shader_storage_buffer_array_dynamic_indexing(
                    features.contains(Features::SHADER_STORAGE_BUFFER_ARRAY_DYNAMIC_INDEXING),
                )
                .shader_storage_image_array_dynamic_indexing(
                    features.contains(Features::SHADER_STORAGE_IMAGE_ARRAY_DYNAMIC_INDEXING),
                )
                .shader_clip_distance(features.contains(Features::SHADER_CLIP_DISTANCE))
                .shader_cull_distance(features.contains(Features::SHADER_CULL_DISTANCE))
                .shader_float64(features.contains(Features::SHADER_FLOAT64))
                .shader_int64(features.contains(Features::SHADER_INT64))
                .shader_int16(features.contains(Features::SHADER_INT16))
                .shader_resource_residency(features.contains(Features::SHADER_RESOURCE_RESIDENCY))
                .shader_resource_min_lod(features.contains(Features::SHADER_RESOURCE_MIN_LOD))
                .sparse_binding(features.contains(Features::SPARSE_BINDING))
                .sparse_residency_buffer(features.contains(Features::SPARSE_RESIDENCY_BUFFER))
                .sparse_residency_image2_d(features.contains(Features::SPARSE_RESIDENCY_IMAGE_2D))
                .sparse_residency_image3_d(features.contains(Features::SPARSE_RESIDENCY_IMAGE_3D))
                .sparse_residency2_samples(features.contains(Features::SPARSE_RESIDENCY_2_SAMPLES))
                .sparse_residency4_samples(features.contains(Features::SPARSE_RESIDENCY_4_SAMPLES))
                .sparse_residency8_samples(features.contains(Features::SPARSE_RESIDENCY_8_SAMPLES))
                .sparse_residency16_samples(
                    features.contains(Features::SPARSE_RESIDENCY_16_SAMPLES),
                )
                .sparse_residency_aliased(features.contains(Features::SPARSE_RESIDENCY_ALIASED))
                .variable_multisample_rate(features.contains(Features::VARIABLE_MULTISAMPLE_RATE))
                .inherited_queries(features.contains(Features::INHERITED_QUERIES))
                .build(),
            vulkan_1_2: if api_version >= Version::V1_2 {
                Some(
                    vk::PhysicalDeviceVulkan12Features::builder()
                        .sampler_mirror_clamp_to_edge(
                            features.contains(Features::SAMPLER_MIRROR_CLAMP_EDGE),
                        )
                        .draw_indirect_count(features.contains(Features::DRAW_INDIRECT_COUNT))
                        .descriptor_indexing(
                            features.intersects(Features::DESCRIPTOR_INDEXING_MASK),
                        )
                        .shader_sampled_image_array_non_uniform_indexing(
                            features.contains(Features::SAMPLED_TEXTURE_DESCRIPTOR_INDEXING),
                        )
                        .shader_storage_image_array_non_uniform_indexing(
                            features.contains(Features::STORAGE_TEXTURE_DESCRIPTOR_INDEXING),
                        )
                        .shader_storage_buffer_array_non_uniform_indexing(
                            features.contains(Features::STORAGE_BUFFER_DESCRIPTOR_INDEXING),
                        )
                        .shader_uniform_buffer_array_non_uniform_indexing(
                            features.contains(Features::UNIFORM_BUFFER_DESCRIPTOR_INDEXING),
                        )
                        .runtime_descriptor_array(
                            features.contains(Features::UNSIZED_DESCRIPTOR_ARRAY),
                        )
                        .sampler_filter_minmax(features.contains(Features::SAMPLER_REDUCTION))
                        .imageless_framebuffer(supports_vulkan12_imageless_framebuffer)
                        .build(),
                )
            } else {
                None
            },
            descriptor_indexing: if enabled_extensions
                .contains(&vk::ExtDescriptorIndexingFn::name())
            {
                Some(
                    vk::PhysicalDeviceDescriptorIndexingFeaturesEXT::builder()
                        .shader_sampled_image_array_non_uniform_indexing(
                            features.contains(Features::SAMPLED_TEXTURE_DESCRIPTOR_INDEXING),
                        )
                        .shader_storage_image_array_non_uniform_indexing(
                            features.contains(Features::STORAGE_TEXTURE_DESCRIPTOR_INDEXING),
                        )
                        .shader_storage_buffer_array_non_uniform_indexing(
                            features.contains(Features::STORAGE_BUFFER_DESCRIPTOR_INDEXING),
                        )
                        .shader_uniform_buffer_array_non_uniform_indexing(
                            features.contains(Features::UNIFORM_BUFFER_DESCRIPTOR_INDEXING),
                        )
                        .runtime_descriptor_array(
                            features.contains(Features::UNSIZED_DESCRIPTOR_ARRAY),
                        )
                        .build(),
                )
            } else {
                None
            },
            mesh_shader: if enabled_extensions.contains(&vk::NvMeshShaderFn::name()) {
                Some(
                    vk::PhysicalDeviceMeshShaderFeaturesNV::builder()
                        .task_shader(features.contains(Features::TASK_SHADER))
                        .mesh_shader(features.contains(Features::MESH_SHADER))
                        .build(),
                )
            } else {
                None
            },
            imageless_framebuffer: if enabled_extensions
                .contains(&vk::KhrImagelessFramebufferFn::name())
            {
                Some(
                    vk::PhysicalDeviceImagelessFramebufferFeaturesKHR::builder()
                        .imageless_framebuffer(true)
                        .build(),
                )
            } else {
                None
            },
        }
    }

    /// Get the `hal::Features` corresponding to the raw physical device's features and properties.
    fn to_hal_features(&self, info: &PhysicalDeviceInfo) -> Features {
        let mut bits = Features::empty()
            | Features::TRIANGLE_FAN
            | Features::SEPARATE_STENCIL_REF_VALUES
            | Features::SAMPLER_MIP_LOD_BIAS
            | Features::SAMPLER_BORDER_COLOR
            | Features::MUTABLE_COMPARISON_SAMPLER
            | Features::MUTABLE_UNNORMALIZED_SAMPLER
            | Features::TEXTURE_DESCRIPTOR_ARRAY
            | Features::BUFFER_DESCRIPTOR_ARRAY;

        if self.core.robust_buffer_access != 0 {
            bits |= Features::ROBUST_BUFFER_ACCESS;
        }
        if self.core.full_draw_index_uint32 != 0 {
            bits |= Features::FULL_DRAW_INDEX_U32;
        }
        if self.core.image_cube_array != 0 {
            bits |= Features::IMAGE_CUBE_ARRAY;
        }
        if self.core.independent_blend != 0 {
            bits |= Features::INDEPENDENT_BLENDING;
        }
        if self.core.geometry_shader != 0 {
            bits |= Features::GEOMETRY_SHADER;
        }
        if self.core.tessellation_shader != 0 {
            bits |= Features::TESSELLATION_SHADER;
        }
        if self.core.sample_rate_shading != 0 {
            bits |= Features::SAMPLE_RATE_SHADING;
        }
        if self.core.dual_src_blend != 0 {
            bits |= Features::DUAL_SRC_BLENDING;
        }
        if self.core.logic_op != 0 {
            bits |= Features::LOGIC_OP;
        }
        if self.core.multi_draw_indirect != 0 {
            bits |= Features::MULTI_DRAW_INDIRECT;
        }
        if self.core.draw_indirect_first_instance != 0 {
            bits |= Features::DRAW_INDIRECT_FIRST_INSTANCE;
        }
        if self.core.depth_clamp != 0 {
            bits |= Features::DEPTH_CLAMP;
        }
        if self.core.depth_bias_clamp != 0 {
            bits |= Features::DEPTH_BIAS_CLAMP;
        }
        if self.core.fill_mode_non_solid != 0 {
            bits |= Features::NON_FILL_POLYGON_MODE;
        }
        if self.core.depth_bounds != 0 {
            bits |= Features::DEPTH_BOUNDS;
        }
        if self.core.wide_lines != 0 {
            bits |= Features::LINE_WIDTH;
        }
        if self.core.large_points != 0 {
            bits |= Features::POINT_SIZE;
        }
        if self.core.alpha_to_one != 0 {
            bits |= Features::ALPHA_TO_ONE;
        }
        if self.core.multi_viewport != 0 {
            bits |= Features::MULTI_VIEWPORTS;
        }
        if self.core.sampler_anisotropy != 0 {
            bits |= Features::SAMPLER_ANISOTROPY;
        }
        if self.core.texture_compression_etc2 != 0 {
            bits |= Features::FORMAT_ETC2;
        }
        if self.core.texture_compression_astc_ldr != 0 {
            bits |= Features::FORMAT_ASTC_LDR;
        }
        if self.core.texture_compression_bc != 0 {
            bits |= Features::FORMAT_BC;
        }
        if self.core.occlusion_query_precise != 0 {
            bits |= Features::PRECISE_OCCLUSION_QUERY;
        }
        if self.core.pipeline_statistics_query != 0 {
            bits |= Features::PIPELINE_STATISTICS_QUERY;
        }
        if self.core.vertex_pipeline_stores_and_atomics != 0 {
            bits |= Features::VERTEX_STORES_AND_ATOMICS;
        }
        if self.core.fragment_stores_and_atomics != 0 {
            bits |= Features::FRAGMENT_STORES_AND_ATOMICS;
        }
        if self.core.shader_tessellation_and_geometry_point_size != 0 {
            bits |= Features::SHADER_TESSELLATION_AND_GEOMETRY_POINT_SIZE;
        }
        if self.core.shader_image_gather_extended != 0 {
            bits |= Features::SHADER_IMAGE_GATHER_EXTENDED;
        }
        if self.core.shader_storage_image_extended_formats != 0 {
            bits |= Features::SHADER_STORAGE_IMAGE_EXTENDED_FORMATS;
        }
        if self.core.shader_storage_image_multisample != 0 {
            bits |= Features::SHADER_STORAGE_IMAGE_MULTISAMPLE;
        }
        if self.core.shader_storage_image_read_without_format != 0 {
            bits |= Features::SHADER_STORAGE_IMAGE_READ_WITHOUT_FORMAT;
        }
        if self.core.shader_storage_image_write_without_format != 0 {
            bits |= Features::SHADER_STORAGE_IMAGE_WRITE_WITHOUT_FORMAT;
        }
        if self.core.shader_uniform_buffer_array_dynamic_indexing != 0 {
            bits |= Features::SHADER_UNIFORM_BUFFER_ARRAY_DYNAMIC_INDEXING;
        }
        if self.core.shader_sampled_image_array_dynamic_indexing != 0 {
            bits |= Features::SHADER_SAMPLED_IMAGE_ARRAY_DYNAMIC_INDEXING;
        }
        if self.core.shader_storage_buffer_array_dynamic_indexing != 0 {
            bits |= Features::SHADER_STORAGE_BUFFER_ARRAY_DYNAMIC_INDEXING;
        }
        if self.core.shader_storage_image_array_dynamic_indexing != 0 {
            bits |= Features::SHADER_STORAGE_IMAGE_ARRAY_DYNAMIC_INDEXING;
        }
        if self.core.shader_clip_distance != 0 {
            bits |= Features::SHADER_CLIP_DISTANCE;
        }
        if self.core.shader_cull_distance != 0 {
            bits |= Features::SHADER_CULL_DISTANCE;
        }
        if self.core.shader_float64 != 0 {
            bits |= Features::SHADER_FLOAT64;
        }
        if self.core.shader_int64 != 0 {
            bits |= Features::SHADER_INT64;
        }
        if self.core.shader_int16 != 0 {
            bits |= Features::SHADER_INT16;
        }
        if self.core.shader_resource_residency != 0 {
            bits |= Features::SHADER_RESOURCE_RESIDENCY;
        }
        if self.core.shader_resource_min_lod != 0 {
            bits |= Features::SHADER_RESOURCE_MIN_LOD;
        }
        if self.core.sparse_binding != 0 {
            bits |= Features::SPARSE_BINDING;
        }
        if self.core.sparse_residency_buffer != 0 {
            bits |= Features::SPARSE_RESIDENCY_BUFFER;
        }
        if self.core.sparse_residency_image2_d != 0 {
            bits |= Features::SPARSE_RESIDENCY_IMAGE_2D;
        }
        if self.core.sparse_residency_image3_d != 0 {
            bits |= Features::SPARSE_RESIDENCY_IMAGE_3D;
        }
        if self.core.sparse_residency2_samples != 0 {
            bits |= Features::SPARSE_RESIDENCY_2_SAMPLES;
        }
        if self.core.sparse_residency4_samples != 0 {
            bits |= Features::SPARSE_RESIDENCY_4_SAMPLES;
        }
        if self.core.sparse_residency8_samples != 0 {
            bits |= Features::SPARSE_RESIDENCY_8_SAMPLES;
        }
        if self.core.sparse_residency16_samples != 0 {
            bits |= Features::SPARSE_RESIDENCY_16_SAMPLES;
        }
        if self.core.sparse_residency_aliased != 0 {
            bits |= Features::SPARSE_RESIDENCY_ALIASED;
        }
        if self.core.variable_multisample_rate != 0 {
            bits |= Features::VARIABLE_MULTISAMPLE_RATE;
        }
        if self.core.inherited_queries != 0 {
            bits |= Features::INHERITED_QUERIES;
        }

        if info.supports_extension(vk::AmdNegativeViewportHeightFn::name())
            || info.supports_extension(vk::KhrMaintenance1Fn::name())
            || info.api_version() >= Version::V1_1
        {
            bits |= Features::NDC_Y_UP;
        }

        if info.supports_extension(vk::KhrSamplerMirrorClampToEdgeFn::name()) {
            bits |= Features::SAMPLER_MIRROR_CLAMP_EDGE;
        }

        if info.supports_extension(vk::ExtSamplerFilterMinmaxFn::name()) {
            bits |= Features::SAMPLER_REDUCTION;
        }

        if info.supports_extension(DrawIndirectCount::name()) {
            bits |= Features::DRAW_INDIRECT_COUNT
        }

        if info.supports_extension(vk::ExtConservativeRasterizationFn::name()) {
            bits |= Features::CONSERVATIVE_RASTERIZATION
        }

        if info.api_version() >= Version::V1_1
            || (info.supports_extension(vk::KhrGetPhysicalDeviceProperties2Fn::name())
                && info.supports_extension(vk::KhrExternalMemoryFn::name()))
        {
            bits |= Features::EXTERNAL_MEMORY
        }

        if let Some(ref vulkan_1_2) = self.vulkan_1_2 {
            if vulkan_1_2.shader_sampled_image_array_non_uniform_indexing != 0 {
                bits |= Features::SAMPLED_TEXTURE_DESCRIPTOR_INDEXING;
            }
            if vulkan_1_2.shader_storage_image_array_non_uniform_indexing != 0 {
                bits |= Features::STORAGE_TEXTURE_DESCRIPTOR_INDEXING;
            }
            if vulkan_1_2.shader_storage_buffer_array_non_uniform_indexing != 0 {
                bits |= Features::STORAGE_BUFFER_DESCRIPTOR_INDEXING;
            }
            if vulkan_1_2.shader_uniform_buffer_array_non_uniform_indexing != 0 {
                bits |= Features::UNIFORM_BUFFER_DESCRIPTOR_INDEXING;
            }
            if vulkan_1_2.runtime_descriptor_array != 0 {
                bits |= Features::UNSIZED_DESCRIPTOR_ARRAY;
            }
            if vulkan_1_2.sampler_mirror_clamp_to_edge != 0 {
                bits |= Features::SAMPLER_MIRROR_CLAMP_EDGE;
            }
            if vulkan_1_2.sampler_filter_minmax != 0 {
                bits |= Features::SAMPLER_REDUCTION
            }
            if vulkan_1_2.draw_indirect_count != 0 {
                bits |= Features::DRAW_INDIRECT_COUNT
            }
        }

        if let Some(ref descriptor_indexing) = self.descriptor_indexing {
            if descriptor_indexing.shader_sampled_image_array_non_uniform_indexing != 0 {
                bits |= Features::SAMPLED_TEXTURE_DESCRIPTOR_INDEXING;
            }
            if descriptor_indexing.shader_storage_image_array_non_uniform_indexing != 0 {
                bits |= Features::STORAGE_TEXTURE_DESCRIPTOR_INDEXING;
            }
            if descriptor_indexing.shader_storage_buffer_array_non_uniform_indexing != 0 {
                bits |= Features::STORAGE_BUFFER_DESCRIPTOR_INDEXING;
            }
            if descriptor_indexing.shader_uniform_buffer_array_non_uniform_indexing != 0 {
                bits |= Features::UNIFORM_BUFFER_DESCRIPTOR_INDEXING;
            }
            if descriptor_indexing.runtime_descriptor_array != 0 {
                bits |= Features::UNSIZED_DESCRIPTOR_ARRAY;
            }
        }

        if let Some(ref mesh_shader) = self.mesh_shader {
            if mesh_shader.task_shader != 0 {
                bits |= Features::TASK_SHADER;
            }
            if mesh_shader.mesh_shader != 0 {
                bits |= Features::MESH_SHADER;
            }
        }

        bits
    }
}

/// Information gathered about a physical device. Used to
pub struct PhysicalDeviceInfo {
    supported_extensions: Vec<vk::ExtensionProperties>,
    properties: vk::PhysicalDeviceProperties,
}

impl PhysicalDeviceInfo {
    fn api_version(&self) -> Version {
        self.properties.api_version.into()
    }

    fn supports_extension(&self, extension: &CStr) -> bool {
        self.supported_extensions
            .iter()
            .any(|ep| unsafe { CStr::from_ptr(ep.extension_name.as_ptr()) } == extension)
    }

    /// Map `requested_features` to the list of Vulkan extension strings required to create the logical device.
    fn get_required_extensions(&self, requested_features: Features) -> Vec<&'static CStr> {
        let mut requested_extensions = Vec::new();

        requested_extensions.push(Swapchain::name());

        if self.api_version() < Version::V1_1 {
            requested_extensions.push(vk::KhrMaintenance1Fn::name());
            requested_extensions.push(vk::KhrMaintenance2Fn::name());
        }

        if requested_features.contains(Features::NDC_Y_UP) {
            // `VK_AMD_negative_viewport_height` is obsoleted by `VK_KHR_maintenance1` and must not be enabled alongside `VK_KHR_maintenance1` or a 1.1+ device.
            if self.api_version() < Version::V1_1
                && !self.supports_extension(vk::KhrMaintenance1Fn::name())
            {
                requested_extensions.push(vk::AmdNegativeViewportHeightFn::name());
            }
        }

        if self.api_version() < Version::V1_2
            && self.supports_extension(vk::KhrImagelessFramebufferFn::name())
        {
            requested_extensions.push(vk::KhrImagelessFramebufferFn::name());
            requested_extensions.push(vk::KhrImageFormatListFn::name()); // Required for `KhrImagelessFramebufferFn`
        }

        if self.api_version() < Version::V1_2 {
            requested_extensions.push(vk::ExtSamplerFilterMinmaxFn::name());
        }

        if self.api_version() < Version::V1_2
            && requested_features.intersects(Features::DESCRIPTOR_INDEXING_MASK)
        {
            requested_extensions.push(vk::ExtDescriptorIndexingFn::name());

            if self.api_version() < Version::V1_1 {
                requested_extensions.push(vk::KhrMaintenance3Fn::name());
            }
        }

        if self.api_version() < Version::V1_2
            && requested_features.intersects(Features::SAMPLER_MIRROR_CLAMP_EDGE)
        {
            requested_extensions.push(vk::KhrSamplerMirrorClampToEdgeFn::name());
        }

        if self.api_version() < Version::V1_2
            && requested_features.contains(Features::SAMPLER_REDUCTION)
        {
            requested_extensions.push(vk::ExtSamplerFilterMinmaxFn::name());
        }

        if requested_features.intersects(Features::MESH_SHADER_MASK) {
            requested_extensions.push(MeshShader::name());
        }

        if self.api_version() < Version::V1_2
            && requested_features.contains(Features::DRAW_INDIRECT_COUNT)
        {
            requested_extensions.push(DrawIndirectCount::name());
        }

        if requested_features.contains(Features::CONSERVATIVE_RASTERIZATION) {
            requested_extensions.push(vk::ExtConservativeRasterizationFn::name());
            requested_extensions.push(vk::KhrGetDisplayProperties2Fn::name()); // TODO NOT NEEDED, RIGHT?
        }

        if self.supports_extension(vk::ExtDisplayControlFn::name()) {
            requested_extensions.push(vk::ExtDisplayControlFn::name());
        }

        if requested_features.contains(Features::EXTERNAL_MEMORY) {
            if self.api_version() < Version::V1_1 {
                requested_extensions.push(vk::KhrGetPhysicalDeviceProperties2Fn::name());
                requested_extensions.push(vk::KhrExternalMemoryFn::name());

                // External memory interact with DedicatedAllocation extension, but it is not a strict dependency.
                requested_extensions.push(vk::KhrGetMemoryRequirements2Fn::name()); // TODO Functions should be added because they are useful
                requested_extensions.push(vk::KhrDedicatedAllocationFn::name());
            }

            requested_extensions.push(vk::ExtExternalMemoryHostFn::name());
            #[cfg(window)]
            requested_extensions.push(vk::KhrExternalMemoryWin32Fn::name());
            #[cfg(unix)]
            {
                requested_extensions.push(vk::KhrExternalMemoryFdFn::name());
                requested_extensions.push(vk::ExtExternalMemoryDmaBufFn::name());

                requested_extensions.push(vk::KhrBindMemory2Fn::name());

                requested_extensions.push(vk::KhrImageFormatListFn::name());
                requested_extensions.push(vk::KhrSamplerYcbcrConversionFn::name());
                requested_extensions.push(vk::ExtImageDrmFormatModifierFn::name());
            }
        }
        requested_extensions
    }

    fn load(
        instance: &Arc<RawInstance>,
        device: vk::PhysicalDevice,
    ) -> (Self, PhysicalDeviceFeatures) {
        let device_properties = unsafe {
            PhysicalDeviceInfo {
                supported_extensions: instance
                    .inner
                    .enumerate_device_extension_properties(device)
                    .unwrap(),
                properties: instance.inner.get_physical_device_properties(device),
            }
        };

        let mut features = PhysicalDeviceFeatures::default();
        features.core = if let Some(ref get_device_properties) =
            instance.get_physical_device_properties
        {
            let core = vk::PhysicalDeviceFeatures::builder().build();
            let mut features2 = vk::PhysicalDeviceFeatures2KHR::builder()
                .features(core)
                .build();

            if device_properties.api_version() >= Version::V1_2 {
                features.vulkan_1_2 = Some(vk::PhysicalDeviceVulkan12Features::builder().build());

                let mut_ref = features.vulkan_1_2.as_mut().unwrap();
                mut_ref.p_next = mem::replace(&mut features2.p_next, mut_ref as *mut _ as *mut _);
            }

            if device_properties.supports_extension(vk::ExtDescriptorIndexingFn::name()) {
                features.descriptor_indexing =
                    Some(vk::PhysicalDeviceDescriptorIndexingFeaturesEXT::builder().build());

                let mut_ref = features.descriptor_indexing.as_mut().unwrap();
                mut_ref.p_next = mem::replace(&mut features2.p_next, mut_ref as *mut _ as *mut _);
            }

            if device_properties.supports_extension(MeshShader::name()) {
                features.mesh_shader =
                    Some(vk::PhysicalDeviceMeshShaderFeaturesNV::builder().build());

                let mut_ref = features.mesh_shader.as_mut().unwrap();
                mut_ref.p_next = mem::replace(&mut features2.p_next, mut_ref as *mut _ as *mut _);
            }

            // `VK_KHR_imageless_framebuffer` is promoted to 1.2, but has no changes, so we can keep using the extension unconditionally.
            if device_properties.supports_extension(vk::KhrImagelessFramebufferFn::name()) {
                features.imageless_framebuffer =
                    Some(vk::PhysicalDeviceImagelessFramebufferFeaturesKHR::builder().build());

                let mut_ref = features.imageless_framebuffer.as_mut().unwrap();
                mut_ref.p_next = mem::replace(&mut features2.p_next, mut_ref as *mut _ as *mut _);
            }

            match get_device_properties {
                ExtensionFn::Promoted => {
                    use ash::version::InstanceV1_1;
                    unsafe {
                        instance
                            .inner
                            .get_physical_device_features2(device, &mut features2);
                    }
                }
                ExtensionFn::Extension(get_device_properties) => unsafe {
                    get_device_properties
                        .get_physical_device_features2_khr(device, &mut features2 as *mut _);
                },
            }

            features2.features
        } else {
            unsafe { instance.inner.get_physical_device_features(device) }
        };

        /// # Safety
        /// `T` must be a struct bigger than `vk::BaseOutStructure`.
        unsafe fn null_p_next<T>(features: &mut Option<T>) {
            if let Some(features) = features {
                // This is technically invalid since `vk::BaseOutStructure` and `T` will probably never have the same size.
                mem::transmute::<_, &mut vk::BaseOutStructure>(features).p_next = ptr::null_mut();
            }
        }

        unsafe {
            null_p_next(&mut features.vulkan_1_2);
            null_p_next(&mut features.descriptor_indexing);
            null_p_next(&mut features.mesh_shader);
            null_p_next(&mut features.imageless_framebuffer);
        }

        (device_properties, features)
    }
}

pub struct PhysicalDevice {
    instance: Arc<RawInstance>,
    pub handle: vk::PhysicalDevice,
    known_memory_flags: vk::MemoryPropertyFlags,
    device_info: PhysicalDeviceInfo,
    device_features: PhysicalDeviceFeatures,
    available_features: Features,
}

impl PhysicalDevice {
    /// # Safety
    /// `raw_device` must be created from `self` (or from the inner raw handle)
    /// `raw_device` must be created with `requested_features`
    pub unsafe fn gpu_from_raw(
        &self,
        raw_device: ash::Device,
        families: &[(&QueueFamily, &[queue::QueuePriority])],
        requested_features: Features,
    ) -> Result<adapter::Gpu<Backend>, CreationError> {
        let enabled_extensions = self.enabled_extensions(requested_features)?;
        Ok(self.inner_create_gpu(
            raw_device,
            true,
            families,
            requested_features,
            enabled_extensions,
        ))
    }

    unsafe fn inner_create_gpu(
        &self,
        device_raw: ash::Device,
        handle_is_external: bool,
        families: &[(&QueueFamily, &[queue::QueuePriority])],
        requested_features: Features,
        enabled_extensions: Vec<&CStr>,
    ) -> adapter::Gpu<Backend> {
        let valid_ash_memory_types = {
            let mem_properties = self
                .instance
                .inner
                .get_physical_device_memory_properties(self.handle);
            mem_properties.memory_types[..mem_properties.memory_type_count as usize]
                .iter()
                .enumerate()
                .fold(0, |u, (i, mem)| {
                    if self.known_memory_flags.contains(mem.property_flags) {
                        u | (1 << i)
                    } else {
                        u
                    }
                })
        };

        let supports_vulkan12_imageless_framebuffer = self
            .device_features
            .vulkan_1_2
            .map_or(false, |features| features.imageless_framebuffer == vk::TRUE);

        let swapchain_fn = Swapchain::new(&self.instance.inner, &device_raw);

        let mesh_fn = if enabled_extensions.contains(&MeshShader::name()) {
            Some(ExtensionFn::Extension(MeshShader::new(
                &self.instance.inner,
                &device_raw,
            )))
        } else {
            None
        };

        let indirect_count_fn = if enabled_extensions.contains(&DrawIndirectCount::name()) {
            Some(ExtensionFn::Extension(DrawIndirectCount::new(
                &self.instance.inner,
                &device_raw,
            )))
        } else if self.device_info.api_version() >= Version::V1_2 {
            Some(ExtensionFn::Promoted)
        } else {
            None
        };

        let display_control = if enabled_extensions.contains(&vk::ExtDisplayControlFn::name()) {
            Some(vk::ExtDisplayControlFn::load(|name| {
                std::mem::transmute(
                    self.instance
                        .inner
                        .get_device_proc_addr(device_raw.handle(), name.as_ptr()),
                )
            }))
        } else {
            None
        };

        let memory_requirements2 =
            if enabled_extensions.contains(&vk::KhrGetMemoryRequirements2Fn::name()) {
                Some(ExtensionFn::Extension(
                    vk::KhrGetMemoryRequirements2Fn::load(|name| {
                        std::mem::transmute(
                            self.instance
                                .inner
                                .get_device_proc_addr(device_raw.handle(), name.as_ptr()),
                        )
                    }),
                ))
            } else {
                None
            };

        let dedicated_allocation;
        let external_memory;
        let external_memory_host;

        #[cfg(unix)]
        let external_memory_fd;

        #[cfg(any(target_os = "linux", target_os = "android"))]
        let external_memory_dma_buf;

        #[cfg(any(target_os = "linux", target_os = "android"))]
        let image_drm_format_modifier;

        #[cfg(windows)]
        let external_memory_win32;

        if requested_features.contains(Features::EXTERNAL_MEMORY) {
            if self.device_info.api_version() < Version::V1_1 {
                external_memory = if enabled_extensions.contains(&vk::KhrExternalMemoryFn::name()) {
                    Some(ExtensionFn::Extension(()))
                } else {
                    None
                };

                // External memory interact with DedicatedAllocation extension, but it is not a strict dependency.
                dedicated_allocation =
                    if enabled_extensions.contains(&vk::KhrDedicatedAllocationFn::name()) {
                        Some(ExtensionFn::Extension(()))
                    } else {
                        None
                    };
            } else {
                external_memory = Some(ExtensionFn::Promoted);
                dedicated_allocation = Some(ExtensionFn::Promoted);
            }

            external_memory_host =
                if enabled_extensions.contains(&vk::ExtExternalMemoryHostFn::name()) {
                    Some(vk::ExtExternalMemoryHostFn::load(|name| {
                        std::mem::transmute(
                            self.instance
                                .inner
                                .get_device_proc_addr(device_raw.handle(), name.as_ptr()),
                        )
                    }))
                } else {
                    None
                };

            #[cfg(windows)]
            {
                external_memory_win32 =
                    if enabled_extensions.contains(&vk::KhrExternalMemoryWin32Fn::name()) {
                        Some(vk::KhrExternalMemoryWin32Fn::load(|name| {
                            std::mem::transmute(
                                self.instance
                                    .inner
                                    .get_device_proc_addr(device_raw.handle(), name.as_ptr()),
                            )
                        }))
                    } else {
                        None
                    };
            }
            #[cfg(unix)]
            {
                external_memory_fd = if enabled_extensions.contains(&ExternalMemoryFd::name()) {
                    Some(ExternalMemoryFd::new(&self.instance.inner, &device_raw))
                } else {
                    None
                };

                #[cfg(any(target_os = "linux", target_os = "android"))]
                {
                    external_memory_dma_buf =
                        if enabled_extensions.contains(&vk::ExtExternalMemoryDmaBufFn::name()) {
                            Some(())
                        } else {
                            None
                        };

                    image_drm_format_modifier =
                        if enabled_extensions.contains(&vk::ExtImageDrmFormatModifierFn::name()) {
                            Some(vk::ExtImageDrmFormatModifierFn::load(|name| {
                                std::mem::transmute(
                                    self.instance
                                        .inner
                                        .get_device_proc_addr(device_raw.handle(), name.as_ptr()),
                                )
                            }))
                        } else {
                            None
                        };
                }
            }
        } else {
            dedicated_allocation = None;
            external_memory = None;
            external_memory_host = None;

            #[cfg(unix)]
            {
                external_memory_fd = None;
            }

            #[cfg(any(target_os = "linux", target_os = "android"))]
            {
                external_memory_dma_buf = None;
                image_drm_format_modifier = None;
            }

            #[cfg(windows)]
            {
                external_memory_win32 = None;
            }
        }

        #[cfg(feature = "naga")]
        let naga_options = {
            use naga::back::spv;
            let capabilities = [
                spv::Capability::Shader,
                spv::Capability::Matrix,
                spv::Capability::InputAttachment,
                spv::Capability::Sampled1D,
                spv::Capability::Image1D,
                spv::Capability::SampledBuffer,
                spv::Capability::ImageBuffer,
                spv::Capability::ImageQuery,
                spv::Capability::DerivativeControl,
                //TODO: fill out the rest
            ];
            let mut flags = spv::WriterFlags::empty();
            flags.set(spv::WriterFlags::DEBUG, cfg!(debug_assertions));
            flags.set(
                spv::WriterFlags::ADJUST_COORDINATE_SPACE,
                !requested_features.contains(hal::Features::NDC_Y_UP),
            );
            spv::Options {
                lang_version: (1, 0),
                flags,
                capabilities: Some(capabilities.iter().cloned().collect()),
            }
        };

        let device = Device {
            shared: Arc::new(RawDevice {
                raw: device_raw,
                handle_is_external,
                features: requested_features,
                instance: Arc::clone(&self.instance),
                extension_fns: DeviceExtensionFunctions {
                    mesh_shaders: mesh_fn,
                    draw_indirect_count: indirect_count_fn,
                    display_control,
                    memory_requirements2: memory_requirements2,
                    dedicated_allocation: dedicated_allocation,
                    external_memory,
                    external_memory_host,
                    #[cfg(unix)]
                    external_memory_fd,
                    #[cfg(windows)]
                    external_memory_win32,
                    #[cfg(any(target_os = "linux", target_os = "android"))]
                    external_memory_dma_buf,
                    #[cfg(any(target_os = "linux", target_os = "android"))]
                    image_drm_format_modifier,
                },
                flip_y_requires_shift: self.device_info.api_version() >= Version::V1_1
                    || self
                        .device_info
                        .supports_extension(vk::KhrMaintenance1Fn::name()),
                imageless_framebuffers: supports_vulkan12_imageless_framebuffer
                    || self
                        .device_info
                        .supports_extension(vk::KhrImagelessFramebufferFn::name()),
                image_view_usage: self.device_info.api_version() >= Version::V1_1
                    || self
                        .device_info
                        .supports_extension(vk::KhrMaintenance2Fn::name()),
                timestamp_period: self.device_info.properties.limits.timestamp_period,
            }),
            vendor_id: self.device_info.properties.vendor_id,
            valid_ash_memory_types,
            render_doc: Default::default(),
            #[cfg(feature = "naga")]
            naga_options,
        };

        let device_arc = Arc::clone(&device.shared);
        let queue_groups = families
            .iter()
            .map(|&(family, ref priorities)| {
                let mut family_raw =
                    queue::QueueGroup::new(queue::QueueFamilyId(family.index as usize));
                for id in 0..priorities.len() {
                    let queue_raw = device_arc.raw.get_device_queue(family.index, id as _);
                    family_raw.add_queue(Queue {
                        raw: Arc::new(queue_raw),
                        device: device_arc.clone(),
                        swapchain_fn: swapchain_fn.clone(),
                    });
                }
                family_raw
            })
            .collect();

        adapter::Gpu {
            device,
            queue_groups,
        }
    }

    pub fn enabled_extensions(
        &self,
        requested_features: Features,
    ) -> Result<Vec<&'static CStr>, CreationError> {
        use adapter::PhysicalDevice;

        if !self.features().contains(requested_features) {
            return Err(CreationError::MissingFeature);
        }

        let (supported_extensions, unsupported_extensions) = self
            .device_info
            .get_required_extensions(requested_features)
            .iter()
            .partition::<Vec<&CStr>, _>(|&&extension| {
                self.device_info.supports_extension(extension)
            });

        if !unsupported_extensions.is_empty() {
            warn!("Missing extensions: {:?}", unsupported_extensions);
        }

        debug!("Supported extensions: {:?}", supported_extensions);

        Ok(supported_extensions)
    }
}

pub(crate) fn load_adapter(
    instance: &Arc<RawInstance>,
    device: vk::PhysicalDevice,
) -> adapter::Adapter<Backend> {
    let (device_info, device_features) = PhysicalDeviceInfo::load(instance, device);

    let info = adapter::AdapterInfo {
        name: unsafe {
            CStr::from_ptr(device_info.properties.device_name.as_ptr())
                .to_str()
                .unwrap_or("Unknown")
                .to_owned()
        },
        vendor: device_info.properties.vendor_id as usize,
        device: device_info.properties.device_id as usize,
        device_type: match device_info.properties.device_type {
            ash::vk::PhysicalDeviceType::OTHER => adapter::DeviceType::Other,
            ash::vk::PhysicalDeviceType::INTEGRATED_GPU => adapter::DeviceType::IntegratedGpu,
            ash::vk::PhysicalDeviceType::DISCRETE_GPU => adapter::DeviceType::DiscreteGpu,
            ash::vk::PhysicalDeviceType::VIRTUAL_GPU => adapter::DeviceType::VirtualGpu,
            ash::vk::PhysicalDeviceType::CPU => adapter::DeviceType::Cpu,
            _ => adapter::DeviceType::Other,
        },
    };

    let available_features = {
        let mut bits = device_features.to_hal_features(&device_info);

        // see https://github.com/gfx-rs/gfx/issues/1930
        let is_windows_intel_dual_src_bug = cfg!(windows)
            && device_info.properties.vendor_id == info::intel::VENDOR
            && (device_info.properties.device_id & info::intel::DEVICE_KABY_LAKE_MASK
                == info::intel::DEVICE_KABY_LAKE_MASK
                || device_info.properties.device_id & info::intel::DEVICE_SKY_LAKE_MASK
                    == info::intel::DEVICE_SKY_LAKE_MASK);
        if is_windows_intel_dual_src_bug {
            bits.set(Features::DUAL_SRC_BLENDING, false);
        }

        bits
    };

    let physical_device = PhysicalDevice {
        instance: instance.clone(),
        handle: device,
        known_memory_flags: vk::MemoryPropertyFlags::DEVICE_LOCAL
            | vk::MemoryPropertyFlags::HOST_VISIBLE
            | vk::MemoryPropertyFlags::HOST_COHERENT
            | vk::MemoryPropertyFlags::HOST_CACHED
            | vk::MemoryPropertyFlags::LAZILY_ALLOCATED,
        device_info,
        device_features,
        available_features,
    };

    let queue_families = unsafe {
        instance
            .inner
            .get_physical_device_queue_family_properties(device)
            .into_iter()
            .enumerate()
            .map(|(i, properties)| QueueFamily {
                properties,
                device,
                index: i as u32,
            })
            .collect()
    };

    adapter::Adapter {
        info,
        physical_device,
        queue_families,
    }
}

impl fmt::Debug for PhysicalDevice {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("PhysicalDevice").finish()
    }
}

impl adapter::PhysicalDevice<Backend> for PhysicalDevice {
    unsafe fn open(
        &self,
        families: &[(&QueueFamily, &[queue::QueuePriority])],
        requested_features: Features,
    ) -> Result<adapter::Gpu<Backend>, CreationError> {
        let family_infos = families
            .iter()
            .map(|&(family, priorities)| {
                vk::DeviceQueueCreateInfo::builder()
                    .flags(vk::DeviceQueueCreateFlags::empty())
                    .queue_family_index(family.index)
                    .queue_priorities(priorities)
                    .build()
            })
            .collect::<Vec<_>>();

        let enabled_extensions = self.enabled_extensions(requested_features)?;

        let supports_vulkan12_imageless_framebuffer = self
            .device_features
            .vulkan_1_2
            .map_or(false, |features| features.imageless_framebuffer == vk::TRUE);

        // Create device
        let device_raw = {
            let str_pointers = enabled_extensions
                .iter()
                .map(|&s| {
                    // Safe because `enabled_extensions` entries have static lifetime.
                    s.as_ptr()
                })
                .collect::<Vec<_>>();

            let mut enabled_features =
                PhysicalDeviceFeatures::from_extensions_and_requested_features(
                    self.device_info.api_version(),
                    &enabled_extensions,
                    requested_features,
                    supports_vulkan12_imageless_framebuffer,
                );
            let info = vk::DeviceCreateInfo::builder()
                .queue_create_infos(&family_infos)
                .enabled_extension_names(&str_pointers);
            let info = enabled_features.add_to_device_create_builder(info);

            match self.instance.inner.create_device(self.handle, &info, None) {
                Ok(device) => device,
                Err(e) => {
                    return Err(match e {
                        vk::Result::ERROR_OUT_OF_HOST_MEMORY => {
                            CreationError::OutOfMemory(OutOfMemory::Host)
                        }
                        vk::Result::ERROR_OUT_OF_DEVICE_MEMORY => {
                            CreationError::OutOfMemory(OutOfMemory::Device)
                        }
                        vk::Result::ERROR_INITIALIZATION_FAILED => {
                            CreationError::InitializationFailed
                        }
                        vk::Result::ERROR_DEVICE_LOST => CreationError::DeviceLost,
                        vk::Result::ERROR_TOO_MANY_OBJECTS => CreationError::TooManyObjects,
                        _ => {
                            error!("Unknown device creation error: {:?}", e);
                            CreationError::InitializationFailed
                        }
                    })
                }
            }
        };

        Ok(self.inner_create_gpu(
            device_raw,
            false,
            families,
            requested_features,
            enabled_extensions,
        ))
    }

    fn format_properties(&self, format: Option<format::Format>) -> format::Properties {
        let supports_transfer_bits = self
            .device_info
            .supports_extension(vk::KhrMaintenance1Fn::name());

        let supports_sampler_filter_minmax = self
            .available_features
            .contains(Features::SAMPLER_REDUCTION);

        let (properties, drm_format_properties) = unsafe {
            match self.instance.get_physical_device_properties {
                None => {
                    let format_properties =
                        self.instance.inner.get_physical_device_format_properties(
                            self.handle,
                            format.map_or(vk::Format::UNDEFINED, conv::map_format),
                        );
                    (format_properties, Vec::new())
                }
                Some(ref extension) => {
                    let mut raw_format_modifiers: Vec<vk::DrmFormatModifierPropertiesEXT> = Vec::new();
                    let mut drm_format_properties =
                        vk::DrmFormatModifierPropertiesListEXT::builder().build();
                    let mut format_properties2 = vk::FormatProperties2::builder()
                        .push_next(&mut drm_format_properties)
                        .build();
                    // Ash does not implement the "double call" behaviour for this function, so it is implemented here.
                    match extension {
                        ExtensionFn::Promoted => {
                            use ash::version::InstanceV1_1;
                            self.instance.inner.get_physical_device_format_properties2(
                                self.handle,
                                format.map_or(vk::Format::UNDEFINED, conv::map_format),
                                &mut format_properties2,
                            );
                            raw_format_modifiers.reserve_exact(drm_format_properties.drm_format_modifier_count as usize);
                            drm_format_properties.p_drm_format_modifier_properties = raw_format_modifiers.as_mut_ptr();
                            self.instance.inner.get_physical_device_format_properties2(
                                self.handle,
                                format.map_or(vk::Format::UNDEFINED, conv::map_format),
                                &mut format_properties2,
                            );
                            raw_format_modifiers.set_len(drm_format_properties.drm_format_modifier_count as usize);
                        }
                        ExtensionFn::Extension(extension) => {
                            extension.get_physical_device_format_properties2_khr(
                                self.handle,
                                format.map_or(vk::Format::UNDEFINED, conv::map_format),
                                &mut format_properties2,
                            );
                            raw_format_modifiers.reserve_exact(drm_format_properties.drm_format_modifier_count as usize);
                            drm_format_properties.p_drm_format_modifier_properties = raw_format_modifiers.as_mut_ptr();
                            extension.get_physical_device_format_properties2_khr(
                                self.handle,
                                format.map_or(vk::Format::UNDEFINED, conv::map_format),
                                &mut format_properties2,
                            );
                            raw_format_modifiers.set_len(drm_format_properties.drm_format_modifier_count as usize);
                        }
                    }

                    let format_modifiers: Vec<format::DrmFormatProperties> = raw_format_modifiers
                        .into_iter()
                        .filter_map(|format_modifier_properties| {
                            let format_modifier = format::DrmModifier::from(
                                format_modifier_properties.drm_format_modifier,
                            );
                            if let format::DrmModifier::Unrecognized(value) = format_modifier {
                                error!("Unrecognized drm format modifier: {:#?}", value);
                                None
                            } else {
                                Some(format::DrmFormatProperties {
                                    drm_modifier: format_modifier,
                                    plane_count: format_modifier_properties
                                        .drm_format_modifier_plane_count,
                                    valid_usages: conv::map_image_features(
                                        format_modifier_properties
                                            .drm_format_modifier_tiling_features,
                                        supports_transfer_bits,
                                        supports_sampler_filter_minmax,
                                    ),
                                })
                            }
                        })
                        .collect();
                    (format_properties2.format_properties, format_modifiers)
                }
            }
        };

        format::Properties {
            linear_tiling: conv::map_image_features(
                properties.linear_tiling_features,
                supports_transfer_bits,
                supports_sampler_filter_minmax,
            ),
            optimal_tiling: conv::map_image_features(
                properties.optimal_tiling_features,
                supports_transfer_bits,
                supports_sampler_filter_minmax,
            ),
            buffer_features: conv::map_buffer_features(properties.buffer_features),
            drm_format_properties,
        }
    }

    fn image_format_properties(
        &self,
        format: format::Format,
        dimensions: u8,
        tiling: image::Tiling,
        usage: image::Usage,
        view_caps: image::ViewCapabilities,
    ) -> Option<image::FormatProperties> {
        let format_properties = unsafe {
            self.instance
                .inner
                .get_physical_device_image_format_properties(
                    self.handle,
                    conv::map_format(format),
                    match dimensions {
                        1 => vk::ImageType::TYPE_1D,
                        2 => vk::ImageType::TYPE_2D,
                        3 => vk::ImageType::TYPE_3D,
                        _ => panic!("Unexpected image dimensionality: {}", dimensions),
                    },
                    conv::map_tiling(tiling),
                    conv::map_image_usage(usage),
                    conv::map_view_capabilities(view_caps),
                )
        };

        match format_properties {
            Ok(props) => Some(image::FormatProperties {
                max_extent: image::Extent {
                    width: props.max_extent.width,
                    height: props.max_extent.height,
                    depth: props.max_extent.depth,
                },
                max_levels: props.max_mip_levels as _,
                max_layers: props.max_array_layers as _,
                sample_count_mask: props.sample_counts.as_raw() as _,
                max_resource_size: props.max_resource_size as _,
            }),
            Err(vk::Result::ERROR_FORMAT_NOT_SUPPORTED) => None,
            Err(other) => {
                error!("Unexpected error in `image_format_properties`: {:?}", other);
                None
            }
        }
    }

    fn memory_properties(&self) -> adapter::MemoryProperties {
        let mem_properties = unsafe {
            self.instance
                .inner
                .get_physical_device_memory_properties(self.handle)
        };
        let memory_heaps = mem_properties.memory_heaps[..mem_properties.memory_heap_count as usize]
            .iter()
            .map(|mem| adapter::MemoryHeap {
                size: mem.size,
                flags: conv::map_vk_memory_heap_flags(mem.flags),
            })
            .collect();
        let memory_types = mem_properties.memory_types[..mem_properties.memory_type_count as usize]
            .iter()
            .filter_map(|mem| {
                if self.known_memory_flags.contains(mem.property_flags) {
                    Some(adapter::MemoryType {
                        properties: conv::map_vk_memory_properties(mem.property_flags),
                        heap_index: mem.heap_index as usize,
                    })
                } else {
                    warn!(
                        "Skipping memory type with unknown flags {:?}",
                        mem.property_flags
                    );
                    None
                }
            })
            .collect();

        adapter::MemoryProperties {
            memory_heaps,
            memory_types,
        }
    }

    fn external_buffer_properties(
        &self,
        usage: hal::buffer::Usage,
        sparse: hal::memory::SparseFlags,
        external_memory_type: external_memory::ExternalMemoryType,
    ) -> external_memory::ExternalMemoryProperties {
        let external_memory_type_flags: hal::external_memory::ExternalMemoryTypeFlags =
            external_memory_type.into();
        let vk_external_memory_type =
            vk::ExternalMemoryHandleTypeFlags::from_raw(external_memory_type_flags.bits());

        let external_buffer_info = vk::PhysicalDeviceExternalBufferInfo::builder()
            .flags(conv::map_buffer_create_flags(sparse))
            .usage(conv::map_buffer_usage(usage))
            .handle_type(vk_external_memory_type)
            .build();

        let vk_mem_properties = match self.instance.external_memory_capabilities.as_ref() {
            Some(ExtensionFn::Extension(external_memory_capabilities_extension)) => {
                let mut external_buffer_properties =
                    vk::ExternalBufferProperties::builder().build();
                unsafe {
                    external_memory_capabilities_extension
                        .get_physical_device_external_buffer_properties_khr(
                            self.handle,
                            &external_buffer_info,
                            &mut external_buffer_properties,
                        )
                };
                external_buffer_properties.external_memory_properties
            }
            Some(ExtensionFn::Promoted) => {
                use ash::version::InstanceV1_1;
                let mut external_buffer_properties =
                    vk::ExternalBufferProperties::builder().build();
                unsafe {
                    self.instance
                        .inner
                        .get_physical_device_external_buffer_properties(
                            self.handle,
                            &external_buffer_info,
                            &mut external_buffer_properties,
                        )
                }
                external_buffer_properties.external_memory_properties
            }
            None => panic!(
                "This function rely on `Feature::EXTERNAL_MEMORY`, but the feature is not enabled"
            ),
        };

        let mut external_memory_properties = external_memory::ExternalMemoryProperties::empty();
        if vk_mem_properties
            .external_memory_features
            .contains(vk::ExternalMemoryFeatureFlags::EXPORTABLE)
        {
            external_memory_properties |= external_memory::ExternalMemoryProperties::EXPORTABLE;
        }

        if vk_mem_properties
            .external_memory_features
            .contains(vk::ExternalMemoryFeatureFlags::IMPORTABLE)
        {
            external_memory_properties |= external_memory::ExternalMemoryProperties::IMPORTABLE;
        }

        if vk_mem_properties
            .export_from_imported_handle_types
            .contains(vk_external_memory_type)
        {
            external_memory_properties |=
                external_memory::ExternalMemoryProperties::EXPORTABLE_FROM_IMPORTED;
        }

        external_memory_properties
    }

    fn external_image_properties(
        &self,
        format: format::Format,
        dimensions: u8,
        tiling: image::Tiling,
        usage: image::Usage,
        view_caps: image::ViewCapabilities,
        external_memory_type: external_memory::ExternalMemoryType,
    ) -> Result<external_memory::ExternalMemoryProperties, external_memory::ExternalImagePropertiesError>
    {
        if self.instance.external_memory_capabilities.is_none() {
            panic!(
                "This function rely on `Feature::EXTERNAL_MEMORY`, but the feature is not enabled"
            );
        }

        use ash::version::InstanceV1_1;
        let external_memory_type_flags: hal::external_memory::ExternalMemoryTypeFlags =
            external_memory_type.into();
        let vk_external_memory_type =
            vk::ExternalMemoryHandleTypeFlags::from_raw(external_memory_type_flags.bits());

        let mut external_image_format_info = vk::PhysicalDeviceExternalImageFormatInfo::builder()
            .handle_type(vk_external_memory_type)
            .build();
        let image_format_info = vk::PhysicalDeviceImageFormatInfo2::builder()
            .push_next(&mut external_image_format_info)
            .format(conv::map_format(format))
            .ty(match dimensions {
                1 => vk::ImageType::TYPE_1D,
                2 => vk::ImageType::TYPE_2D,
                3 => vk::ImageType::TYPE_3D,
                _ => panic!("Unexpected image dimensionality: {}", dimensions),
            })
            .tiling(conv::map_tiling(tiling))
            .usage(conv::map_image_usage(usage))
            .flags(conv::map_view_capabilities(view_caps))
            .build();

        let mut external_image_format_properties =
            vk::ExternalImageFormatProperties::builder().build();
        let mut image_format_properties = vk::ImageFormatProperties2::builder()
            .push_next(&mut external_image_format_properties)
            .build();

        match unsafe {
            self.instance
                .inner
                .get_physical_device_image_format_properties2(
                    self.handle,
                    &image_format_info,
                    &mut image_format_properties,
                )
        } {
            Ok(_) => {
                let vk_mem_properties = external_image_format_properties.external_memory_properties;

                let mut external_memory_properties =
                    external_memory::ExternalMemoryProperties::empty();
                if vk_mem_properties
                    .external_memory_features
                    .contains(vk::ExternalMemoryFeatureFlags::EXPORTABLE)
                {
                    external_memory_properties |=
                        external_memory::ExternalMemoryProperties::EXPORTABLE;
                }

                if vk_mem_properties
                    .external_memory_features
                    .contains(vk::ExternalMemoryFeatureFlags::IMPORTABLE)
                {
                    external_memory_properties |=
                        external_memory::ExternalMemoryProperties::IMPORTABLE;
                }

                if vk_mem_properties
                    .export_from_imported_handle_types
                    .contains(vk_external_memory_type)
                {
                    external_memory_properties |=
                        external_memory::ExternalMemoryProperties::EXPORTABLE_FROM_IMPORTED;
                }
                Ok(external_memory_properties)
            }
            Err(vk::Result::ERROR_OUT_OF_HOST_MEMORY) => Err(OutOfMemory::Host.into()),
            Err(vk::Result::ERROR_OUT_OF_DEVICE_MEMORY) => Err(OutOfMemory::Device.into()),
            Err(vk::Result::ERROR_FORMAT_NOT_SUPPORTED) => {
                Err(external_memory::ExternalImagePropertiesError::FormatNotSupported)
            }
            Err(err) => {
                panic!("Unexpected error: {:#?}", err);
            }
        }
    }

    fn features(&self) -> Features {
        self.available_features
    }

    fn properties(&self) -> PhysicalDeviceProperties {
        let limits = {
            let limits = &self.device_info.properties.limits;

            let max_group_count = limits.max_compute_work_group_count;
            let max_group_size = limits.max_compute_work_group_size;

            Limits {
                max_image_1d_size: limits.max_image_dimension1_d,
                max_image_2d_size: limits.max_image_dimension2_d,
                max_image_3d_size: limits.max_image_dimension3_d,
                max_image_cube_size: limits.max_image_dimension_cube,
                max_image_array_layers: limits.max_image_array_layers as _,
                max_texel_elements: limits.max_texel_buffer_elements as _,
                max_patch_size: limits.max_tessellation_patch_size as PatchSize,
                max_viewports: limits.max_viewports as _,
                max_viewport_dimensions: limits.max_viewport_dimensions,
                max_framebuffer_extent: image::Extent {
                    width: limits.max_framebuffer_width,
                    height: limits.max_framebuffer_height,
                    depth: limits.max_framebuffer_layers,
                },
                max_compute_work_group_count: [
                    max_group_count[0] as _,
                    max_group_count[1] as _,
                    max_group_count[2] as _,
                ],
                max_compute_work_group_size: [
                    max_group_size[0] as _,
                    max_group_size[1] as _,
                    max_group_size[2] as _,
                ],
                max_vertex_input_attributes: limits.max_vertex_input_attributes as _,
                max_vertex_input_bindings: limits.max_vertex_input_bindings as _,
                max_vertex_input_attribute_offset: limits.max_vertex_input_attribute_offset as _,
                max_vertex_input_binding_stride: limits.max_vertex_input_binding_stride as _,
                max_vertex_output_components: limits.max_vertex_output_components as _,
                optimal_buffer_copy_offset_alignment: limits.optimal_buffer_copy_offset_alignment
                    as _,
                optimal_buffer_copy_pitch_alignment: limits.optimal_buffer_copy_row_pitch_alignment
                    as _,
                min_texel_buffer_offset_alignment: limits.min_texel_buffer_offset_alignment as _,
                min_uniform_buffer_offset_alignment: limits.min_uniform_buffer_offset_alignment
                    as _,
                min_storage_buffer_offset_alignment: limits.min_storage_buffer_offset_alignment
                    as _,
                framebuffer_color_sample_counts: limits.framebuffer_color_sample_counts.as_raw()
                    as _,
                framebuffer_depth_sample_counts: limits.framebuffer_depth_sample_counts.as_raw()
                    as _,
                framebuffer_stencil_sample_counts: limits.framebuffer_stencil_sample_counts.as_raw()
                    as _,
                timestamp_compute_and_graphics: limits.timestamp_compute_and_graphics != 0,
                max_color_attachments: limits.max_color_attachments as _,
                buffer_image_granularity: limits.buffer_image_granularity,
                non_coherent_atom_size: limits.non_coherent_atom_size as _,
                max_sampler_anisotropy: limits.max_sampler_anisotropy,
                min_vertex_input_binding_stride_alignment: 1,
                max_bound_descriptor_sets: limits.max_bound_descriptor_sets as _,
                max_compute_shared_memory_size: limits.max_compute_shared_memory_size as _,
                max_compute_work_group_invocations: limits.max_compute_work_group_invocations as _,
                descriptor_limits: DescriptorLimits {
                    max_per_stage_descriptor_samplers: limits.max_per_stage_descriptor_samplers,
                    max_per_stage_descriptor_storage_buffers: limits
                        .max_per_stage_descriptor_storage_buffers,
                    max_per_stage_descriptor_uniform_buffers: limits
                        .max_per_stage_descriptor_uniform_buffers,
                    max_per_stage_descriptor_sampled_images: limits
                        .max_per_stage_descriptor_sampled_images,
                    max_per_stage_descriptor_storage_images: limits
                        .max_per_stage_descriptor_storage_images,
                    max_per_stage_descriptor_input_attachments: limits
                        .max_per_stage_descriptor_input_attachments,
                    max_per_stage_resources: limits.max_per_stage_resources,
                    max_descriptor_set_samplers: limits.max_descriptor_set_samplers,
                    max_descriptor_set_uniform_buffers: limits.max_descriptor_set_uniform_buffers,
                    max_descriptor_set_uniform_buffers_dynamic: limits
                        .max_descriptor_set_uniform_buffers_dynamic,
                    max_descriptor_set_storage_buffers: limits.max_descriptor_set_storage_buffers,
                    max_descriptor_set_storage_buffers_dynamic: limits
                        .max_descriptor_set_storage_buffers_dynamic,
                    max_descriptor_set_sampled_images: limits.max_descriptor_set_sampled_images,
                    max_descriptor_set_storage_images: limits.max_descriptor_set_storage_images,
                    max_descriptor_set_input_attachments: limits
                        .max_descriptor_set_input_attachments,
                },
                max_draw_indexed_index_value: limits.max_draw_indexed_index_value,
                max_draw_indirect_count: limits.max_draw_indirect_count,
                max_fragment_combined_output_resources: limits
                    .max_fragment_combined_output_resources
                    as _,
                max_fragment_dual_source_attachments: limits.max_fragment_dual_src_attachments as _,
                max_fragment_input_components: limits.max_fragment_input_components as _,
                max_fragment_output_attachments: limits.max_fragment_output_attachments as _,
                max_framebuffer_layers: limits.max_framebuffer_layers as _,
                max_geometry_input_components: limits.max_geometry_input_components as _,
                max_geometry_output_components: limits.max_geometry_output_components as _,
                max_geometry_output_vertices: limits.max_geometry_output_vertices as _,
                max_geometry_shader_invocations: limits.max_geometry_shader_invocations as _,
                max_geometry_total_output_components: limits.max_geometry_total_output_components
                    as _,
                max_memory_allocation_count: limits.max_memory_allocation_count as _,
                max_push_constants_size: limits.max_push_constants_size as _,
                max_sampler_allocation_count: limits.max_sampler_allocation_count as _,
                max_sampler_lod_bias: limits.max_sampler_lod_bias as _,
                max_storage_buffer_range: limits.max_storage_buffer_range as _,
                max_uniform_buffer_range: limits.max_uniform_buffer_range as _,
                min_memory_map_alignment: limits.min_memory_map_alignment,
                standard_sample_locations: limits.standard_sample_locations == ash::vk::TRUE,
            }
        };

        let mut descriptor_indexing_capabilities = hal::DescriptorIndexingProperties::default();
        let mut mesh_shader_capabilities = hal::MeshShaderProperties::default();
        let mut sampler_reduction_capabilities = hal::SamplerReductionProperties::default();
        let mut external_memory_limits = hal::ExternalMemoryLimits::default();

        if let Some(get_physical_device_properties) =
            self.instance.get_physical_device_properties.as_ref()
        {
            let mut descriptor_indexing_properties =
                vk::PhysicalDeviceDescriptorIndexingPropertiesEXT::builder();
            let mut mesh_shader_properties = vk::PhysicalDeviceMeshShaderPropertiesNV::builder();
            let mut sampler_reduction_properties =
                vk::PhysicalDeviceSamplerFilterMinmaxProperties::builder();
            let mut memory_host_properties =
                vk::PhysicalDeviceExternalMemoryHostPropertiesEXT::builder();

            let mut physical_device_properties2 = vk::PhysicalDeviceProperties2::builder()
                .push_next(&mut descriptor_indexing_properties)
                .push_next(&mut mesh_shader_properties)
                .push_next(&mut sampler_reduction_properties)
                .push_next(&mut memory_host_properties)
                .build();

            match get_physical_device_properties {
                ExtensionFn::Promoted => {
                    use ash::version::InstanceV1_1;
                    unsafe {
                        self.instance.inner.get_physical_device_properties2(
                            self.handle,
                            &mut physical_device_properties2,
                        );
                    }
                }
                ExtensionFn::Extension(get_physical_device_properties) => unsafe {
                    get_physical_device_properties.get_physical_device_properties2_khr(
                        self.handle,
                        &mut physical_device_properties2,
                    );
                },
            }

            descriptor_indexing_capabilities = hal::DescriptorIndexingProperties {
                shader_uniform_buffer_array_non_uniform_indexing_native:
                    descriptor_indexing_properties
                        .shader_uniform_buffer_array_non_uniform_indexing_native
                        == vk::TRUE,
                shader_sampled_image_array_non_uniform_indexing_native:
                    descriptor_indexing_properties
                        .shader_sampled_image_array_non_uniform_indexing_native
                        == vk::TRUE,
                shader_storage_buffer_array_non_uniform_indexing_native:
                    descriptor_indexing_properties
                        .shader_storage_buffer_array_non_uniform_indexing_native
                        == vk::TRUE,
                shader_storage_image_array_non_uniform_indexing_native:
                    descriptor_indexing_properties
                        .shader_storage_image_array_non_uniform_indexing_native
                        == vk::TRUE,
                shader_input_attachment_array_non_uniform_indexing_native:
                    descriptor_indexing_properties
                        .shader_input_attachment_array_non_uniform_indexing_native
                        == vk::TRUE,
                quad_divergent_implicit_lod: descriptor_indexing_properties
                    .quad_divergent_implicit_lod
                    == vk::TRUE,
            };

            mesh_shader_capabilities = hal::MeshShaderProperties {
                max_draw_mesh_tasks_count: mesh_shader_properties.max_draw_mesh_tasks_count,
                max_task_work_group_invocations: mesh_shader_properties
                    .max_task_work_group_invocations,
                max_task_work_group_size: mesh_shader_properties.max_task_work_group_size,
                max_task_total_memory_size: mesh_shader_properties.max_task_total_memory_size,
                max_task_output_count: mesh_shader_properties.max_task_output_count,
                max_mesh_work_group_invocations: mesh_shader_properties
                    .max_mesh_work_group_invocations,
                max_mesh_work_group_size: mesh_shader_properties.max_mesh_work_group_size,
                max_mesh_total_memory_size: mesh_shader_properties.max_mesh_total_memory_size,
                max_mesh_output_vertices: mesh_shader_properties.max_mesh_output_vertices,
                max_mesh_output_primitives: mesh_shader_properties.max_mesh_output_primitives,
                max_mesh_multiview_view_count: mesh_shader_properties.max_mesh_multiview_view_count,
                mesh_output_per_vertex_granularity: mesh_shader_properties
                    .mesh_output_per_vertex_granularity,
                mesh_output_per_primitive_granularity: mesh_shader_properties
                    .mesh_output_per_primitive_granularity,
            };

            sampler_reduction_capabilities = hal::SamplerReductionProperties {
                single_component_formats: sampler_reduction_properties
                    .filter_minmax_single_component_formats
                    == vk::TRUE,
                image_component_mapping: sampler_reduction_properties
                    .filter_minmax_image_component_mapping
                    == vk::TRUE,
            };

            external_memory_limits = ExternalMemoryLimits {
                min_imported_host_pointer_alignment: memory_host_properties
                    .min_imported_host_pointer_alignment,
            };
        }

        PhysicalDeviceProperties {
            limits,
            descriptor_indexing: descriptor_indexing_capabilities,
            mesh_shader: mesh_shader_capabilities,
            sampler_reduction: sampler_reduction_capabilities,
            performance_caveats: Default::default(),
            dynamic_pipeline_states: DynamicStates::all(),
            downlevel: DownlevelProperties::all_enabled(),
            external_memory_limits,
        }
    }

    fn is_valid_cache(&self, cache: &[u8]) -> bool {
        const HEADER_SIZE: usize = 16 + vk::UUID_SIZE;

        if cache.len() < HEADER_SIZE {
            warn!("Bad cache data length {:?}", cache.len());
            return false;
        }

        let header_len = u32::from_le_bytes([cache[0], cache[1], cache[2], cache[3]]);
        let header_version = u32::from_le_bytes([cache[4], cache[5], cache[6], cache[7]]);
        let vendor_id = u32::from_le_bytes([cache[8], cache[9], cache[10], cache[11]]);
        let device_id = u32::from_le_bytes([cache[12], cache[13], cache[14], cache[15]]);

        // header length
        if (header_len as usize) < HEADER_SIZE {
            warn!("Bad header length {:?}", header_len);
            return false;
        }

        // cache header version
        if header_version != vk::PipelineCacheHeaderVersion::ONE.as_raw() as u32 {
            warn!("Unsupported cache header version: {:?}", header_version);
            return false;
        }

        // vendor id
        if vendor_id != self.device_info.properties.vendor_id {
            warn!(
                "Vendor ID mismatch. Device: {:?}, cache: {:?}.",
                self.device_info.properties.vendor_id, vendor_id,
            );
            return false;
        }

        // device id
        if device_id != self.device_info.properties.device_id {
            warn!(
                "Device ID mismatch. Device: {:?}, cache: {:?}.",
                self.device_info.properties.device_id, device_id,
            );
            return false;
        }

        if self.device_info.properties.pipeline_cache_uuid != cache[16..16 + vk::UUID_SIZE] {
            warn!(
                "Pipeline cache UUID mismatch. Device: {:?}, cache: {:?}.",
                self.device_info.properties.pipeline_cache_uuid,
                &cache[16..16 + vk::UUID_SIZE],
            );
            return false;
        }
        true
    }

    unsafe fn enumerate_displays(&self) -> Vec<display::Display<Backend>> {
        let display_extension = match self.instance.display {
            Some(ref display_extension) => display_extension,
            None => {
                error!("Direct display feature not supported");
                return Vec::new();
            }
        };

        let display_properties =
            match display_extension.get_physical_device_display_properties(self.handle) {
                Ok(display_properties) => display_properties,
                Err(err) => {
                    match err {
                        vk::Result::ERROR_OUT_OF_HOST_MEMORY
                        | vk::Result::ERROR_OUT_OF_DEVICE_MEMORY => error!(
                            "Error returned on `get_physical_device_display_properties`: {:#?}",
                            err
                        ),
                        err => error!(
                            "Unexpected error on `get_physical_device_display_properties`: {:#?}",
                            err
                        ),
                    }
                    return Vec::new();
                }
            };

        let mut displays = Vec::new();
        for display_property in display_properties {
            let supported_transforms = hal::display::SurfaceTransformFlags::from_bits(
                display_property.supported_transforms.as_raw(),
            )
            .unwrap();
            let display_name = if display_property.display_name.is_null() {
                None
            } else {
                Some(
                    std::ffi::CStr::from_ptr(display_property.display_name)
                        .to_str()
                        .unwrap()
                        .to_owned(),
                )
            };

            let display_info = display::DisplayInfo {
                name: display_name,
                physical_dimensions: (
                    display_property.physical_dimensions.width,
                    display_property.physical_dimensions.height,
                )
                    .into(),
                physical_resolution: (
                    display_property.physical_resolution.width,
                    display_property.physical_resolution.height,
                )
                    .into(),
                supported_transforms: supported_transforms,
                plane_reorder_possible: display_property.plane_reorder_possible == 1,
                persistent_content: display_property.persistent_content == 1,
            };

            let display_modes = match display_extension
                .get_display_mode_properties(self.handle, display_property.display)
            {
                Ok(display_modes) => display_modes,
                Err(err) => {
                    match err {
                        vk::Result::ERROR_OUT_OF_HOST_MEMORY
                        | vk::Result::ERROR_OUT_OF_DEVICE_MEMORY => error!(
                            "Error returned on `get_display_mode_properties`: {:#?}",
                            err
                        ),
                        err => error!(
                            "Unexpected error on `get_display_mode_properties`: {:#?}",
                            err
                        ),
                    }
                    return Vec::new();
                }
            }
            .iter()
            .map(|display_mode_properties| display::DisplayMode {
                handle: native::DisplayMode(display_mode_properties.display_mode),
                resolution: (
                    display_mode_properties.parameters.visible_region.width,
                    display_mode_properties.parameters.visible_region.height,
                ),
                refresh_rate: display_mode_properties.parameters.refresh_rate,
            })
            .collect();

            let display = display::Display {
                handle: native::Display(display_property.display),
                info: display_info,
                modes: display_modes,
            };

            displays.push(display);
        }
        return displays;
    }

    unsafe fn enumerate_compatible_planes(
        &self,
        display: &display::Display<Backend>,
    ) -> Vec<display::Plane> {
        let display_extension = match self.instance.display {
            Some(ref display_extension) => display_extension,
            None => {
                error!("Direct display feature not supported");
                return Vec::new();
            }
        };

        match display_extension.get_physical_device_display_plane_properties(self.handle) {
            Ok(planes_properties) => {
                let mut planes = Vec::new();
                for index in 0..planes_properties.len() {
                    let compatible_displays = match display_extension
                        .get_display_plane_supported_displays(self.handle, index as u32)
                    {
                        Ok(compatible_displays) => compatible_displays,
                        Err(err) => {
                            match err {
                                vk::Result::ERROR_OUT_OF_HOST_MEMORY | vk::Result::ERROR_OUT_OF_DEVICE_MEMORY =>
                                    error!("Error returned on `get_display_plane_supported_displays`: {:#?}",err),
                                err=>error!("Unexpected error on `get_display_plane_supported_displays`: {:#?}",err)
                            }
                            return Vec::new();
                        }
                    };
                    if compatible_displays.contains(&display.handle.0) {
                        planes.push(display::Plane {
                            handle: index as u32,
                            z_index: planes_properties[index].current_stack_index,
                        });
                    }
                }
                planes
            }
            Err(err) => {
                match err {
                    vk::Result::ERROR_OUT_OF_HOST_MEMORY
                    | vk::Result::ERROR_OUT_OF_DEVICE_MEMORY => error!(
                        "Error returned on `get_physical_device_display_plane_properties`: {:#?}",
                        err
                    ),
                    err => error!(
                        "Unexpected error on `get_physical_device_display_plane_properties`: {:#?}",
                        err
                    ),
                }
                Vec::new()
            }
        }
    }

    unsafe fn create_display_mode(
        &self,
        display: &display::Display<Backend>,
        resolution: (u32, u32),
        refresh_rate: u32,
    ) -> Result<display::DisplayMode<Backend>, display::DisplayModeError> {
        let display_extension = self.instance.display.as_ref().unwrap();

        let display_mode_ci = vk::DisplayModeCreateInfoKHR::builder()
            .parameters(vk::DisplayModeParametersKHR {
                visible_region: vk::Extent2D {
                    width: resolution.0,
                    height: resolution.1,
                },
                refresh_rate: refresh_rate,
            })
            .build();

        match display_extension.create_display_mode(
            self.handle,
            display.handle.0,
            &display_mode_ci,
            None,
        ) {
            Ok(display_mode_handle) => Ok(display::DisplayMode {
                handle: native::DisplayMode(display_mode_handle),
                resolution: resolution,
                refresh_rate: refresh_rate,
            }),
            Err(vk::Result::ERROR_OUT_OF_HOST_MEMORY) => return Err(OutOfMemory::Host.into()),
            Err(vk::Result::ERROR_OUT_OF_DEVICE_MEMORY) => return Err(OutOfMemory::Device.into()),
            Err(vk::Result::ERROR_INITIALIZATION_FAILED) => {
                return Err(display::DisplayModeError::UnsupportedDisplayMode.into())
            }
            Err(err) => panic!("Unexpected error on `create_display_mode`: {:#?}", err),
        }
    }

    unsafe fn create_display_plane<'a>(
        &self,
        display_mode: &'a display::DisplayMode<Backend>,
        plane: &'a display::Plane,
    ) -> Result<display::DisplayPlane<'a, Backend>, OutOfMemory> {
        let display_extension = self.instance.display.as_ref().unwrap();

        let display_plane_capabilities = match display_extension.get_display_plane_capabilities(
            self.handle,
            display_mode.handle.0,
            plane.handle,
        ) {
            Ok(display_plane_capabilities) => display_plane_capabilities,
            Err(vk::Result::ERROR_OUT_OF_HOST_MEMORY) => return Err(OutOfMemory::Host.into()),
            Err(vk::Result::ERROR_OUT_OF_DEVICE_MEMORY) => return Err(OutOfMemory::Device.into()),
            Err(err) => panic!(
                "Unexpected error on `get_display_plane_capabilities`: {:#?}",
                err
            ),
        };

        let mut supported_alpha_capabilities = Vec::new();
        if display_plane_capabilities
            .supported_alpha
            .contains(vk::DisplayPlaneAlphaFlagsKHR::OPAQUE)
        {
            supported_alpha_capabilities.push(display::DisplayPlaneAlpha::Opaque);
        }
        if display_plane_capabilities
            .supported_alpha
            .contains(vk::DisplayPlaneAlphaFlagsKHR::GLOBAL)
        {
            supported_alpha_capabilities.push(display::DisplayPlaneAlpha::Global(1.0));
        }
        if display_plane_capabilities
            .supported_alpha
            .contains(vk::DisplayPlaneAlphaFlagsKHR::PER_PIXEL)
        {
            supported_alpha_capabilities.push(display::DisplayPlaneAlpha::PerPixel);
        }
        if display_plane_capabilities
            .supported_alpha
            .contains(vk::DisplayPlaneAlphaFlagsKHR::PER_PIXEL_PREMULTIPLIED)
        {
            supported_alpha_capabilities.push(display::DisplayPlaneAlpha::PerPixelPremultiplied);
        }

        Ok(display::DisplayPlane {
            plane: &plane,
            display_mode: &display_mode,
            supported_alpha: supported_alpha_capabilities,
            src_position: std::ops::Range {
                start: (
                    display_plane_capabilities.min_src_position.x,
                    display_plane_capabilities.min_src_position.x,
                )
                    .into(),
                end: (
                    display_plane_capabilities.max_src_position.x,
                    display_plane_capabilities.max_src_position.x,
                )
                    .into(),
            },
            src_extent: std::ops::Range {
                start: (
                    display_plane_capabilities.min_src_extent.width,
                    display_plane_capabilities.min_src_extent.height,
                )
                    .into(),
                end: (
                    display_plane_capabilities.max_src_extent.width,
                    display_plane_capabilities.max_src_extent.height,
                )
                    .into(),
            },
            dst_position: std::ops::Range {
                start: (
                    display_plane_capabilities.min_dst_position.x,
                    display_plane_capabilities.min_dst_position.x,
                )
                    .into(),
                end: (
                    display_plane_capabilities.max_dst_position.x,
                    display_plane_capabilities.max_dst_position.x,
                )
                    .into(),
            },
            dst_extent: std::ops::Range {
                start: (
                    display_plane_capabilities.min_dst_extent.width,
                    display_plane_capabilities.min_dst_extent.height,
                )
                    .into(),
                end: (
                    display_plane_capabilities.max_dst_extent.width,
                    display_plane_capabilities.max_dst_extent.height,
                )
                    .into(),
            },
        })
    }
}