-
Notifications
You must be signed in to change notification settings - Fork 40
/
shader_object.cpp
4162 lines (3545 loc) · 182 KB
/
shader_object.cpp
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
/*
* Copyright 2023 Nintendo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// clang-format off
#include <cassert>
#include <cctype>
#include <cstring>
#include <chrono>
#include <bitset>
#include <utility>
#include <mutex>
#include <shared_mutex>
#include <functional>
#include <vector>
#include <vulkan/vulkan.h>
#include <vulkan/vk_layer.h>
#include "log.h"
#include "vk_safe_struct.h"
#include "vk_api_hash.h"
#include "vk_layer_config.h"
// Required by vk_safe_struct
std::vector<std::pair<uint32_t, uint32_t>> custom_stype_info{};
#define SHADER_OBJECT_BINARY_VERSION 1
//#define ENABLE_DEBUG_LOG
//#define DEBUG_LOG_TO_OUTPUT
#if defined(ENABLE_DEBUG_LOG)
#if defined(DEBUG_LOG_TO_OUTPUT)
#define WIN32_MEAN_AND_LEAN
#if !defined(NOMINMAX)
#define NOMINMAX
#endif
#include <Windows.h>
#define DEBUG_LOG(...) \
{ \
char msg[256] = {}; \
sprintf(msg, "[VkLayer_khronos_shader_object] " __VA_ARGS__); \
OutputDebugString(msg); \
}
#else
#define DEBUG_LOG(...) \
fprintf(stderr, "[VkLayer_khronos_shader_object] " __VA_ARGS__); \
fflush(stderr)
#endif
#else
#define DEBUG_LOG(...)
#endif
#define ASSERT_VK_FALSE(state) ASSERT((state) == VK_FALSE)
#define ASSERT_VK_TRUE(state) ASSERT((state) == VK_TRUE)
#define UNIMPLEMENTED() ASSERT(!"Unimplemented")
#define UNUSED(x) ((void)x)
namespace shader_object {
static const char* kLayerName = "VkLayer_khronos_shader_object";
static const VkExtensionProperties kExtensionProperties = {VK_EXT_SHADER_OBJECT_EXTENSION_NAME, VK_EXT_SHADER_OBJECT_SPEC_VERSION};
static const char* const kEnvarForceEnable =
#if defined(__ANDROID__)
"debug.vulkan.shader_object.force_enable";
#else
"VK_SHADER_OBJECT_FORCE_ENABLE";
#endif
static const char* const kLayerSettingsForceEnable = "khronos_shader_object.force_enable";
static void string_tolower(std::string &s) {
for (auto& c: s) {
c = tolower(c);
}
}
static bool GetForceEnable() {
bool result = false;
std::string setting = GetEnvironment(kEnvarForceEnable);
if (setting.empty()) {
setting = GetLayerOption(kLayerSettingsForceEnable);
}
if (!setting.empty()) {
string_tolower(setting);
if (setting == "true") {
result = true;
} else {
result = std::atoi(setting.c_str()) != 0;
}
}
return result;
}
static VKAPI_ATTR void* VKAPI_CALL DefaultAlloc(void*, size_t size, size_t alignment, VkSystemAllocationScope) {
return std::malloc(size);
}
static VKAPI_ATTR void VKAPI_CALL DefaultFree(void*, void* pMem) { std::free(pMem); }
static VKAPI_ATTR void* VKAPI_CALL DefaultRealloc(void*, void* pOriginal, size_t size, size_t alignment, VkSystemAllocationScope) {
return std::realloc(pOriginal, size);
}
static const VkAllocationCallbacks kDefaultAllocator = {
nullptr, DefaultAlloc, DefaultRealloc, DefaultFree, nullptr, nullptr,
};
template <typename T>
T* AllocateArray(VkAllocationCallbacks const& allocator, uint32_t count, VkSystemAllocationScope scope) {
return static_cast<T*>(allocator.pfnAllocation(allocator.pUserData, sizeof(T) * count, alignof(T), scope));
}
template <typename T, uint32_t N>
constexpr uint32_t GetArrayLength(const T (&arr)[N]) {
return N;
}
constexpr uint32_t CalculateRequiredGroupSize(int x, int group_size) { return (x + group_size - 1) / group_size; }
static uint64_t ChecksumFletcher64(uint32_t const* data, size_t count) {
constexpr uint32_t mod_value = 0xFFFFFFFF;
uint64_t num1 = 0;
uint64_t num2 = 0;
for (size_t i = 0; i < count; ++i) {
num1 = (num1 + data[i]) % mod_value;
num2 = (num2 + num1) % mod_value;
}
return (num1 << 32) | num2;
}
#include "generated/shader_object_constants.h"
#include "generated/shader_object_entry_points_x_macros.inl"
template <typename T>
class ReaderWriterContainer {
public:
ReaderWriterContainer() = default;
ReaderWriterContainer(T&& data) : data_(std::move(data)) {}
T const& GetDataForReading(std::shared_lock<std::shared_mutex>& lock) {
lock = std::shared_lock<std::shared_mutex>(mutex_);
return data_;
}
T& GetDataForWriting(std::unique_lock<std::shared_mutex>& lock) {
lock = std::unique_lock<std::shared_mutex>(mutex_);
return data_;
}
T& GetDataUnsafe() {
return data_;
}
private:
std::shared_mutex mutex_;
T data_;
};
template <typename T, VkSystemAllocationScope Scope>
class DynamicArray {
public:
DynamicArray(VkAllocationCallbacks allocator) : allocator_(allocator) {}
DynamicArray(VkAllocationCallbacks allocator, uint32_t initial_size) : DynamicArray(allocator) { Resize(initial_size); }
~DynamicArray() { CleanupData(); }
class Iterator {
public:
T& operator*() { return (*array_)[index_]; }
T* operator->() { return &(*array_)[index_]; }
void operator++() { ++index_; }
bool operator==(Iterator const& o) { return array_ == o.array_ && index_ == o.index_; }
bool operator!=(Iterator const& o) { return !(*this == o); }
private:
friend class DynamicArray<T, Scope>;
Iterator(DynamicArray& array, uint32_t index) : array_(&array), index_(index) {}
DynamicArray* array_;
uint32_t index_;
};
DynamicArray(DynamicArray const& o) { *this = o; }
DynamicArray(DynamicArray&& o) noexcept { *this = std::move(o); }
DynamicArray& operator=(DynamicArray const& o) {
CleanupData();
allocator_ = o.allocator_;
used_ = o.used_;
capacity_ = o.capacity_;
if (o.used_ > 0) {
data_ = (T*)allocator_.pfnAllocation(allocator_.pUserData, sizeof(T) * capacity_, alignof(T), Scope);
for (uint32_t i = 0; i < used_; ++i) {
new (data_ + i) T(o.data_[i]);
}
}
return *this;
}
DynamicArray& operator=(DynamicArray&& o) noexcept {
CleanupData();
allocator_ = o.allocator_;
used_ = o.used_;
capacity_ = o.capacity_;
data_ = o.data_;
o.data_ = nullptr;
return *this;
}
T& operator[](uint32_t i) {
ASSERT(i < used_);
return data_[i];
}
T const& operator[](uint32_t i) const {
ASSERT(i < used_);
return data_[i];
}
void Resize(uint32_t new_size) {
if (!data_) {
capacity_ = new_size;
used_ = new_size;
data_ = (T*)allocator_.pfnAllocation(allocator_.pUserData, sizeof(T) * capacity_, alignof(T),
VkSystemAllocationScope::VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
data_ = new (data_) T[new_size];
return;
}
if (new_size > capacity_) {
capacity_ = new_size;
data_ = (T*)allocator_.pfnReallocation(allocator_.pUserData, data_, sizeof(T) * capacity_, alignof(T),
VkSystemAllocationScope::VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
new (data_ + used_) T[new_size - used_];
used_ = new_size;
return;
}
for (uint32_t i = new_size; i < used_; ++i) {
data_[i].~T();
}
used_ = new_size;
}
void Clear() { Resize(0); }
uint32_t GetUsed() const { return used_; }
bool IsEmpty() const { return GetUsed() == 0; }
T* GetPointer() const { return data_; }
Iterator begin() { return Iterator(*this, 0); }
Iterator end() { return Iterator(*this, used_); }
private:
// Destruct and deallocate all data if it's there
void CleanupData() {
if (data_) {
for (uint32_t i = 0; i < used_; ++i) {
data_[i].~T();
}
allocator_.pfnFree(allocator_.pUserData, data_);
data_ = nullptr;
}
}
T* data_ = nullptr;
uint32_t capacity_ = 0;
uint32_t used_ = 0;
VkAllocationCallbacks allocator_;
};
template <typename Key, typename Value, bool UseMutex = true>
class HashMap {
public:
class Iterator {
public:
struct ValuePair {
Key const& key;
Value& value;
};
Iterator(Iterator const& o) { *this = o; }
Iterator& operator=(Iterator const& o) {
map_ = o.map_;
index_ = o.index_;
return *this;
}
ValuePair operator*() {
HashMap::Slot& slot = map_->slots_[index_];
return {slot.key, slot.value};
};
void operator++() {
if (index_ < map_->slots_.GetUsed()) {
++index_;
}
while (index_ < map_->slots_.GetUsed() && map_->slots_[index_].state != Slot::State::OCCUPIED) {
++index_;
}
}
bool operator==(Iterator const& o) { return map_ == o.map_ && index_ == o.index_; }
bool operator!=(Iterator const& o) { return !(*this == o); }
Key const& GetKey() { return map_->slots_[index_].key; }
Value& GetValue() { return map_->slots_[index_].value; }
private:
friend class HashMap<Key, Value, UseMutex>;
Iterator(HashMap& map, uint32_t start_index) : map_(&map), index_(start_index) {}
HashMap* map_;
uint32_t index_;
};
HashMap() : allocator_(kDefaultAllocator), slots_(kDefaultAllocator) {}
HashMap(HashMap const& o) { *this = o; };
HashMap(HashMap&& o) noexcept { *this = std::move(o); };
HashMap& operator=(HashMap const& o) {
allocator_ = o.allocator_;
slots_ = o.slots_;
num_entries_ = o.num_entries_;
hasher_ = o.hasher_;
return *this;
}
HashMap& operator=(HashMap&& o) noexcept {
if (this == &o) {
return *this;
}
allocator_ = std::move(o.allocator_);
slots_ = std::move(o.slots_);
num_entries_ = std::move(o.num_entries_);
hasher_ = std::move(o.hasher_);
return *this;
}
void Add(Key const& key, Value const& value) {
std::unique_lock<std::mutex> lock = UseMutex ? std::unique_lock<std::mutex>(mutex_) : std::unique_lock<std::mutex>{};
// See if we're updating an existing key
auto search_it = FindNoLock(key);
if (search_it != end()) {
search_it.GetValue() = value;
return;
}
// Otherwise, we're adding a key
RehashIfNecessary(num_entries_ + 1);
const size_t hashed_key = hasher_(key);
// Find which slot we should insert key and value into
Slot* found_slot = nullptr;
uint32_t index = (uint32_t)(hashed_key % slots_.GetUsed());
for (;;) {
Slot& slot = slots_[index];
if (slot.state != Slot::State::OCCUPIED) {
found_slot = &slot;
break;
}
index = (index + 1) % slots_.GetUsed();
}
// Fill the slot
++num_entries_;
found_slot->key = key;
found_slot->value = value;
found_slot->state = Slot::State::OCCUPIED;
found_slot->hashed_key = hashed_key;
}
// Might rehash
void Remove(Key const& key) {
std::unique_lock<std::mutex> lock = UseMutex ? std::unique_lock<std::mutex>(mutex_) : std::unique_lock<std::mutex>{};
auto it = FindNoLock(key);
if (it != end()) {
RemoveNoLock(it);
RehashIfNecessary(num_entries_);
}
}
// Does not rehash
Iterator Remove(Iterator it) {
std::unique_lock<std::mutex> lock = UseMutex ? std::unique_lock<std::mutex>(mutex_) : std::unique_lock<std::mutex>{};
return RemoveNoLock(it);
}
void RemoveAllWithValue(Value const& value) {
std::unique_lock<std::mutex> lock = UseMutex ? std::unique_lock<std::mutex>(mutex_) : std::unique_lock<std::mutex>{};
for (auto it = begin(); it != end();) {
if (it.GetValue() == value) {
it = RemoveNoLock(it);
} else {
++it;
}
}
}
void RemoveAllWithValueCustom(Value const& value, std::function<void(Key const&, Value const&)> const& custom_function) {
std::unique_lock<std::mutex> lock = UseMutex ? std::unique_lock<std::mutex>(mutex_) : std::unique_lock<std::mutex>{};
for (auto it = begin(); it != end();) {
if (it.GetValue() == value) {
custom_function(it.GetKey(), it.GetValue());
it = RemoveNoLock(it);
} else {
++it;
}
}
}
void Clear() {
slots_.Clear();
num_entries_ = 0;
}
const Value& Get(Key const& key) { return *GetOrNullptr(key); }
const Value* GetOrNullptr(Key const& key) const {
std::unique_lock<std::mutex> lock = UseMutex ? std::unique_lock<std::mutex>(mutex_) : std::unique_lock<std::mutex>{};
if (slots_.IsEmpty()) {
return nullptr;
}
const size_t hashed_key = hasher_(key);
const uint32_t start_index = (uint32_t)(hashed_key % slots_.GetUsed());
uint32_t index = start_index;
for (;;) {
const Slot& slot = slots_[index];
if (slot.state == Slot::State::OCCUPIED && slot.key == key) {
// We found the key
return &slots_[index].value;
}
if (slot.state == Slot::State::UNOCCUPIED) {
// If we came across an unoccupied slot, we've gone past the end of the cluster
// i.e. we didn't find the key
return nullptr;
}
// If we reach here, we're still in the cluster
// i.e. this is a deleted slot or it's an occupied slot with the wrong key
index = (index + 1) % slots_.GetUsed();
if (index == start_index) {
// We searched through all the slots and didn't find it
return nullptr;
}
}
}
Iterator Find(Key const& key) {
std::unique_lock<std::mutex> lock = UseMutex ? std::unique_lock<std::mutex>(mutex_) : std::unique_lock<std::mutex>{};
return FindNoLock(key);
}
uint32_t NumSlots() const { return slots_.GetUsed(); }
uint32_t NumEntries() const { return num_entries_; }
Iterator begin() {
auto it = Iterator(*this, 0);
// Start the iterator at first valid slot
if (!slots_.IsEmpty() && slots_[0].state != Slot::State::OCCUPIED) {
++it;
}
return it;
}
Iterator end() { return Iterator(*this, slots_.GetUsed()); }
private:
friend class HashMap::Iterator;
struct Slot {
enum class State { UNOCCUPIED, OCCUPIED, DELETED };
size_t hashed_key{};
Key key{};
Value value{};
State state = State::UNOCCUPIED;
};
Iterator FindNoLock(Key const& key) {
if (slots_.IsEmpty()) {
return end();
}
const size_t hashed_key = hasher_(key);
const uint32_t start_index = (uint32_t)(hashed_key % slots_.GetUsed());
uint32_t index = start_index;
for (;;) {
Slot& slot = slots_[index];
if (slot.state == Slot::State::OCCUPIED && slot.key == key) {
// We found the key
return Iterator(*this, index);
}
if (slot.state == Slot::State::UNOCCUPIED) {
// If we came across an unoccupied slot, we've gone past the end of the cluster
// i.e. we didn't find the key
return end();
}
// If we reach here, we're still in the cluster
// i.e. this is a deleted slot or it's an occupied slot with the wrong key
index = (index + 1) % slots_.GetUsed();
if (index == start_index) {
// We searched through all the slots and didn't find it
return end();
}
}
}
Iterator RemoveNoLock(Iterator it) {
ASSERT(it.map_ == this);
if (it == end()) return it;
// Delete the slot specified by the iterator
slots_[it.index_].state = Slot::State::DELETED;
--num_entries_;
// Return iterator to next element
uint32_t next_index = (it.index_ + 1) % slots_.GetUsed();
Iterator next_it(*this, next_index);
if (slots_[next_index].state != Slot::State::OCCUPIED) {
++next_it;
}
return next_it;
}
static float CalculateLoadFactor(uint32_t num_entries, uint32_t num_buckets) { return num_entries / (float)num_buckets; }
// If the key exists, the slot is returned. Otherwise, the next unoccupied slot is returned
template <VkSystemAllocationScope Scope>
static Slot& FindSlotOrNextUnoccupied(DynamicArray<Slot, Scope>& slots, Key const& key, size_t hashed_key) {
uint32_t index = (uint32_t)(hashed_key % slots.GetUsed());
for (;;) {
Slot& slot = slots[index];
if ((slot.state == Slot::State::OCCUPIED && slot.key == key) || slot.state == Slot::State::UNOCCUPIED) {
return slot;
}
// Skip if it's a deleted slot or an occupied slot with wrong key
index = (index + 1) % slots.GetUsed();
}
}
void RehashIfNecessary(uint32_t entries) {
uint32_t required_slots = entries;
if (required_slots > slots_.GetUsed()) {
Resize(required_slots * 2);
return;
}
if (required_slots < slots_.GetUsed() / 4) {
Resize(slots_.GetUsed() / 2);
return;
}
}
void Resize(uint32_t new_size) {
DynamicArray<Slot, VK_SYSTEM_ALLOCATION_SCOPE_OBJECT> new_slots(allocator_, new_size);
for (Slot& old_slot : slots_) {
if (old_slot.state != Slot::State::OCCUPIED) {
continue;
}
Slot& found_slot = FindSlotOrNextUnoccupied(new_slots, old_slot.key, old_slot.hashed_key);
ASSERT(found_slot.state == Slot::State::UNOCCUPIED);
found_slot.key = std::move(old_slot.key);
found_slot.value = std::move(old_slot.value);
found_slot.state = Slot::State::OCCUPIED;
found_slot.hashed_key = old_slot.hashed_key;
}
std::swap(slots_, new_slots);
}
VkAllocationCallbacks allocator_;
DynamicArray<Slot, VK_SYSTEM_ALLOCATION_SCOPE_OBJECT> slots_;
uint32_t num_entries_ = 0;
std::hash<Key> hasher_;
mutable std::mutex mutex_;
};
// These LayerDispatch* structs hold pointers to the next layer's version of these functions so that we can call down the chain
struct LayerDispatchInstance {
#define ENTRY_POINT(name) PFN_vk##name name = nullptr;
#define ENTRY_POINT_ALIAS(alias, canon)
ENTRY_POINTS_INSTANCE
ADDITIONAL_INSTANCE_FUNCTIONS
#undef ENTRY_POINT_ALIAS
#undef ENTRY_POINT
void Initialize(VkInstance instance, PFN_vkGetInstanceProcAddr get_proc_addr) {
#define ENTRY_POINT_ALIAS(alias, canon) if (canon == nullptr) { canon = (PFN_vk##canon)get_proc_addr(instance, "vk" #alias); }
#define ENTRY_POINT(name) ENTRY_POINT_ALIAS(name, name)
ENTRY_POINTS_INSTANCE
ADDITIONAL_INSTANCE_FUNCTIONS
#undef ENTRY_POINT
#undef ENTRY_POINT_ALIAS
}
};
struct LayerDispatchDevice {
#define ENTRY_POINT(name) PFN_vk##name name = nullptr;
#define ENTRY_POINT_ALIAS(alias, canon)
ENTRY_POINTS_DEVICE
ADDITIONAL_DEVICE_FUNCTIONS
#undef ENTRY_POINT_ALIAS
#undef ENTRY_POINT
void Initialize(VkDevice device, PFN_vkGetDeviceProcAddr get_proc_addr) {
#define ENTRY_POINT_ALIAS(alias, canon) if (canon == nullptr) { canon = (PFN_vk##canon)get_proc_addr(device, "vk" #alias); }
#define ENTRY_POINT(name) ENTRY_POINT_ALIAS(name, name)
ENTRY_POINTS_DEVICE
ADDITIONAL_DEVICE_FUNCTIONS
#undef ENTRY_POINT
#undef ENTRY_POINT_ALIAS
}
};
enum ShaderType {
VERTEX_SHADER = 0,
FRAGMENT_SHADER,
TESSELLATION_CONTROL_SHADER,
TESSELLATION_EVALUATION_SHADER,
GEOMETRY_SHADER,
MESH_SHADER,
TASK_SHADER,
NUM_SHADERS
};
static ShaderType ShaderStageToShaderType(VkShaderStageFlagBits stage) {
switch (stage) {
case VK_SHADER_STAGE_VERTEX_BIT:
return VERTEX_SHADER;
case VK_SHADER_STAGE_FRAGMENT_BIT:
return FRAGMENT_SHADER;
case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
return TESSELLATION_CONTROL_SHADER;
case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
return TESSELLATION_EVALUATION_SHADER;
case VK_SHADER_STAGE_GEOMETRY_BIT:
return GEOMETRY_SHADER;
case VK_SHADER_STAGE_MESH_BIT_EXT:
return MESH_SHADER;
case VK_SHADER_STAGE_TASK_BIT_EXT:
return TASK_SHADER;
default:
ASSERT(false);
return NUM_SHADERS;
}
}
inline bool operator==(VkStencilOpState const& a, VkStencilOpState const& b) { return memcmp(&a, &b, sizeof(a)) == 0; }
inline bool operator==(VkPipelineColorBlendAttachmentState const& a, VkPipelineColorBlendAttachmentState const& b) {
return memcmp(&a, &b, sizeof(a)) == 0;
}
inline bool operator==(VkVertexInputAttributeDescription const& a, VkVertexInputAttributeDescription const& b) {
return memcmp(&a, &b, sizeof(a)) == 0;
}
inline bool operator==(VkVertexInputBindingDescription const& a, VkVertexInputBindingDescription const& b) {
return memcmp(&a, &b, sizeof(a)) == 0;
}
inline bool operator==(VkViewportSwizzleNV const& a, VkViewportSwizzleNV const& b) {
return memcmp(&a, &b, sizeof(a)) == 0;
}
class CommandBufferData;
static void UpdateDrawState(CommandBufferData& data, VkCommandBuffer commandBuffer);
// All relevant draw state for a single command buffer
struct Shader;
struct FullDrawStateData {
struct Limits {
Limits() {}
Limits(VkPhysicalDeviceProperties const& properties)
: max_color_attachments(properties.limits.maxColorAttachments),
max_vertex_input_attributes(properties.limits.maxVertexInputAttributes),
max_vertex_input_bindings(properties.limits.maxVertexInputBindings),
max_viewports(properties.limits.maxViewports) {}
uint32_t max_color_attachments{};
uint32_t max_vertex_input_attributes{};
uint32_t max_vertex_input_bindings{};
uint32_t max_viewports{};
};
// Key wraps a FullDrawStateData pointer so that it may be used as a key in a HashMap
class Key {
public:
Key() : draw_state_data_(nullptr), is_owner_(false) {}
~Key() {
if (is_owner_ && draw_state_data_) {
FullDrawStateData::Destroy(draw_state_data_);
draw_state_data_ = nullptr;
}
}
Key(Key const& o) {
// When a key is copied, the data that it wraps should be deep copied along with it
// This happens when they key is inserted into the HashMap
if (o.draw_state_data_) {
draw_state_data_ = FullDrawStateData::Copy(o.draw_state_data_);
is_owner_ = true;
} else {
draw_state_data_ = nullptr;
is_owner_ = false;
}
}
Key(Key&& o) noexcept : draw_state_data_(o.draw_state_data_), is_owner_(o.is_owner_) {
o.draw_state_data_ = nullptr;
o.is_owner_ = false;
}
Key& operator=(Key const& o) {
// See copy constructor
if (&o == this) {
return *this;
}
if (o.draw_state_data_) {
draw_state_data_ = FullDrawStateData::Copy(o.draw_state_data_);
is_owner_ = true;
} else {
draw_state_data_ = nullptr;
is_owner_ = false;
}
return *this;
}
Key& operator=(Key&& o) noexcept {
if (&o == this) {
return *this;
}
draw_state_data_ = o.draw_state_data_;
is_owner_ = o.is_owner_;
o.draw_state_data_ = nullptr;
o.is_owner_ = false;
return *this;
}
bool operator==(Key const& o) const {
return draw_state_data_ && o.draw_state_data_ && (*draw_state_data_ == *o.draw_state_data_);
}
FullDrawStateData* GetData() const {
return draw_state_data_;
}
private:
friend struct FullDrawStateData;
Key(FullDrawStateData* data) : draw_state_data_(data), is_owner_(false) {}
FullDrawStateData* draw_state_data_;
bool is_owner_ = false;
};
#include "generated/shader_object_full_draw_state_utility_functions.inl"
// memory must be at least GetSizeInBytes bytes
static void InitializeMemory(void* memory, VkPhysicalDeviceProperties const& properties) {
FullDrawStateData* state = new (memory) FullDrawStateData{};
Limits limits(properties);
SetInternalArrayPointers(state, limits);
state->limits_ = limits;
// Set default draw state for feature-rich pipeline compilation
VkPipelineColorBlendAttachmentState color_blend_attachment_state{
VK_TRUE,
VK_BLEND_FACTOR_SRC_COLOR,
VK_BLEND_FACTOR_DST_COLOR,
VK_BLEND_OP_ADD,
VK_BLEND_FACTOR_SRC_ALPHA,
VK_BLEND_FACTOR_DST_ALPHA,
VK_BLEND_OP_ADD,
VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT
};
state->SetColorBlendAttachmentState(0, color_blend_attachment_state);
state->SetColorAttachmentFormat(0, VK_FORMAT_R8G8B8A8_UNORM);
state->SetNumColorAttachments(1);
state->SetPrimitiveTopology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST);
state->SetPolygonMode(VK_POLYGON_MODE_FILL);
state->SetCullMode(VK_CULL_MODE_FRONT_BIT);
state->SetDepthCompareOp(VK_COMPARE_OP_LESS);
state->SetDepthTestEnable(VK_TRUE);
state->SetDepthWriteEnable(VK_TRUE);
state->SetDepthBoundsTestEnable(VK_TRUE);
state->SetStencilTestEnable(VK_TRUE);
}
static FullDrawStateData* Create(VkPhysicalDeviceProperties const& properties, VkAllocationCallbacks const& allocator) {
size_t bytes_to_allocate = GetSizeInBytes(properties);
auto state = static_cast<FullDrawStateData*>(allocator.pfnAllocation(allocator.pUserData, bytes_to_allocate, 0, VkSystemAllocationScope::VK_SYSTEM_ALLOCATION_SCOPE_DEVICE));
if (!state) {
return nullptr;
}
InitializeMemory(state, properties);
state->allocator_ = allocator;
return state;
}
static FullDrawStateData* Copy(FullDrawStateData const* o) {
size_t bytes_to_allocate = GetSizeInBytes(o->limits_);
auto allocator = kDefaultAllocator;
auto state = static_cast<FullDrawStateData*>(allocator.pfnAllocation(allocator.pUserData, bytes_to_allocate, 0, VkSystemAllocationScope::VK_SYSTEM_ALLOCATION_SCOPE_DEVICE));
if (!state) {
return nullptr;
}
memcpy(state, o, bytes_to_allocate);
SetInternalArrayPointers(state, o->limits_);
state->allocator_ = allocator;
return state;
}
static void Destroy(FullDrawStateData* pState) {
auto allocator = pState->allocator_;
pState->~FullDrawStateData();
allocator.pfnFree(allocator.pUserData, pState);
}
size_t GetHash() const {
if (dirty_hash_bits_.any()) {
for (uint32_t i = 0; i < dirty_hash_bits_.size(); ++i) {
if (!dirty_hash_bits_.test(i)) {
continue;
}
// undo previous partial hash
final_hash_ ^= partial_hashes_[i];
// compute new partial hash
partial_hashes_[i] = CalculatePartialHash((StateGroup)i);
// apply new partial hash
final_hash_ ^= partial_hashes_[i];
dirty_hash_bits_.reset(i);
}
}
return final_hash_;
}
Key GetKey() {
return Key(this);
}
void MarkDirty() { is_dirty_ = true; }
#include "generated/shader_object_full_draw_state_struct_members.inl"
private:
friend void UpdateDrawState(CommandBufferData& data, VkCommandBuffer commandBuffer);
FullDrawStateData() = default;
Limits limits_;
VkAllocationCallbacks allocator_;
mutable size_t final_hash_ = 0;
mutable size_t partial_hashes_[NUM_STATE_GROUPS]{};
mutable std::bitset<NUM_STATE_GROUPS> dirty_hash_bits_{0xFFFFFFFF};
mutable bool is_dirty_ = true;
};
} // namespace shader_object
namespace std {
template<>
struct hash<shader_object::FullDrawStateData::Key> {
std::size_t operator()(shader_object::FullDrawStateData::Key const& o) const {
shader_object::FullDrawStateData* data = o.GetData();
if (!data) {
return 0;
}
return data->GetHash();
}
};
} // namespace std
#if defined(__GNUC__) && __GNUC__ >= 4
#define VEL_EXPORT __attribute__((visibility("default")))
#else
#define VEL_EXPORT
#endif
namespace shader_object {
struct PartialPipeline {
// The precompiled partial pipeline
VkPipeline pipeline = VK_NULL_HANDLE;
// Information about the pipeline
FullDrawStateData* draw_state;
VkGraphicsPipelineLibraryFlagBitsEXT library_flags;
VkShaderStageFlags shader_stages;
};
struct DeviceData;
struct Shader {
struct PrivateDataSlotPair {
VkPrivateDataSlot slot;
uint64_t data;
};
static VkResult Create(DeviceData const& deviceData, VkShaderCreateInfoEXT const& createInfo, VkAllocationCallbacks const& allocator, Shader** ppShader);
static void Destroy(DeviceData const& deviceData, Shader* pShader, VkAllocationCallbacks const& allocator);
uint64_t GetPrivateData(DeviceData const& device_data, VkPrivateDataSlot slot);
void SetPrivateData(DeviceData const& device_data, VkPrivateDataSlot slot, uint64_t data);
const char* name;
size_t name_byte_count;
void* spirv_data;
size_t spirv_data_size;
VkPushConstantRange* push_constant_ranges;
uint32_t num_push_constant_ranges;
VkDescriptorSetLayout* descriptor_set_layouts;
uint32_t num_descriptor_set_layouts;
// Points to specialization_info if there is any specialization info
VkSpecializationInfo* specialization_info_ptr;
VkSpecializationInfo specialization_info;