-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvulkan.odin
More file actions
4479 lines (3713 loc) · 158 KB
/
vulkan.odin
File metadata and controls
4479 lines (3713 loc) · 158 KB
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
#+build !js
package gpu
// Core
import "base:runtime"
import "core:dynlib"
import "core:fmt"
import "core:log"
import "core:mem"
import "core:slice"
import "core:strings"
import "core:sync"
import sa "core:container/small_array"
// Local packages
import "libs/vma"
// Vendor
import vk "vendor:vulkan"
// Required Vulkan version
VK_API_VERSION :: vk.API_VERSION_1_3
vk_init :: proc(allocator := context.allocator) {
// Global procedures
create_instance_impl = vk_create_instance
// Adapter procedures
adapter_get_info = vk_adapter_get_info
adapter_info_free_members = vk_adapter_info_free_members
adapter_get_features = vk_adapter_get_features
adapter_get_limits = vk_adapter_get_limits
adapter_request_device = vk_adapter_request_device
adapter_get_label = vk_adapter_get_label
adapter_set_label = vk_adapter_set_label
adapter_add_ref = vk_adapter_add_ref
adapter_release = vk_adapter_release
// Bind Group procedures
bind_group_get_label = vk_bind_group_get_label
bind_group_set_label = vk_bind_group_set_label
bind_group_add_ref = vk_bind_group_add_ref
bind_group_release = vk_bind_group_release
// Bind Group Layout procedures
bind_group_layout_get_label = vk_bind_group_layout_get_label
bind_group_layout_set_label = vk_bind_group_layout_set_label
bind_group_layout_add_ref = vk_bind_group_layout_add_ref
bind_group_layout_release = vk_bind_group_layout_release
// Buffer procedures
buffer_destroy = vk_buffer_destroy
buffer_unmap = vk_buffer_unmap
buffer_get_map_state = vk_buffer_get_map_state
buffer_get_size = vk_buffer_get_size
buffer_get_usage = vk_buffer_get_usage
buffer_get_label = vk_buffer_get_label
buffer_set_label = vk_buffer_set_label
buffer_add_ref = vk_buffer_add_ref
buffer_release = vk_buffer_release
// Command Buffer procedures
command_buffer_get_label = vk_command_buffer_get_label
command_buffer_set_label = vk_command_buffer_set_label
command_buffer_add_ref = vk_command_buffer_add_ref
command_buffer_release = vk_command_buffer_release
// Command Encoder procedures
command_encoder_begin_render_pass = vk_command_encoder_begin_render_pass
command_encoder_copy_texture_to_texture = vk_command_encoder_copy_texture_to_texture
command_encoder_finish = vk_command_encoder_finish
command_encoder_get_label = vk_command_encoder_get_label
command_encoder_set_label = vk_command_encoder_set_label
command_encoder_add_ref = vk_command_encoder_add_ref
command_encoder_release = vk_command_encoder_release
// Device procedures
device_get_features = vk_device_get_features
device_get_limits = vk_device_get_limits
device_create_bind_group = vk_device_create_bind_group
device_create_bind_group_layout = vk_device_create_bind_group_layout
device_create_buffer = vk_device_create_buffer
device_create_command_encoder = vk_device_create_command_encoder
device_create_pipeline_layout = vk_device_create_pipeline_layout
device_create_render_pipeline = vk_device_create_render_pipeline
device_create_sampler = vk_device_create_sampler
device_create_shader_module = vk_device_create_shader_module
device_create_texture = vk_device_create_texture
device_get_queue = vk_device_get_queue
device_get_label = vk_device_get_label
device_set_label = vk_device_set_label
device_add_ref = vk_device_add_ref
device_release = vk_device_release
// Instance procedures
instance_create_surface = vk_instance_create_surface
instance_request_adapter = vk_instance_request_adapter
instance_enumerate_adapters = vk_instance_enumerate_adapters
instance_get_label = vk_instance_get_label
instance_set_label = vk_instance_set_label
instance_add_ref = vk_instance_add_ref
instance_release = vk_instance_release
// Queue procedures
queue_submit = vk_queue_submit
queue_write_buffer_impl = vk_queue_write_buffer
queue_write_texture = vk_queue_write_texture
queue_get_label = vk_queue_get_label
queue_set_label = vk_queue_set_label
queue_add_ref = vk_queue_add_ref
queue_release = vk_queue_release
// Render Pass procedures
render_pass_draw = vk_render_pass_draw
render_pass_draw_indexed = vk_render_pass_draw_indexed
render_pass_end = vk_render_pass_end
render_pass_set_bind_group = vk_render_pass_set_bind_group
render_pass_set_index_buffer = vk_render_pass_set_index_buffer
render_pass_set_pipeline = vk_render_pass_set_pipeline
render_pass_set_scissor_rect = vk_render_pass_set_scissor_rect
render_pass_set_stencil_reference = vk_render_pass_set_stencil_reference
render_pass_set_vertex_buffer = vk_render_pass_set_vertex_buffer
render_pass_set_viewport = vk_render_pass_set_viewport
render_pass_get_label = vk_render_pass_get_label
render_pass_set_label = vk_render_pass_set_label
render_pass_add_ref = vk_render_pass_add_ref
render_pass_release = vk_render_pass_release
// Render Pipeline procedures
render_pipeline_get_label = vk_render_pipeline_get_label
render_pipeline_set_label = vk_render_pipeline_set_label
render_pipeline_add_ref = vk_render_pipeline_add_ref
render_pipeline_release = vk_render_pipeline_release
// Pipeline Layout procedures
pipeline_layout_get_label = vk_pipeline_layout_get_label
pipeline_layout_set_label = vk_pipeline_layout_set_label
pipeline_layout_add_ref = vk_pipeline_layout_add_ref
pipeline_layout_release = vk_pipeline_layout_release
// Sampler procedures
sampler_get_label = vk_sampler_get_label
sampler_set_label = vk_sampler_set_label
sampler_add_ref = vk_sampler_add_ref
sampler_release = vk_sampler_release
// Shader Module procedures
shader_module_get_label = vk_shader_module_get_label
shader_module_set_label = vk_shader_module_set_label
shader_module_add_ref = vk_shader_module_add_ref
shader_module_release = vk_shader_module_release
// Surface procedures
surface_get_capabilities = vk_surface_get_capabilities
surface_capabilities_free_members = vk_surface_capabilities_free_members
surface_configure = vk_surface_configure
surface_get_current_texture = vk_surface_get_current_texture
surface_present = vk_surface_present
surface_get_label = vk_surface_get_label
surface_set_label = vk_surface_set_label
surface_add_ref = vk_surface_add_ref
surface_release = vk_surface_release
// Texture procedures
texture_create_view_impl = vk_texture_create_view
texture_get_descriptor = vk_texture_get_descriptor
texture_get_dimension = vk_texture_get_dimension
texture_get_format = vk_texture_get_format
texture_get_height = vk_texture_get_height
texture_get_mip_level_count = vk_texture_get_mip_level_count
texture_get_sample_count = vk_texture_get_sample_count
texture_get_size = vk_texture_get_size
texture_get_usage = vk_texture_get_usage
texture_get_width = vk_texture_get_width
texture_get_label = vk_texture_get_label
texture_set_label = vk_texture_set_label
texture_add_ref = vk_texture_add_ref
texture_release = vk_texture_release
// Texture View procedures
texture_view_get_label = vk_texture_view_get_label
texture_view_set_label = vk_texture_view_set_label
texture_view_add_ref = vk_texture_view_add_ref
texture_view_release = vk_texture_view_release
}
// -----------------------------------------------------------------------------
// Global procedures that are not specific to an object
// -----------------------------------------------------------------------------
// VK_LAYER_KHRONOS_validation
VK_VALIDATION_LAYER_NAME :: "VK_LAYER_KHRONOS_validation"
Vulkan_Library :: struct {
get_instance_proc_addr: vk.ProcGetInstanceProcAddr,
library: dynlib.Library,
did_load: bool,
init_mutex: sync.Mutex,
}
@(require_results)
vk_create_instance :: proc(
descriptor: Maybe(Instance_Descriptor) = nil,
allocator := context.allocator,
loc := #caller_location,
) -> (
instance: Instance,
) {
desc := descriptor.? or_else {}
ta := context.temp_allocator
runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = allocator == ta)
lib: Vulkan_Library
// Check if user provided a custom proc addr
fp_get_instance_proc_addr := desc.backend_options.vulkan.fp_get_instance_proc_addr
if fp_get_instance_proc_addr != nil {
lib.get_instance_proc_addr = auto_cast fp_get_instance_proc_addr
}
// Otherwise, load the Vulkan library...
if lib.get_instance_proc_addr == nil {
library: dynlib.Library
did_load: bool
when ODIN_OS == .Windows {
library, did_load = dynlib.load_library("vulkan-1.dll")
} else when ODIN_OS == .Darwin {
library, did_load = dynlib.load_library("libvulkan.dylib")
if !did_load { library, did_load = dynlib.load_library("libvulkan.1.dylib") }
// Modern versions of macOS don't search /usr/local/lib
// automatically contrary to what man dlopen says Vulkan SDK uses
// this as the system-wide installation location, so we're going to
// fallback to this if all else fails
if !did_load {
_, found_lib_path := os.lookup_env("DYLD_FALLBACK_LIBRARY_PATH", ta)
if !found_lib_path {
library, did_load = dynlib.load_library("/usr/local/lib/libvulkan.dylib")
}
}
if !did_load { library, did_load = dynlib.load_library("libMoltenVK.dylib") }
// Add support for using Vulkan and MoltenVK in a Framework. App
// store rules for iOS strictly enforce no .dylib's. If they aren't
// found it just falls through
if !did_load { library, did_load = dynlib.load_library("vulkan.framework/vulkan") }
if !did_load { library, did_load = dynlib.load_library("MoltenVK.framework/MoltenVK") }
} else {
library, did_load = dynlib.load_library("libvulkan.so.1")
if !did_load { library, did_load = dynlib.load_library("libvulkan.so") }
}
ensure(did_load && library != nil, "Failed to load Vulkan library", loc)
fp, fp_found := dynlib.symbol_address(library, "vkGetInstanceProcAddr")
ensure(fp_found, "Failed to load Vulkan library", loc)
lib.get_instance_proc_addr = auto_cast fp
lib.library = library
lib.did_load = true
}
// Load the base Vulkan procedures before we can start using them
vk.load_proc_addresses_global(auto_cast lib.get_instance_proc_addr)
ensure(vk.CreateInstance != nil, "Failed to load Vulkan proc addresses", loc)
// Create the instance impl
impl := instance_new_impl(Vulkan_Instance_Impl, allocator, loc)
impl.lib = lib
impl.backend = .Vulkan
impl.shader_formats = { .Spirv }
layer_count: u32
vk_check(vk.EnumerateInstanceLayerProperties(&layer_count, nil))
available_layers := make([]vk.LayerProperties, layer_count, ta)
vk_check(vk.EnumerateInstanceLayerProperties(&layer_count, raw_data(available_layers)))
validation_layers_available: bool
for &layer in available_layers {
layer_name := byte_arr_str(&layer.layerName)
if layer_name == VK_VALIDATION_LAYER_NAME {
validation_layers_available = true
break
}
}
extension_count: u32
vk_check(vk.EnumerateInstanceExtensionProperties(nil, &extension_count, nil))
available_extensions := make([]vk.ExtensionProperties, extension_count, ta)
vk_check(vk.EnumerateInstanceExtensionProperties(
nil, &extension_count, raw_data(available_extensions)))
debug_utils_available: bool
for &ext in available_extensions {
ext_name := byte_arr_str(&ext.extensionName)
if ext_name == vk.EXT_DEBUG_UTILS_EXTENSION_NAME {
debug_utils_available = true
break
}
}
is_extension_available :: proc(
available_extensions: []vk.ExtensionProperties,
required: string,
) -> bool {
for &available in available_extensions {
ext_name := byte_arr_str(&available.extensionName)
if ext_name == required { return true }
}
return false
}
// Query current instance version
instance_api_version : u32 = vk.API_VERSION_1_0
// Instance implementation may be too old to support EnumerateInstanceVersion. We need
// to check the function pointer before calling it, if the function doesn't exist,
// then the instance version must be 1.0.
if vk.EnumerateInstanceVersion != nil {
res := vk.EnumerateInstanceVersion(&instance_api_version)
if res != .SUCCESS {
instance_api_version = vk.API_VERSION_1_0
}
}
ensure(instance_api_version >= VK_API_VERSION, "Vulkan version not available", loc)
// If validation was requested and layers are NOT available, silently
// disable validation flags, this also disables debug messenger
if .Validation in desc.flags && !validation_layers_available {
desc.flags -= { .Validation }
}
// Extensions names to enable
extensions: sa.Small_Array(8, cstring)
if .Validation in desc.flags && debug_utils_available {
sa.push_back(&extensions, vk.EXT_DEBUG_UTILS_EXTENSION_NAME)
}
when ODIN_OS == .Darwin {
portability_enumeration_support: bool
if is_extension_available(
available_extensions,
vk.KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME,
) {
portability_enumeration_support = true
sa.push_back(&extensions, vk.KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME)
}
}
// Add required surface extensions
if !desc.headless {
sa.push_back(&extensions, vk.KHR_SURFACE_EXTENSION_NAME)
when ODIN_OS == .Windows {
sa.push_back(&extensions, vk.KHR_WIN32_SURFACE_EXTENSION_NAME)
} else when ODIN_OS == .Linux {
sa.push_back(&extensions, vk.KHR_XCB_SURFACE_EXTENSION_NAME)
sa.push_back(&extensions, vk.KHR_XLIB_SURFACE_EXTENSION_NAME)
sa.push_back(&extensions, vk.KHR_WAYLAND_SURFACE_EXTENSION_NAME)
} else when ODIN_OS == Darwin {
sa.push_back(&extensions, vk.EXT_METAL_SURFACE_EXTENSION_NAME)
}
} else {
sa.push_back(&extensions, vk.EXT_HEADLESS_SURFACE_EXTENSION_NAME)
}
// Optional instance extensions for enhanced swapchain functionality
if is_extension_available(available_extensions, vk.EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME) {
impl.swapchain_colorspace = true
sa.push_back(&extensions, vk.EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME)
}
// Required for the device extension VK_EXT_swapchain_maintenance1
if is_extension_available(available_extensions, vk.EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME) {
sa.push_back(&extensions, vk.EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME)
}
// Required dependency for VK_EXT_surface_maintenance1
if is_extension_available(available_extensions, vk.KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME) {
sa.push_back(&extensions, vk.KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME)
}
// Layer names to enable
layers: sa.Small_Array(1, cstring)
if .Validation in desc.flags {
sa.push_back(&layers, VK_VALIDATION_LAYER_NAME)
}
pnext_chain := make([dynamic]^vk.BaseOutStructure, ta)
// Setup instance debug utils
messenger_create_info: vk.DebugUtilsMessengerCreateInfoEXT
if .Validation in desc.flags && debug_utils_available {
messenger_create_info.sType = .DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT
messenger_create_info.messageSeverity = { .WARNING, .ERROR }
messenger_create_info.messageType = { .GENERAL, .VALIDATION, .PERFORMANCE }
messenger_create_info.pfnUserCallback = vk_default_debug_callback
messenger_create_info.pUserData = impl
append(&pnext_chain, cast(^vk.BaseOutStructure)&messenger_create_info)
}
app_info := vk.ApplicationInfo {
sType = .APPLICATION_INFO,
pApplicationName = "Odin/GPU",
engineVersion = vk.MAKE_VERSION(1, 0, 0),
pEngineName = "Odin/GPU",
applicationVersion = vk.MAKE_VERSION(1, 0, 0),
apiVersion = VK_API_VERSION,
}
instance_create_info := vk.InstanceCreateInfo {
sType = .INSTANCE_CREATE_INFO,
pApplicationInfo = &app_info,
enabledExtensionCount = u32(sa.len(extensions)),
ppEnabledExtensionNames = raw_data(sa.slice(&extensions)),
enabledLayerCount = u32(sa.len(layers)),
ppEnabledLayerNames = raw_data(sa.slice(&layers)),
}
when ODIN_OS == .Darwin {
if portability_enumeration_support {
instance_create_info.flags += { .ENUMERATE_PORTABILITY_KHR }
}
}
vk_setup_pnext_chain(&instance_create_info, pnext_chain[:])
vk_instance: vk.Instance
vk_check(vk.CreateInstance(&instance_create_info, nil, &vk_instance))
// Load the rest of the functions with our instance
vk.load_proc_addresses(vk_instance)
vk_debug_messenger: vk.DebugUtilsMessengerEXT
if .Validation in desc.flags && debug_utils_available {
debug_utils_create_info := vk.DebugUtilsMessengerCreateInfoEXT {
sType = .DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
messageSeverity = { .WARNING, .ERROR },
messageType = { .GENERAL, .VALIDATION, .PERFORMANCE },
pfnUserCallback = vk_default_debug_callback,
pUserData = impl,
}
vk_check(vk.CreateDebugUtilsMessengerEXT(
vk_instance,
&debug_utils_create_info,
nil,
&vk_debug_messenger,
))
}
impl.vk_instance = vk_instance
impl.vk_debug_messenger = vk_debug_messenger
impl.instance_version = instance_api_version
impl.api_version = VK_API_VERSION
impl.flags = desc.flags
impl.headless = desc.headless
return Instance(impl)
}
// -----------------------------------------------------------------------------
// Adapter procedures
// -----------------------------------------------------------------------------
Vulkan_Adapter_Impl :: struct {
// Base
using base: Adapter_Base,
// Initialization
vk_physical_device: vk.PhysicalDevice,
features_10: vk.PhysicalDeviceFeatures,
features_11: vk.PhysicalDeviceVulkan11Features,
features_12: vk.PhysicalDeviceVulkan12Features,
features_13: vk.PhysicalDeviceVulkan13Features,
}
@(require_results)
vk_adapter_get_info :: proc(
adapter: Adapter,
allocator := context.allocator,
loc: runtime.Source_Code_Location,
) -> (
info: Adapter_Info,
) {
impl := get_impl(Vulkan_Adapter_Impl, adapter, loc)
device_properties2 := vk.PhysicalDeviceProperties2 {
sType = .PHYSICAL_DEVICE_PROPERTIES_2,
}
driver_properties := vk.PhysicalDeviceDriverProperties {
sType = .PHYSICAL_DEVICE_DRIVER_PROPERTIES,
}
device_properties2.pNext = &driver_properties
// Get properties
vk.GetPhysicalDeviceProperties2(impl.vk_physical_device, &device_properties2)
// Convert byte arrays to strings
device_name := strings.string_from_null_terminated_ptr(
&device_properties2.properties.deviceName[0],
len(device_properties2.properties.deviceName),
)
if device_name != "" {
info.name = strings.clone_from(device_name, allocator)
}
driver_name := strings.string_from_null_terminated_ptr(
&driver_properties.driverName[0],
len(driver_properties.driverName),
)
if driver_name != "" {
info.driver = strings.clone_from(driver_name, allocator)
}
driver_info := strings.string_from_null_terminated_ptr(
&driver_properties.driverInfo[0],
len(driver_properties.driverInfo),
)
if driver_info != "" {
info.driver_info = strings.clone_from(driver_info, allocator)
}
// Convert device type to our enum
#partial switch device_properties2.properties.deviceType {
case .INTEGRATED_GPU:
info.device_type = .Integrated_Gpu
case .DISCRETE_GPU:
info.device_type = .Discrete_Gpu
case .VIRTUAL_GPU, .CPU:
info.device_type = .Cpu
case:
info.device_type = .Other
}
info.vendor = device_properties2.properties.vendorID
info.device = device_properties2.properties.deviceID
info.backend = .Vulkan
return
}
vk_adapter_info_free_members :: proc(self: Adapter_Info, allocator := context.allocator) {
context.allocator = allocator
if len(self.name) > 0 do delete(self.name)
if len(self.driver) > 0 do delete(self.driver)
if len(self.driver_info) > 0 do delete(self.driver_info)
}
@private
vk_adapter_get_features_impl :: proc(impl: ^Vulkan_Adapter_Impl) -> (features: Features) {
return
}
vk_adapter_get_features :: proc(adapter: Adapter, loc := #caller_location) -> (features: Features) {
impl := get_impl(Vulkan_Adapter_Impl, adapter, loc)
return impl.features
}
@private
vk_adapter_get_limits_impl :: proc(impl: ^Vulkan_Adapter_Impl) -> (ret: Limits) {
subgroup_props := vk.PhysicalDeviceSubgroupProperties{
sType = .PHYSICAL_DEVICE_SUBGROUP_PROPERTIES,
}
vk_properties := vk.PhysicalDeviceProperties2{
sType = .PHYSICAL_DEVICE_PROPERTIES_2,
pNext = &subgroup_props,
}
vk.GetPhysicalDeviceProperties2(impl.vk_physical_device, &vk_properties)
properties := vk_properties.properties
limits := properties.limits
// Texture limits
ret.max_texture_dimension_1d = limits.maxImageDimension1D
ret.max_texture_dimension_2d = limits.maxImageDimension2D
ret.max_texture_dimension_3d = limits.maxImageDimension3D
ret.max_texture_array_layers = limits.maxImageArrayLayers
// Descriptor/Binding limits
ret.max_bind_groups = max(limits.maxBoundDescriptorSets, 4)
ret.max_bind_groups_plus_vertex_buffers = max(
limits.maxBoundDescriptorSets + limits.maxVertexInputBindings, 24)
ret.max_bindings_per_bind_group = 1000
// Dynamic buffer limits
ret.max_dynamic_uniform_buffers_per_pipeline_layout =
limits.maxDescriptorSetUniformBuffersDynamic
ret.max_dynamic_storage_buffers_per_pipeline_layout =
limits.maxDescriptorSetStorageBuffersDynamic
// Per-shader-stage limits
ret.max_sampled_textures_per_shader_stage = limits.maxPerStageDescriptorSampledImages
ret.max_samplers_per_shader_stage = limits.maxPerStageDescriptorSamplers
ret.max_storage_buffers_per_shader_stage = limits.maxPerStageDescriptorStorageBuffers
ret.max_storage_textures_per_shader_stage = limits.maxPerStageDescriptorStorageImages
ret.max_uniform_buffers_per_shader_stage = limits.maxPerStageDescriptorUniformBuffers
// Buffer limits
ret.max_uniform_buffer_binding_size = u64(limits.maxUniformBufferRange)
ret.max_storage_buffer_binding_size = u64(limits.maxStorageBufferRange)
ret.min_uniform_buffer_offset_alignment = u32(limits.minUniformBufferOffsetAlignment)
ret.min_storage_buffer_offset_alignment = u32(limits.minStorageBufferOffsetAlignment)
// On Linux/Android non-NVIDIA drivers, there's a known issue where very
// large buffer sizes (>2GB) can cause problems, so we limit it to max(i32).
// NVIDIA drivers and other platforms can handle the full size.
max_buffer_size: u64
when ODIN_OS == .Linux {
is_nvidia := properties.vendorID == NVIDIA_VENDOR
if !is_nvidia {
max_buffer_size = u64(max(i32))
} else {
max_buffer_size = 1 << 52
}
} else {
max_buffer_size = 1 << 52
}
ret.max_buffer_size = max_buffer_size
// Vertex input limits
ret.max_vertex_buffers = limits.maxVertexInputBindings
ret.max_vertex_attributes = limits.maxVertexInputAttributes
ret.max_vertex_buffer_array_stride = limits.maxVertexInputBindingStride
// Inter-stage limits
ret.max_inter_stage_shader_variables = min(
limits.maxVertexOutputComponents,
limits.maxFragmentInputComponents) / 4 // Divide by 4 for vec4s
// Color attachment limits
ret.max_color_attachments = limits.maxColorAttachments
ret.max_color_attachment_bytes_per_sample =
limits.maxColorAttachments * MAX_TARGET_PIXEL_BYTE_COST
// Compute shader limits
ret.max_compute_workgroup_storage_size = limits.maxComputeSharedMemorySize
ret.max_compute_invocations_per_workgroup = limits.maxComputeWorkGroupInvocations
ret.max_compute_workgroup_size_x = limits.maxComputeWorkGroupSize[0]
ret.max_compute_workgroup_size_y = limits.maxComputeWorkGroupSize[1]
ret.max_compute_workgroup_size_z = limits.maxComputeWorkGroupSize[2]
ret.max_compute_workgroups_per_dimension = limits.maxComputeWorkGroupCount[0]
// Subgroup limits
ret.min_subgroup_size = subgroup_props.subgroupSize
ret.max_subgroup_size = subgroup_props.subgroupSize
// Push constant limits
ret.max_push_constant_size = limits.maxPushConstantsSize
// Non-sampler bindings (sum of all non-sampler descriptors)
ret.max_non_sampler_bindings = min(
limits.maxPerStageDescriptorUniformBuffers +
limits.maxPerStageDescriptorStorageBuffers +
limits.maxPerStageDescriptorSampledImages +
limits.maxPerStageDescriptorStorageImages, 1000000)
// TODO: ray tracing
ret.max_task_workgroup_total_count = 0
ret.max_task_workgroups_per_dimension = 0
ret.max_mesh_output_layers = 0
ret.max_mesh_multiview_count = 0
ret.max_blas_primitive_count = 0
ret.max_blas_geometry_count = 0
ret.max_tlas_instance_count = 0
ret.max_acceleration_structures_per_shader_stage = 0
return
}
vk_adapter_get_limits :: proc(adapter: Adapter, loc := #caller_location) -> (ret: Limits) {
impl := get_impl(Vulkan_Adapter_Impl, adapter, loc)
return impl.limits
}
vk_adapter_request_device :: proc(
adapter: Adapter,
callback_info: Request_Device_Callback_Info,
descriptor: Maybe(Device_Descriptor) = nil,
loc := #caller_location,
) {
impl := get_impl(Vulkan_Adapter_Impl, adapter, loc)
instance_impl := get_impl(Vulkan_Instance_Impl, impl.instance, loc)
invoke_callback :: proc(
callback_info: Request_Device_Callback_Info,
status: Request_Device_Status,
device: Device,
message: string,
) {
callback_info.callback(
status,
device,
message,
callback_info.userdata1,
callback_info.userdata2,
)
}
ta := context.temp_allocator
runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = impl.allocator == ta)
extension_count: u32
vk_check(vk.EnumerateDeviceExtensionProperties(impl.vk_physical_device, nil, &extension_count, nil))
available_extensions := make([]vk.ExtensionProperties, extension_count, ta)
vk_check(vk.EnumerateDeviceExtensionProperties(
impl.vk_physical_device, nil, &extension_count, raw_data(available_extensions)))
queue_family_count: u32
vk.GetPhysicalDeviceQueueFamilyProperties(impl.vk_physical_device, &queue_family_count, nil)
queue_families := make([]vk.QueueFamilyProperties, queue_family_count, ta)
vk.GetPhysicalDeviceQueueFamilyProperties(
impl.vk_physical_device, &queue_family_count, raw_data(queue_families))
is_extension_available :: proc(
available_extensions: []vk.ExtensionProperties,
required: string,
) -> bool {
for &available in available_extensions {
ext_name := byte_arr_str(&available.extensionName)
if ext_name == required { return true }
}
return false
}
// Chain of extensions
pnext_chain: sa.Small_Array(4, ^vk.BaseOutStructure)
// Extension names to enable
extensions: sa.Small_Array(10, cstring)
// Extension `VK_KHR_swapchain` is required to present surface
if !instance_impl.headless {
sa.push_back(&extensions, vk.KHR_SWAPCHAIN_EXTENSION_NAME)
}
// Core Vulkan 1.2 features
enabled_features_12 := vk.PhysicalDeviceVulkan12Features {
sType = .PHYSICAL_DEVICE_VULKAN_1_2_FEATURES,
descriptorIndexing = true,
descriptorBindingVariableDescriptorCount = true,
runtimeDescriptorArray = true,
bufferDeviceAddress = true,
timelineSemaphore = true,
drawIndirectCount = true,
}
sa.push_back(&pnext_chain, cast(^vk.BaseOutStructure)&enabled_features_12)
// Core Vulkan 1.3 features
enabled_features_13 := vk.PhysicalDeviceVulkan13Features {
sType = .PHYSICAL_DEVICE_VULKAN_1_3_FEATURES,
synchronization2 = true,
dynamicRendering = true,
maintenance4 = true,
}
sa.push_back(&pnext_chain, cast(^vk.BaseOutStructure)&enabled_features_13)
// Vulkan 1.0 features
enabled_features_10 := vk.PhysicalDeviceFeatures {
samplerAnisotropy = true,
shaderClipDistance = true,
shaderCullDistance = true,
}
// Enables relaxed present timing and fence-based release of swapchain
// images for lower latency
has_EXT_swapchain_maintenance1: bool
swapchain_maintenance1_features := vk.PhysicalDeviceSwapchainMaintenance1FeaturesEXT {
sType = .PHYSICAL_DEVICE_SWAPCHAIN_MAINTENANCE_1_FEATURES_EXT,
swapchainMaintenance1 = true,
}
if is_extension_available(available_extensions[:], vk.EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) {
has_EXT_swapchain_maintenance1 = true
sa.push_back(&extensions, vk.EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME)
sa.push_back(&pnext_chain, cast(^vk.BaseOutStructure)&swapchain_maintenance1_features)
}
// Provides detailed GPU fault reporting (page faults, driver errors).
has_EXT_device_fault: bool
device_fault_features := vk.PhysicalDeviceFaultFeaturesEXT {
sType = .PHYSICAL_DEVICE_FAULT_FEATURES_EXT,
deviceFault = true,
}
if is_extension_available(available_extensions[:], vk.EXT_DEVICE_FAULT_EXTENSION_NAME) {
has_EXT_device_fault = true
sa.push_back(&extensions, vk.EXT_DEVICE_FAULT_EXTENSION_NAME)
sa.push_back(&pnext_chain, cast(^vk.BaseOutStructure)&device_fault_features)
}
has_KHR_maintenance5: bool
if is_extension_available(available_extensions[:], vk.KHR_MAINTENANCE_5_EXTENSION_NAME) {
has_KHR_maintenance5 = true
sa.push_back(&extensions, vk.KHR_MAINTENANCE_5_EXTENSION_NAME)
}
// Allows setting HDR metadata (e.g., max luminance, color primaries) on
// swapchains for HDR displays
has_EXT_hdr_metadata: bool
if is_extension_available(available_extensions[:], vk.EXT_HDR_METADATA_EXTENSION_NAME) {
has_EXT_hdr_metadata = true
sa.push_back(&extensions, vk.EXT_HDR_METADATA_EXTENSION_NAME)
}
find_queue_family_index :: proc(
vk_physical_device: vk.PhysicalDevice,
queue_families: []vk.QueueFamilyProperties,
flags: vk.QueueFlags,
) -> (
index: u32,
) {
// Helper to find a dedicated queue family
find_dedicated_queue_family_index :: proc(
props: []vk.QueueFamilyProperties,
require: vk.QueueFlags,
avoid: vk.QueueFlags,
) -> u32 {
for &prop, i in props {
is_suitable := (prop.queueFlags >= require)
is_dedicated := (prop.queueFlags & avoid) == {}
if prop.queueCount > 0 && is_suitable && is_dedicated {
return u32(i)
}
}
return vk.QUEUE_FAMILY_IGNORED
}
// Try to find dedicated compute queue (no graphics)
if .COMPUTE in flags {
q := find_dedicated_queue_family_index(
queue_families,
flags,
{.GRAPHICS},
)
if q != vk.QUEUE_FAMILY_IGNORED {
return q
}
}
// Try to find dedicated transfer queue (no graphics)
if .TRANSFER in flags {
q := find_dedicated_queue_family_index(
queue_families,
flags,
{.GRAPHICS},
)
if q != vk.QUEUE_FAMILY_IGNORED {
return q
}
}
// Fall back to any suitable queue (no avoidance)
return find_dedicated_queue_family_index(queue_families, flags, {})
}
graphics_queue_family_index :=
find_queue_family_index(impl.vk_physical_device, queue_families, { .GRAPHICS })
ensure(graphics_queue_family_index !=
vk.QUEUE_FAMILY_IGNORED, "GRAPHICS queue is not supported", loc)
compute_queue_family_index :=
find_queue_family_index(impl.vk_physical_device, queue_families, { .COMPUTE })
ensure(compute_queue_family_index !=
vk.QUEUE_FAMILY_IGNORED, "COMPUTE queue is not supported", loc)
default_queue_priority : f32 = 1.0
queue_setup := [2]vk.DeviceQueueCreateInfo {
{
sType = .DEVICE_QUEUE_CREATE_INFO,
queueFamilyIndex = graphics_queue_family_index,
queueCount = 1,
pQueuePriorities = &default_queue_priority,
},
{
sType = .DEVICE_QUEUE_CREATE_INFO,
queueFamilyIndex = compute_queue_family_index,
queueCount = 1,
pQueuePriorities = &default_queue_priority,
},
}
num_queues := queue_setup[0].queueFamilyIndex == queue_setup[1].queueFamilyIndex ? 1 : 2
device_create_info := vk.DeviceCreateInfo {
sType = .DEVICE_CREATE_INFO,
queueCreateInfoCount = u32(num_queues),
pQueueCreateInfos = raw_data(queue_setup[:]),
enabledExtensionCount = u32(sa.len(extensions)),
ppEnabledExtensionNames = raw_data(sa.slice(&extensions)),
pEnabledFeatures = &enabled_features_10,
}
vk_setup_pnext_chain(&device_create_info, sa.slice(&pnext_chain))
vk_device: vk.Device
vk_check(vk.CreateDevice(impl.vk_physical_device, &device_create_info, nil, &vk_device))
vk.load_proc_addresses_device(vk_device)
vk_set_debug_object_name(
vk_device, .DEVICE, u64(uintptr(vk_device)), "Device: impl.vk_device")
device := adapter_new_handle(Vulkan_Device_Impl, adapter, loc)
device.heap_alloc = runtime.default_allocator()
device.backend = .Vulkan
device.shader_formats = { .Spirv }
device.vk_physical_device = impl.vk_physical_device
device.vk_device = vk_device
device.has_EXT_hdr_metadata = has_EXT_hdr_metadata
device.has_EXT_swapchain_maintenance1 = has_EXT_swapchain_maintenance1
device.has_EXT_device_fault = has_EXT_device_fault
device.has_KHR_maintenance5 = has_KHR_maintenance5
vk_graphics_queue: vk.Queue
vk.GetDeviceQueue(vk_device, graphics_queue_family_index, 0, &vk_graphics_queue)
vk_compute_queue: vk.Queue
vk.GetDeviceQueue(vk_device, compute_queue_family_index, 0, &vk_compute_queue)
// Set device queues
device.queue = device_new_handle(Vulkan_Queue_Impl, Device(device), loc)
device.queue.queues = {
.Graphics = {
graphics_queue_family_index, vk_graphics_queue,
},
.Compute = {
compute_queue_family_index, vk_compute_queue,
},
}
device.queue.pending_writes.allocator = device.allocator
// Set command encoder defaults
device.encoder = Vulkan_Command_Encoder_Impl {
vk_device = device.vk_device,
vk_queue = vk_graphics_queue,
available_command_buffers = VK_MAX_COMMAND_BUFFERS,
submit_counter = 1,
last_submit_semaphore = { sType = .SEMAPHORE_SUBMIT_INFO, stageMask = { .ALL_COMMANDS } },
wait_semaphore = { sType = .SEMAPHORE_SUBMIT_INFO, stageMask = { .ALL_COMMANDS } },
signal_semaphore = { sType = .SEMAPHORE_SUBMIT_INFO, stageMask = { .ALL_COMMANDS } },
}
command_pool_info := vk.CommandPoolCreateInfo {
sType = .COMMAND_POOL_CREATE_INFO,
flags = { .RESET_COMMAND_BUFFER, .TRANSIENT },
queueFamilyIndex = graphics_queue_family_index,
}
vk_check(vk.CreateCommandPool(
device.vk_device, &command_pool_info, nil, &device.encoder.vk_command_pool))
allocate_info := vk.CommandBufferAllocateInfo {
sType = .COMMAND_BUFFER_ALLOCATE_INFO,
commandPool = device.encoder.vk_command_pool,
level = .PRIMARY,
commandBufferCount = 1,
}
encoder_label := "Device: impl.encoder"
// for i in 0 ..< u32(VK_MAX_COMMAND_BUFFERS) {
for i : u32 = 0; i != VK_MAX_COMMAND_BUFFERS; i += 1 {
buf := &device.encoder.buffers[i]
buf.device = Device(device)
buf.vk_device = device.vk_device
command_allocator_init(&buf.cmd_allocator, device.allocator)
vk_deletion_queue_init(&buf.resources, device.vk_device, device.heap_alloc)
// Name the synchronization objects for debugging
semaphore_name: [256]u8
fence_name: [256]u8
semaphore_name_str := fmt.bprintf(
semaphore_name[:], "Semaphore: %s (cmdbuf %d)", encoder_label, i)
fence_name_str := fmt.bprintf(fence_name[:], "Fence: %s (cmdbuf %d)", encoder_label, i)
// Create synchronization primitives
buf.vk_semaphore = vk_create_semaphore(device.vk_device, semaphore_name_str)
buf.vk_fence = vk_create_fence(device.vk_device, fence_name_str)
// Allocate the command buffer
vk_check(vk.AllocateCommandBuffers(
device.vk_device,
&allocate_info,
&buf.vk_cmd_buf_allocated,
))
// Store buffer index
buf.handle.buffer_index = i