forked from crosire/reshade
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runtime_vk.cpp
2084 lines (1773 loc) · 84.4 KB
/
runtime_vk.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 (C) 2014 Patrick Mours. All rights reserved.
* License: https://github.com/crosire/reshade#license
*/
#include "dll_log.hpp"
#include "runtime_vk.hpp"
#include "runtime_vk_objects.hpp"
#include "format_utils.hpp"
static inline void transition_layout(const VkLayerDispatchTable &vk, VkCommandBuffer cmd_list, VkImage image, VkImageLayout old_layout, VkImageLayout new_layout,
const VkImageSubresourceRange &subresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, VK_REMAINING_MIP_LEVELS, 0, VK_REMAINING_ARRAY_LAYERS })
{
const auto layout_to_access = [](VkImageLayout layout) -> VkAccessFlags {
switch (layout)
{
default:
case VK_IMAGE_LAYOUT_UNDEFINED:
return 0; // No prending writes to flush
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
return VK_ACCESS_TRANSFER_READ_BIT;
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
return VK_ACCESS_TRANSFER_WRITE_BIT;
case VK_IMAGE_LAYOUT_GENERAL:
return VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
return VK_ACCESS_SHADER_READ_BIT;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:
return VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL:
case VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL:
return VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR:
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
return VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
}
};
const auto layout_to_stage = [](VkImageLayout layout) -> VkPipelineStageFlags {
switch (layout)
{
default:
case VK_IMAGE_LAYOUT_UNDEFINED:
return VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; // Do not wait on any previous stage
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
return VK_PIPELINE_STAGE_TRANSFER_BIT;
case VK_IMAGE_LAYOUT_GENERAL:
return VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
return VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL:
case VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL:
return VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR: // Can use color attachment output here, since the semaphores wait on that stage
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
return VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
}
};
VkImageMemoryBarrier transition { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER };
transition.srcAccessMask = layout_to_access(old_layout);
transition.dstAccessMask = layout_to_access(new_layout);
transition.oldLayout = old_layout;
transition.newLayout = new_layout;
transition.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
transition.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
transition.image = image;
transition.subresourceRange = subresource;
vk.CmdPipelineBarrier(cmd_list, layout_to_stage(old_layout), layout_to_stage(new_layout), 0, 0, nullptr, 0, nullptr, 1, &transition);
}
#define vk _device_impl->_dispatch_table
reshade::vulkan::runtime_impl::runtime_impl(device_impl *device, command_queue_impl *graphics_queue) :
api_object_impl(VK_NULL_HANDLE), // Swap chain object is later set in 'on_init' below
_device_impl(device),
_device(device->_orig),
_queue_impl(graphics_queue),
_queue(graphics_queue->_orig),
_cmd_impl(static_cast<command_list_immediate_impl *>(graphics_queue->get_immediate_command_list()))
{
VkPhysicalDeviceProperties device_props = {};
device->_instance_dispatch_table.GetPhysicalDeviceProperties(device->_physical_device, &device_props);
_renderer_id = 0x20000 |
VK_VERSION_MAJOR(device_props.apiVersion) << 12 |
VK_VERSION_MINOR(device_props.apiVersion) << 8;
_vendor_id = device_props.vendorID;
_device_id = device_props.deviceID;
// NVIDIA has a custom driver version scheme, so extract the proper minor version from it
const uint32_t driver_minor_version = _vendor_id == 0x10DE ?
(device_props.driverVersion >> 14) & 0xFF : VK_VERSION_MINOR(device_props.driverVersion);
LOG(INFO) << "Running on " << device_props.deviceName << " Driver " << VK_VERSION_MAJOR(device_props.driverVersion) << '.' << driver_minor_version;
// Find a supported stencil format
const VkFormat possible_stencil_formats[] = {
VK_FORMAT_S8_UINT,
VK_FORMAT_D16_UNORM_S8_UINT,
VK_FORMAT_D24_UNORM_S8_UINT,
VK_FORMAT_D32_SFLOAT_S8_UINT
};
for (const VkFormat format : possible_stencil_formats)
{
VkFormatProperties format_props = {};
device->_instance_dispatch_table.GetPhysicalDeviceFormatProperties(device->_physical_device, format, &format_props);
if ((format_props.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) != 0)
{
_effect_stencil_format = format;
break;
}
}
}
reshade::vulkan::runtime_impl::~runtime_impl()
{
on_reset();
#if RESHADE_GUI
vk.DestroyPipeline(_device, _imgui.pipeline, nullptr);
_imgui.pipeline = VK_NULL_HANDLE;
vk.DestroyPipelineLayout(_device, _imgui.pipeline_layout, nullptr);
_imgui.pipeline_layout = VK_NULL_HANDLE;
vk.DestroyDescriptorSetLayout(_device, _imgui.descriptor_layout, nullptr);
_imgui.descriptor_layout = VK_NULL_HANDLE;
vk.DestroySampler(_device, _imgui.sampler, nullptr);
_imgui.sampler = VK_NULL_HANDLE;
#endif
vk.DestroyDescriptorSetLayout(_device, _effect_descriptor_layout, nullptr);
_effect_descriptor_layout = VK_NULL_HANDLE;
}
bool reshade::vulkan::runtime_impl::on_init(VkSwapchainKHR swapchain, const VkSwapchainCreateInfoKHR &desc, HWND hwnd)
{
_orig = swapchain;
_width = _window_width = desc.imageExtent.width;
_height = _window_height = desc.imageExtent.height;
_color_bit_depth = desc.imageFormat >= VK_FORMAT_A2R10G10B10_UNORM_PACK32 && desc.imageFormat <= VK_FORMAT_A2B10G10R10_SINT_PACK32 ? 10 : 8;
_backbuffer_format = desc.imageFormat;
if (hwnd != nullptr)
{
RECT window_rect = {};
GetClientRect(hwnd, &window_rect);
_window_width = window_rect.right;
_window_height = window_rect.bottom;
}
if (_queue == VK_NULL_HANDLE)
return false;
// Create back buffer shader image
assert(_backbuffer_format != VK_FORMAT_UNDEFINED);
_backbuffer_image = create_image(
_width, _height, 1, _backbuffer_format,
VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VMA_MEMORY_USAGE_GPU_ONLY,
VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT);
if (_backbuffer_image == VK_NULL_HANDLE)
return false;
set_debug_name_image(_backbuffer_image, "ReShade back buffer");
_backbuffer_image_view[0] = create_image_view(_backbuffer_image, make_format_normal(_backbuffer_format), 1, VK_IMAGE_ASPECT_COLOR_BIT);
if (_backbuffer_image_view[0] == VK_NULL_HANDLE)
return false;
_backbuffer_image_view[1] = create_image_view(_backbuffer_image, make_format_srgb(_backbuffer_format), 1, VK_IMAGE_ASPECT_COLOR_BIT);
if (_backbuffer_image_view[1] == VK_NULL_HANDLE)
return false;
// Create effect depth-stencil resource
assert(_effect_stencil_format != VK_FORMAT_UNDEFINED);
_effect_stencil = create_image(
_width, _height, 1, _effect_stencil_format,
VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VMA_MEMORY_USAGE_GPU_ONLY);
if (_effect_stencil == VK_NULL_HANDLE)
return false;
set_debug_name_image(_effect_stencil, "ReShade stencil buffer");
_effect_stencil_view = create_image_view(_effect_stencil, _effect_stencil_format, 1, VK_IMAGE_ASPECT_STENCIL_BIT);
if (_effect_stencil_view == VK_NULL_HANDLE)
return false;
// Create default render pass
for (uint32_t k = 0; k < 2; ++k)
{
VkAttachmentReference attachment_refs[2] = {};
attachment_refs[0].attachment = 0;
attachment_refs[0].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
attachment_refs[1].attachment = 1;
attachment_refs[1].layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentDescription attachment_descs[2] = {};
attachment_descs[0].format = k == 0 ? make_format_normal(_backbuffer_format) : make_format_srgb(_backbuffer_format);
attachment_descs[0].samples = VK_SAMPLE_COUNT_1_BIT;
attachment_descs[0].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
attachment_descs[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachment_descs[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachment_descs[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachment_descs[0].initialLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
attachment_descs[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
attachment_descs[1].format = _effect_stencil_format;
attachment_descs[1].samples = VK_SAMPLE_COUNT_1_BIT;
attachment_descs[1].loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachment_descs[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachment_descs[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
attachment_descs[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
attachment_descs[1].initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
attachment_descs[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkSubpassDependency subdep = {};
subdep.srcSubpass = VK_SUBPASS_EXTERNAL;
subdep.dstSubpass = 0;
subdep.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
subdep.dstStageMask = VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT;
subdep.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
subdep.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
VkSubpassDescription subpass = {};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &attachment_refs[0];
subpass.pDepthStencilAttachment = &attachment_refs[1];
VkRenderPassCreateInfo create_info { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO };
create_info.attachmentCount = 2;
create_info.pAttachments = attachment_descs;
create_info.subpassCount = 1;
create_info.pSubpasses = &subpass;
create_info.dependencyCount = 1;
create_info.pDependencies = &subdep;
if (vk.CreateRenderPass(_device, &create_info, nullptr, &_default_render_pass[k]) != VK_SUCCESS)
return false;
}
uint32_t num_images = 0;
if (swapchain != VK_NULL_HANDLE)
{
// Get back buffer images
if (vk.GetSwapchainImagesKHR(_device, swapchain, &num_images, nullptr) != VK_SUCCESS)
return false;
_swapchain_images.resize(num_images);
if (vk.GetSwapchainImagesKHR(_device, swapchain, &num_images, _swapchain_images.data()) != VK_SUCCESS)
return false;
}
else
{
num_images = static_cast<uint32_t>(_swapchain_images.size());
assert(num_images != 0);
}
assert(desc.imageUsage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT);
_render_area = desc.imageExtent;
_swapchain_views.resize(num_images * 2);
_swapchain_frames.resize(num_images * 2);
for (uint32_t i = 0, k = 0; i < num_images; ++i, k += 2)
{
_swapchain_views[k + 1] = create_image_view(_swapchain_images[i], make_format_srgb(desc.imageFormat), 1, VK_IMAGE_ASPECT_COLOR_BIT);
_swapchain_views[k + 0] = create_image_view(_swapchain_images[i], make_format_normal(desc.imageFormat), 1, VK_IMAGE_ASPECT_COLOR_BIT);
const VkImageView attachment_views[2] = { _swapchain_views[k + 0], _effect_stencil_view };
const VkImageView attachment_views_srgb[2] = { _swapchain_views[k + 1], _effect_stencil_view };
{ VkFramebufferCreateInfo create_info { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO };
create_info.renderPass = _default_render_pass[0];
create_info.attachmentCount = 2;
create_info.pAttachments = attachment_views;
create_info.width = desc.imageExtent.width;
create_info.height = desc.imageExtent.height;
create_info.layers = 1;
if (vk.CreateFramebuffer(_device, &create_info, nullptr, &_swapchain_frames[k + 0]) != VK_SUCCESS)
return false;
create_info.renderPass = _default_render_pass[1];
create_info.pAttachments = attachment_views_srgb;
if (vk.CreateFramebuffer(_device, &create_info, nullptr, &_swapchain_frames[k + 1]) != VK_SUCCESS)
return false;
}
}
for (uint32_t i = 0; i < NUM_QUERY_FRAMES; ++i)
{
VkSemaphoreCreateInfo sem_create_info { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO };
if (vk.CreateSemaphore(_device, &sem_create_info, nullptr, &_queue_sync_semaphores[i]) != VK_SUCCESS)
return false;
}
// Allocate a single descriptor pool for all effects
if (_effect_descriptor_pool == VK_NULL_HANDLE)
{
VkDescriptorPoolSize pool_sizes[] = {
{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, MAX_EFFECT_DESCRIPTOR_SETS }, // Only need one global UBO per set
{ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, MAX_EFFECT_DESCRIPTOR_SETS * MAX_IMAGE_DESCRIPTOR_SETS },
{ VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, MAX_EFFECT_DESCRIPTOR_SETS * MAX_IMAGE_DESCRIPTOR_SETS },
};
VkDescriptorPoolCreateInfo create_info { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };
// No VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT set, so that all descriptors can be reset in one go via vkResetDescriptorPool
create_info.maxSets = MAX_EFFECT_DESCRIPTOR_SETS;
create_info.poolSizeCount = static_cast<uint32_t>(std::size(pool_sizes));
create_info.pPoolSizes = pool_sizes;
if (vk.CreateDescriptorPool(_device, &create_info, nullptr, &_effect_descriptor_pool) != VK_SUCCESS)
return false;
}
if (_effect_descriptor_layout == VK_NULL_HANDLE)
{
VkDescriptorSetLayoutBinding bindings = { 0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_ALL };
VkDescriptorSetLayoutCreateInfo create_info { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
create_info.bindingCount = 1;
create_info.pBindings = &bindings;
if (vk.CreateDescriptorSetLayout(_device, &create_info, nullptr, &_effect_descriptor_layout) != VK_SUCCESS)
return false;
}
// Create an empty image, which is used when no depth buffer was detected (since you cannot bind nothing to a descriptor in Vulkan)
// Use VK_FORMAT_R16_SFLOAT format, since it is mandatory according to the spec (see https://www.khronos.org/registry/vulkan/specs/1.1/html/vkspec.html#features-required-format-support)
_empty_depth_image = create_image(1, 1, 1, VK_FORMAT_R16_SFLOAT, VK_IMAGE_USAGE_SAMPLED_BIT, VMA_MEMORY_USAGE_GPU_ONLY);
if (_empty_depth_image == VK_NULL_HANDLE)
return false;
_empty_depth_image_view = create_image_view(_empty_depth_image, VK_FORMAT_R16_SFLOAT, 1, VK_IMAGE_ASPECT_COLOR_BIT);
if (_empty_depth_image_view == VK_NULL_HANDLE)
return false;
// Transition image layouts to the ones required below
const VkCommandBuffer cmd_list = _cmd_impl->begin_commands();
transition_layout(vk, cmd_list, _effect_stencil, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, { aspect_flags_from_format(_effect_stencil_format), 0, 1, 0, 1 });
transition_layout(vk, cmd_list, _empty_depth_image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
#if RESHADE_GUI
if (!init_imgui_resources())
return false;
#endif
return runtime::on_init(hwnd);
}
void reshade::vulkan::runtime_impl::on_reset()
{
runtime::on_reset();
// Make sure none of the resources below are currently in use
wait_for_command_buffers();
for (VkImageView view : _swapchain_views)
vk.DestroyImageView(_device, view, nullptr);
_swapchain_views.clear();
for (VkFramebuffer frame : _swapchain_frames)
vk.DestroyFramebuffer(_device, frame, nullptr);
_swapchain_frames.clear();
if (_orig == VK_NULL_HANDLE)
for (VkImage image : _swapchain_images)
vk.DestroyImage(_device, image, nullptr);
_swapchain_images.clear();
for (VkSemaphore &semaphore : _queue_sync_semaphores)
vk.DestroySemaphore(_device, semaphore, nullptr),
semaphore = VK_NULL_HANDLE;
vk.DestroyImage(_device, _backbuffer_image, nullptr);
_backbuffer_image = VK_NULL_HANDLE;
vk.DestroyImageView(_device, _backbuffer_image_view[0], nullptr);
_backbuffer_image_view[0] = VK_NULL_HANDLE;
vk.DestroyImageView(_device, _backbuffer_image_view[1], nullptr);
_backbuffer_image_view[1] = VK_NULL_HANDLE;
vk.DestroyRenderPass(_device, _default_render_pass[0], nullptr);
_default_render_pass[0] = VK_NULL_HANDLE;
vk.DestroyRenderPass(_device, _default_render_pass[1], nullptr);
_default_render_pass[1] = VK_NULL_HANDLE;
vk.DestroyImage(_device, _empty_depth_image, nullptr);
_empty_depth_image = VK_NULL_HANDLE;
vk.DestroyImageView(_device, _empty_depth_image_view, nullptr);
_empty_depth_image_view = VK_NULL_HANDLE;
vk.DestroyImage(_device, _effect_stencil, nullptr);
_effect_stencil = VK_NULL_HANDLE;
vk.DestroyImageView(_device, _effect_stencil_view, nullptr);
_effect_stencil_view = VK_NULL_HANDLE;
vk.DestroyDescriptorPool(_device, _effect_descriptor_pool, nullptr);
_effect_descriptor_pool = VK_NULL_HANDLE;
#if RESHADE_GUI
for (unsigned int i = 0; i < NUM_IMGUI_BUFFERS; ++i)
{
vmaDestroyBuffer(_device_impl->_alloc, _imgui.indices[i], _imgui.indices_mem[i]);
vmaDestroyBuffer(_device_impl->_alloc, _imgui.vertices[i], _imgui.vertices_mem[i]);
_imgui.indices[i] = VK_NULL_HANDLE;
_imgui.vertices[i] = VK_NULL_HANDLE;
_imgui.indices_mem[i] = VK_NULL_HANDLE;
_imgui.vertices_mem[i] = VK_NULL_HANDLE;
_imgui.num_indices[i] = 0;
_imgui.num_vertices[i] = 0;
}
vk.DestroyDescriptorPool(_device, _imgui.descriptor_pool, nullptr);
_imgui.descriptor_pool = VK_NULL_HANDLE;
#endif
// Free all unmanaged device memory allocated via the 'create_image' and 'create_buffer' functions
vmaFreeMemoryPages(_device_impl->_alloc, _allocations.size(), _allocations.data());
_allocations.clear();
}
void reshade::vulkan::runtime_impl::on_present(VkQueue queue, const uint32_t swapchain_image_index, std::vector<VkSemaphore> &wait)
{
if (!_is_initialized)
return;
_swap_index = swapchain_image_index;
update_and_render_effects();
runtime::on_present();
#ifndef NDEBUG
// Some operations force a wait for idle in ReShade, which invalidates the wait semaphores, so signal them again (keeps the validation layers happy)
if (_wait_for_idle_happened)
{
VkSubmitInfo submit_info { VK_STRUCTURE_TYPE_SUBMIT_INFO };
std::vector<VkPipelineStageFlags> wait_stages(wait.size(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
submit_info.waitSemaphoreCount = static_cast<uint32_t>(wait.size());
submit_info.pWaitSemaphores = wait.data();
submit_info.pWaitDstStageMask = wait_stages.data();
submit_info.signalSemaphoreCount = static_cast<uint32_t>(wait.size());
submit_info.pSignalSemaphores = wait.data();
vk.QueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
_wait_for_idle_happened = false;
}
#endif
// If the application is presenting with a different queue than rendering, synchronize these two queues first
// This ensures that it has finished rendering before ReShade applies its own rendering
if (queue != _queue)
{
// Signal a semaphore from the queue the application is presenting with
VkSubmitInfo submit_info { VK_STRUCTURE_TYPE_SUBMIT_INFO };
submit_info.signalSemaphoreCount = 1;
submit_info.pSignalSemaphores = &_queue_sync_semaphores[_queue_sync_index];
vk.QueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
// Wait on that semaphore before the immediate command list flush below
wait.push_back(submit_info.pSignalSemaphores[0]);
_queue_sync_index = (_queue_sync_index + 1) % NUM_QUERY_FRAMES;
}
_cmd_impl->flush(_queue, wait);
}
bool reshade::vulkan::runtime_impl::on_present(VkQueue queue, VkImage source, VkFormat source_format, VkSampleCountFlags source_samples, const VkRect2D ®ion, uint32_t layer_index, HWND hwnd, std::vector<VkSemaphore> &wait)
{
assert(source != VK_NULL_HANDLE);
if (source_samples != VK_SAMPLE_COUNT_1_BIT)
return false;
if (region.extent.width != _width || region.extent.height != _height || source_format != _backbuffer_format)
{
on_reset();
const VkImage image = create_image(
region.extent.width, region.extent.height, 1, source_format,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY);
if (image == VK_NULL_HANDLE)
{
LOG(ERROR) << "Failed to create region image!";
return false;
}
_swapchain_images.resize(1);
_swapchain_images[0] = image;
VkSwapchainCreateInfoKHR desc = { VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR };
desc.imageExtent = region.extent;
desc.imageFormat = source_format;
desc.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
if (!on_init(VK_NULL_HANDLE, desc, hwnd))
{
LOG(ERROR) << "Failed to initialize Vulkan runtime environment on runtime " << this << '!';
return false;
}
}
const VkCommandBuffer cmd_list = _cmd_impl->begin_commands();
transition_layout(_device_impl->_dispatch_table, cmd_list, _swapchain_images[0], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
// Copy region of the source texture
if (source_samples == VK_SAMPLE_COUNT_1_BIT)
{
const VkImageCopy copy_region = {
{ VK_IMAGE_ASPECT_COLOR_BIT, 0, layer_index, 1 }, { region.offset.x, region.offset.y, 0 },
{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, { 0, 0, 0 }, { region.extent.width, region.extent.height, 1 }
};
vk.CmdCopyImage(cmd_list, source, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, _swapchain_images[0], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region);
}
else
{
const VkImageResolve resolve_region = {
{ VK_IMAGE_ASPECT_COLOR_BIT, 0, layer_index, 1 }, { region.offset.x, region.offset.y, 0 },
{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, { 0, 0, 0 }, { region.extent.width, region.extent.height, 1 }
};
vk.CmdResolveImage(cmd_list, source, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, _swapchain_images[0], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &resolve_region);
}
transition_layout(_device_impl->_dispatch_table, cmd_list, _swapchain_images[0], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
on_present(queue, 0, wait);
transition_layout(_device_impl->_dispatch_table, cmd_list, _swapchain_images[0], VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
transition_layout(_device_impl->_dispatch_table, cmd_list, source, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
// Copy results back into the source texture
if (source_samples == VK_SAMPLE_COUNT_1_BIT)
{
const VkImageCopy copy_region = {
{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, { 0, 0, 0 },
{ VK_IMAGE_ASPECT_COLOR_BIT, 0, layer_index, 1 }, { region.offset.x, region.offset.y, 0 }, { region.extent.width, region.extent.height, 1 }
};
vk.CmdCopyImage(cmd_list, _swapchain_images[0], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, source, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region);
}
else
{
// TODO
assert(false);
}
transition_layout(_device_impl->_dispatch_table, cmd_list, source, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
return true;
}
bool reshade::vulkan::runtime_impl::capture_screenshot(uint8_t *buffer) const
{
if (_color_bit_depth != 8 && _color_bit_depth != 10)
{
LOG(ERROR) << "Screenshots are not supported for back buffer format " << _backbuffer_format << '!';
return false;
}
const size_t data_pitch = _width * 4;
VkBuffer intermediate = VK_NULL_HANDLE;
VmaAllocation intermediate_mem = VK_NULL_HANDLE;
{ VkBufferCreateInfo create_info { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
create_info.size = data_pitch * _height;
create_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
VmaAllocationCreateInfo alloc_info = {};
alloc_info.usage = VMA_MEMORY_USAGE_GPU_TO_CPU;
if (vmaCreateBuffer(_device_impl->_alloc, &create_info, &alloc_info, &intermediate, &intermediate_mem, nullptr) != VK_SUCCESS)
return false;
}
// Copy image into download buffer
uint8_t *mapped_data = nullptr;
{
const VkCommandBuffer cmd_list = _cmd_impl->begin_commands();
transition_layout(vk, cmd_list, _swapchain_images[_swap_index], VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
{
VkBufferImageCopy copy;
copy.bufferOffset = 0;
copy.bufferRowLength = _width;
copy.bufferImageHeight = _height;
copy.imageOffset = { 0, 0, 0 };
copy.imageExtent = { _width, _height, 1 };
copy.imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 };
vk.CmdCopyImageToBuffer(cmd_list, _swapchain_images[_swap_index], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, intermediate, 1, ©);
}
transition_layout(vk, cmd_list, _swapchain_images[_swap_index], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
// Wait for any rendering by the application finish before submitting
// It may have submitted that to a different queue, so simply wait for all to idle here
vk.DeviceWaitIdle(_device);
#ifndef NDEBUG
_wait_for_idle_happened = true;
#endif
// Execute and wait for completion
_cmd_impl->flush_and_wait(_queue);
// Copy data from intermediate image into output buffer
if (vmaMapMemory(_device_impl->_alloc, intermediate_mem, reinterpret_cast<void **>(&mapped_data)) != VK_SUCCESS)
mapped_data = nullptr;
}
if (mapped_data != nullptr)
{
for (uint32_t y = 0; y < _height; y++, buffer += data_pitch, mapped_data += data_pitch)
{
if (_color_bit_depth == 10)
{
for (uint32_t x = 0; x < data_pitch; x += 4)
{
const uint32_t rgba = *reinterpret_cast<const uint32_t *>(mapped_data + x);
// Divide by 4 to get 10-bit range (0-1023) into 8-bit range (0-255)
buffer[x + 0] = ( (rgba & 0x000003FF) / 4) & 0xFF;
buffer[x + 1] = (((rgba & 0x000FFC00) >> 10) / 4) & 0xFF;
buffer[x + 2] = (((rgba & 0x3FF00000) >> 20) / 4) & 0xFF;
buffer[x + 3] = (((rgba & 0xC0000000) >> 30) * 85) & 0xFF;
if (_backbuffer_format >= VK_FORMAT_A2B10G10R10_UNORM_PACK32 &&
_backbuffer_format <= VK_FORMAT_A2B10G10R10_SINT_PACK32)
std::swap(buffer[x + 0], buffer[x + 2]);
}
}
else
{
std::memcpy(buffer, mapped_data, data_pitch);
if (_backbuffer_format >= VK_FORMAT_B8G8R8A8_UNORM &&
_backbuffer_format <= VK_FORMAT_B8G8R8A8_SRGB)
{
// Format is BGRA, but output should be RGBA, so flip channels
for (uint32_t x = 0; x < data_pitch; x += 4)
std::swap(buffer[x + 0], buffer[x + 2]);
}
}
}
vmaUnmapMemory(_device_impl->_alloc, intermediate_mem);
}
vmaDestroyBuffer(_device_impl->_alloc, intermediate, intermediate_mem);
return mapped_data != nullptr;
}
bool reshade::vulkan::runtime_impl::init_effect(size_t index)
{
effect &effect = _effects[index];
// Load shader modules
struct shader_modules
{
bool loaded = false;
runtime_impl *const runtime;
std::vector<VkShaderModule> list;
std::unordered_map<std::string, VkShaderModule> entry_points;
shader_modules(runtime_impl *runtime, const reshadefx::module &effect_module) : runtime(runtime)
{
VkResult res = VK_SUCCESS;
// There are various issues with SPIR-V modules that have multiple entry points on all major GPU vendors.
// On AMD for instance creating a graphics pipeline just fails with a generic VK_ERROR_OUT_OF_HOST_MEMORY. On NVIDIA artifacts occur on some driver versions.
// To work around these problems, create a separate shader module for every entry point and rewrite the SPIR-V module for each to removes all but a single entry point (and associated functions/variables).
for (size_t i = 0; i < effect_module.entry_points.size() && res == VK_SUCCESS; ++i)
{
const reshadefx::entry_point &entry_point = effect_module.entry_points[i];
uint32_t current_function = 0, current_function_offset = 0;
std::vector<uint32_t> spirv = effect_module.spirv;
std::vector<uint32_t> functions_to_remove, variables_to_remove;
for (uint32_t inst = 5 /* Skip SPIR-V header information */; inst < spirv.size();)
{
const uint32_t op = spirv[inst] & 0xFFFF;
const uint32_t len = (spirv[inst] >> 16) & 0xFFFF;
assert(len != 0);
switch (op)
{
case 15: // OpEntryPoint
// Look for any non-matching entry points
if (entry_point.name != reinterpret_cast<const char *>(&spirv[inst + 3]))
{
functions_to_remove.push_back(spirv[inst + 2]);
// Get interface variables
for (size_t k = inst + 3 + ((strlen(reinterpret_cast<const char *>(&spirv[inst + 3])) + 4) / 4); k < inst + len; ++k)
variables_to_remove.push_back(spirv[k]);
// Remove this entry point from the module
spirv.erase(spirv.begin() + inst, spirv.begin() + inst + len);
continue;
}
break;
case 16: // OpExecutionMode
if (std::find(functions_to_remove.begin(), functions_to_remove.end(), spirv[inst + 1]) != functions_to_remove.end())
{
spirv.erase(spirv.begin() + inst, spirv.begin() + inst + len);
continue;
}
break;
case 59: // OpVariable
// Remove all declarations of the interface variables for non-matching entry points
if (std::find(variables_to_remove.begin(), variables_to_remove.end(), spirv[inst + 2]) != variables_to_remove.end())
{
spirv.erase(spirv.begin() + inst, spirv.begin() + inst + len);
continue;
}
break;
case 71: // OpDecorate
// Remove all decorations targeting any of the interface variables for non-matching entry points
if (std::find(variables_to_remove.begin(), variables_to_remove.end(), spirv[inst + 1]) != variables_to_remove.end())
{
spirv.erase(spirv.begin() + inst, spirv.begin() + inst + len);
continue;
}
break;
case 54: // OpFunction
current_function = spirv[inst + 2];
current_function_offset = inst;
break;
case 56: // OpFunctionEnd
// Remove all function definitions for non-matching entry points
if (std::find(functions_to_remove.begin(), functions_to_remove.end(), current_function) != functions_to_remove.end())
{
spirv.erase(spirv.begin() + current_function_offset, spirv.begin() + inst + len);
inst = current_function_offset;
continue;
}
break;
}
inst += len;
}
VkShaderModuleCreateInfo create_info { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO };
create_info.codeSize = spirv.size() * sizeof(uint32_t);
create_info.pCode = spirv.data();
res = runtime->vk.CreateShaderModule(runtime->_device, &create_info, nullptr, &list.emplace_back());
entry_points[entry_point.name] = list.back();
}
if (res != VK_SUCCESS)
{
LOG(ERROR) << "Failed to create shader module! Vulkan error code is " << res << '.';
return;
}
loaded = true;
}
~shader_modules()
{
for (const VkShaderModule module : list)
runtime->vk.DestroyShaderModule(runtime->_device, module, nullptr);
}
}
shader_modules(this, effect.module);
if (!shader_modules.loaded)
return false;
if (_effect_data.size() <= index)
_effect_data.resize(index + 1);
effect_data &effect_data = _effect_data[index];
// Create query pool for time measurements
{ VkQueryPoolCreateInfo create_info { VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO };
create_info.queryType = VK_QUERY_TYPE_TIMESTAMP;
create_info.queryCount = static_cast<uint32_t>(effect.module.techniques.size() * 2 * NUM_QUERY_FRAMES);
if (vk.CreateQueryPool(_device, &create_info, nullptr, &effect_data.query_pool) != VK_SUCCESS)
return false;
}
// Initialize pipeline layout
{ std::vector<VkDescriptorSetLayoutBinding> bindings;
bindings.reserve(effect.module.num_sampler_bindings);
for (uint32_t i = 0; i < effect.module.num_sampler_bindings; ++i)
bindings.push_back({ i, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL });
VkDescriptorSetLayoutCreateInfo create_info { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
create_info.bindingCount = uint32_t(bindings.size());
create_info.pBindings = bindings.data();
if (vk.CreateDescriptorSetLayout(_device, &create_info, nullptr, &effect_data.sampler_layout) != VK_SUCCESS)
return false;
}
if (effect.module.num_storage_bindings != 0)
{
std::vector<VkDescriptorSetLayoutBinding> bindings;
bindings.reserve(effect.module.num_storage_bindings);
for (uint32_t i = 0; i < effect.module.num_storage_bindings; ++i)
bindings.push_back({ i, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT });
VkDescriptorSetLayoutCreateInfo create_info { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
create_info.bindingCount = uint32_t(bindings.size());
create_info.pBindings = bindings.data();
if (vk.CreateDescriptorSetLayout(_device, &create_info, nullptr, &effect_data.storage_layout) != VK_SUCCESS)
return false;
}
const VkDescriptorSetLayout set_layouts[3] = { _effect_descriptor_layout, effect_data.sampler_layout, effect_data.storage_layout };
{ VkPipelineLayoutCreateInfo create_info { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO };
create_info.setLayoutCount = effect.module.num_storage_bindings == 0 ? 2 : 3; // [0] = Global UBO, [1] = Samplers, [2] = Storage Images
create_info.pSetLayouts = set_layouts;
if (vk.CreatePipelineLayout(_device, &create_info, nullptr, &effect_data.pipeline_layout) != VK_SUCCESS)
return false;
}
// Create global uniform buffer object
if (!effect.uniform_data_storage.empty())
{
effect_data.ubo = create_buffer(
effect.uniform_data_storage.size(),
VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU,
0, 0, &effect_data.ubo_mem);
if (effect_data.ubo == VK_NULL_HANDLE)
return false;
}
// Initialize image and sampler bindings
assert(effect.module.num_texture_bindings == 0); // Use combined image samplers
std::vector<VkDescriptorImageInfo> sampler_bindings(effect.module.num_sampler_bindings);
std::vector<VkDescriptorImageInfo> storage_bindings(effect.module.num_storage_bindings);
for (const reshadefx::sampler_info &info : effect.module.samplers)
{
const texture &texture = look_up_texture_by_name(info.texture_name);
VkDescriptorImageInfo &image_binding = sampler_bindings[info.binding];
image_binding.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
if (texture.semantic == "COLOR")
{
image_binding.imageView = _backbuffer_image_view[info.srgb];
}
else if (!texture.semantic.empty())
{
// Set to a default view to avoid crash because of this not being set
image_binding.imageView = _empty_depth_image_view;
if (const auto it = _texture_semantic_bindings.find(texture.semantic);
it != _texture_semantic_bindings.end())
image_binding.imageView = it->second;
// Keep track of the texture descriptor to simplify updating it
effect_data.texture_semantic_to_binding.push_back({ texture.semantic, info.binding });
}
else
{
image_binding.imageView = static_cast<tex_data *>(texture.impl)->view[info.srgb];
}
// Unset bindings are not allowed, so fail initialization for the entire effect in that case
if (assert(image_binding.imageView != VK_NULL_HANDLE); image_binding.imageView == VK_NULL_HANDLE)
return false;
VkSamplerCreateInfo create_info { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO };
create_info.addressModeU = static_cast<VkSamplerAddressMode>(static_cast<uint32_t>(info.address_u) - 1);
create_info.addressModeV = static_cast<VkSamplerAddressMode>(static_cast<uint32_t>(info.address_v) - 1);
create_info.addressModeW = static_cast<VkSamplerAddressMode>(static_cast<uint32_t>(info.address_w) - 1);
create_info.mipLodBias = info.lod_bias;
create_info.anisotropyEnable = VK_FALSE;
create_info.maxAnisotropy = 1.0f;
create_info.compareEnable = VK_FALSE;
create_info.compareOp = VK_COMPARE_OP_ALWAYS;
create_info.minLod = info.min_lod;
create_info.maxLod = info.max_lod;
switch (info.filter)
{
case reshadefx::texture_filter::min_mag_mip_point:
create_info.magFilter = VK_FILTER_NEAREST;
create_info.minFilter = VK_FILTER_NEAREST;
create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
break;
case reshadefx::texture_filter::min_mag_point_mip_linear:
create_info.magFilter = VK_FILTER_NEAREST;
create_info.minFilter = VK_FILTER_NEAREST;
create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
break;
case reshadefx::texture_filter::min_point_mag_linear_mip_point:
create_info.magFilter = VK_FILTER_LINEAR;
create_info.minFilter = VK_FILTER_NEAREST;
create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
break;
case reshadefx::texture_filter::min_point_mag_mip_linear:
create_info.magFilter = VK_FILTER_LINEAR;
create_info.minFilter = VK_FILTER_NEAREST;
create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
break;
case reshadefx::texture_filter::min_linear_mag_mip_point:
create_info.magFilter = VK_FILTER_NEAREST;
create_info.minFilter = VK_FILTER_LINEAR;
create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
break;
case reshadefx::texture_filter::min_linear_mag_point_mip_linear:
create_info.magFilter = VK_FILTER_NEAREST;
create_info.minFilter = VK_FILTER_LINEAR;
create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
break;
case reshadefx::texture_filter::min_mag_linear_mip_point:
create_info.magFilter = VK_FILTER_LINEAR;
create_info.minFilter = VK_FILTER_LINEAR;
create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
break;
case reshadefx::texture_filter::min_mag_mip_linear:
create_info.magFilter = VK_FILTER_LINEAR;
create_info.minFilter = VK_FILTER_LINEAR;
create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
break;
}
// Generate hash for sampler description
size_t desc_hash = 2166136261;
for (size_t i = 0; i < sizeof(create_info); ++i)
desc_hash = (desc_hash * 16777619) ^ reinterpret_cast<const uint8_t *>(&create_info)[i];
std::unordered_map<size_t, VkSampler>::iterator it = _effect_sampler_states.find(desc_hash);
if (it == _effect_sampler_states.end())
{
VkSampler sampler = VK_NULL_HANDLE;
if (vk.CreateSampler(_device, &create_info, nullptr, &sampler) != VK_SUCCESS)
return false;
it = _effect_sampler_states.emplace(desc_hash, sampler).first;
}
image_binding.sampler = it->second;
}
for (const reshadefx::storage_info &info : effect.module.storages)
{
const texture &texture = look_up_texture_by_name(info.texture_name);
VkDescriptorImageInfo &image_binding = storage_bindings[info.binding];
image_binding.imageView = static_cast<tex_data *>(texture.impl)->view[0];
image_binding.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
// Unset bindings are not allowed, so fail initialization for the entire effect in that case
if (image_binding.imageView == VK_NULL_HANDLE)
return false;
}
uint32_t num_passes = 0;
for (const reshadefx::technique_info &info : effect.module.techniques)
num_passes += static_cast<uint32_t>(info.passes.size());
std::vector<VkDescriptorSet> sets(1 + 2 * num_passes);
std::vector<VkWriteDescriptorSet> writes;
writes.reserve(sets.size());
{ VkDescriptorSetAllocateInfo alloc_info { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };
alloc_info.descriptorPool = _effect_descriptor_pool;
alloc_info.descriptorSetCount = 1 + (effect.module.num_storage_bindings == 0 ? 1 : 2) * num_passes;
std::vector<VkDescriptorSetLayout> alloc_set_layouts(sets.size());
alloc_set_layouts[0] = _effect_descriptor_layout;
for (size_t i = 0; i < num_passes; ++i)
{
alloc_set_layouts[1 + i] = effect_data.sampler_layout;
alloc_set_layouts[1 + num_passes + i] = effect_data.storage_layout;
}
alloc_info.pSetLayouts = alloc_set_layouts.data();
if (vk.AllocateDescriptorSets(_device, &alloc_info, sets.data()) != VK_SUCCESS)
{
LOG(ERROR) << "Too many effects loaded. Only " << (MAX_EFFECT_DESCRIPTOR_SETS / 2) << " effects can be active simultaneously in Vulkan.";
return false;
}
}
effect_data.ubo_set = sets[0];
const VkDescriptorBufferInfo ubo_info = { effect_data.ubo, 0, VK_WHOLE_SIZE };
if (effect_data.ubo != VK_NULL_HANDLE)
{
VkWriteDescriptorSet &write = writes.emplace_back();
write = { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET };
write.dstSet = effect_data.ubo_set;
write.dstBinding = 0;
write.descriptorCount = 1;
write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
write.pBufferInfo = &ubo_info;
}
std::vector<uint8_t> spec_data;
std::vector<VkSpecializationMapEntry> spec_constants;
for (const reshadefx::uniform_info &constant : effect.module.spec_constants)
{
const uint32_t id = static_cast<uint32_t>(spec_constants.size());
const uint32_t offset = static_cast<uint32_t>(spec_data.size());