forked from crosire/reshade
-
Notifications
You must be signed in to change notification settings - Fork 2
/
runtime.cpp
4859 lines (4149 loc) · 181 KB
/
runtime.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
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "version.h"
#include "dll_log.hpp"
#include "dll_resources.hpp"
#include "ini_file.hpp"
#include "addon_manager.hpp"
#include "runtime.hpp"
#include "runtime_objects.hpp"
#include "effect_parser.hpp"
#include "effect_codegen.hpp"
#include "effect_preprocessor.hpp"
#include "input.hpp"
#include "input_gamepad.hpp"
#include "com_ptr.hpp"
#include "platform_utils.hpp"
#include <set>
#include <thread>
#include <cctype>
#include <cstring>
#include <fstream>
#include <algorithm>
#include <numeric>
#if 0
#include <fpng.h>
#include <stb_image.h>
#include <stb_image_dds.h>
#include <stb_image_write.h>
#include <stb_image_resize.h>
#endif
#include <d3dcompiler.h>
#if RESHADE_FX
bool resolve_path(std::filesystem::path &path, std::error_code &ec)
{
// First convert path to an absolute path
// Ignore the working directory and instead start relative paths at the DLL location
if (path.is_relative())
path = std::filesystem::absolute(g_reshade_base_path / path, ec);
// Finally try to canonicalize the path too
if (std::filesystem::path canonical_path = std::filesystem::canonical(path, ec); !ec)
path = std::move(canonical_path);
return !ec; // The canonicalization step fails if the path does not exist
}
bool resolve_preset_path(std::filesystem::path &path, std::error_code &ec)
{
ec.clear();
// First make sure the extension matches, before diving into the file system
if (const std::filesystem::path ext = path.extension();
ext != L".ini" && ext != L".txt")
return false;
// A non-existent path is valid for a new preset
// Otherwise ensure the file has a technique list, which should make it a preset
return !resolve_path(path, ec) || ini_file::load_cache(path).has({}, "Techniques");
}
static std::filesystem::path make_relative_path(const std::filesystem::path &path)
{
if (path.empty())
return path;
// Use ReShade DLL directory as base for relative paths (see 'resolve_path')
std::filesystem::path proximate_path = path.lexically_proximate(g_reshade_base_path);
if (proximate_path.native().rfind(L"..", 0) != std::wstring::npos)
return path; // Do not use relative path if preset is in a parent directory
if (proximate_path.is_relative())
// Prefix preset path with dot character to better indicate it being a relative path
proximate_path = L"." / proximate_path;
return proximate_path;
}
static bool find_file(const std::vector<std::filesystem::path> &search_paths, std::filesystem::path &path)
{
std::error_code ec;
// Do not have to perform a search if the path is already absolute
if (path.is_absolute())
return std::filesystem::exists(path, ec);
for (std::filesystem::path search_path : search_paths)
{
const bool recursive_search = search_path.filename() == L"**";
if (recursive_search)
search_path.remove_filename();
// Append relative file path to absolute search path
if (std::filesystem::path search_sub_path = search_path / path;
resolve_path(search_sub_path, ec))
{
path = std::move(search_sub_path);
return true;
}
if (recursive_search)
{
for (const std::filesystem::directory_entry &entry : std::filesystem::recursive_directory_iterator(search_path, std::filesystem::directory_options::skip_permission_denied, ec))
{
if (!entry.is_directory(ec))
continue;
if (std::filesystem::path search_sub_path = entry / path;
resolve_path(search_sub_path, ec))
{
path = std::move(search_sub_path);
return true;
}
}
}
}
return false;
}
static std::vector<std::filesystem::path> find_files(const std::vector<std::filesystem::path> &search_paths, std::initializer_list<std::filesystem::path> extensions)
{
std::error_code ec;
std::vector<std::filesystem::path> files;
std::vector<std::pair<std::filesystem::path, bool>> resolved_search_paths;
// First resolve all search paths and ensure they are all unique
for (std::filesystem::path search_path : search_paths)
{
const bool recursive_search = search_path.filename() == L"**";
if (recursive_search)
search_path.remove_filename();
if (resolve_path(search_path, ec))
{
if (const auto it = std::find_if(resolved_search_paths.begin(), resolved_search_paths.end(),
[&search_path](const std::pair<std::filesystem::path, bool> &recursive_search_path) {
return recursive_search_path.first == search_path;
});
it != resolved_search_paths.end())
it->second |= recursive_search;
else
resolved_search_paths.push_back(std::make_pair(std::move(search_path), recursive_search));
}
else
{
LOG(WARN) << "Failed to resolve search path " << search_path << " with error code " << ec.value() << '.';
}
}
// Then iterate through all files in those search paths and add those with a matching extension
const auto check_and_add_file = [&extensions, &ec, &files](const std::filesystem::directory_entry &entry) {
if (!entry.is_directory(ec) &&
std::find(extensions.begin(), extensions.end(), entry.path().extension()) != extensions.end())
files.emplace_back(entry); // Construct path from directory entry in-place
};
for (const std::pair<std::filesystem::path, bool> &resolved_search_path : resolved_search_paths)
{
if (resolved_search_path.second)
for (const std::filesystem::directory_entry &entry : std::filesystem::recursive_directory_iterator(resolved_search_path.first, std::filesystem::directory_options::skip_permission_denied, ec))
check_and_add_file(entry);
else
for (const std::filesystem::directory_entry &entry : std::filesystem::directory_iterator(resolved_search_path.first, std::filesystem::directory_options::skip_permission_denied, ec))
check_and_add_file(entry);
}
return files;
}
static inline int format_color_bit_depth(reshade::api::format value)
{
switch (value)
{
default:
assert(false);
return 0;
case reshade::api::format::b5g6r5_unorm:
case reshade::api::format::b5g5r5a1_unorm:
case reshade::api::format::b5g5r5x1_unorm:
return 5;
case reshade::api::format::r8g8b8a8_typeless:
case reshade::api::format::r8g8b8a8_unorm:
case reshade::api::format::r8g8b8a8_unorm_srgb:
case reshade::api::format::r8g8b8x8_unorm:
case reshade::api::format::r8g8b8x8_unorm_srgb:
case reshade::api::format::b8g8r8a8_typeless:
case reshade::api::format::b8g8r8a8_unorm:
case reshade::api::format::b8g8r8a8_unorm_srgb:
case reshade::api::format::b8g8r8x8_typeless:
case reshade::api::format::b8g8r8x8_unorm:
case reshade::api::format::b8g8r8x8_unorm_srgb:
return 8;
case reshade::api::format::r10g10b10a2_typeless:
case reshade::api::format::r10g10b10a2_unorm:
case reshade::api::format::r10g10b10a2_xr_bias:
case reshade::api::format::b10g10r10a2_typeless:
case reshade::api::format::b10g10r10a2_unorm:
return 10;
case reshade::api::format::r11g11b10_float:
return 11;
case reshade::api::format::r16g16b16a16_typeless:
case reshade::api::format::r16g16b16a16_float:
return 16;
case reshade::api::format::r32g32b32_typeless:
case reshade::api::format::r32g32b32_float:
case reshade::api::format::r32g32b32a32_typeless:
case reshade::api::format::r32g32b32a32_float:
return 32;
}
}
#endif
static std::atomic<unsigned int> s_runtime_index = 0;
reshade::runtime::runtime(api::device *device, api::command_queue *graphics_queue) :
_device(device),
_graphics_queue(graphics_queue),
_start_time(std::chrono::high_resolution_clock::now()),
_last_present_time(_start_time),
_last_frame_duration(std::chrono::milliseconds(1)),
#if RESHADE_FX
_effect_search_paths({ L".\\" }),
_texture_search_paths({ L".\\" }),
#endif
_config_path(g_reshade_base_path / L"ReShade.ini"),
_screenshot_path(L".\\"),
_screenshot_name("%AppName% %Date% %Time%"),
_screenshot_post_save_command_arguments("\"%TargetPath%\""),
_screenshot_post_save_command_working_directory(L".\\")
{
assert(device != nullptr && graphics_queue != nullptr);
_needs_update = check_for_update(_latest_version);
// Default shortcut PrtScrn
_screenshot_key_data[0] = 0x2C;
// Increase global runtime index
const unsigned int runtime_index = s_runtime_index++;
// Fall back to alternative configuration file name if it exists
std::error_code ec;
if (std::filesystem::path config_path_alt = g_reshade_base_path / g_reshade_dll_path.filename().replace_extension(L".ini");
std::filesystem::exists(config_path_alt, ec) && !std::filesystem::exists(_config_path, ec))
{
_config_path = std::move(config_path_alt);
}
// Add an index to the config file name in case there are multiple runtimes
else if (runtime_index != 0)
{
const std::filesystem::path config_path_default = _config_path;
_config_path.replace_filename(L"ReShade" + std::to_wstring(runtime_index + 1) + L".ini");
if (std::filesystem::exists(config_path_default, ec) && !std::filesystem::exists(_config_path, ec))
std::filesystem::copy_file(config_path_default, _config_path, ec);
}
#if RESHADE_GUI
init_gui();
#endif
load_config();
//fpng::fpng_init();
}
reshade::runtime::~runtime()
{
assert(_worker_threads.empty());
#if RESHADE_FX
assert(!_is_initialized && _techniques.empty() && _technique_sorting.empty());
#endif
#if RESHADE_GUI
// Save configuration before shutting down to ensure the current window state is written to disk
save_config();
ini_file::flush_cache(_config_path);
deinit_gui();
#endif
// Decrease global runtime index
--s_runtime_index;
}
bool reshade::runtime::on_init(input::window_handle window)
{
assert(!_is_initialized);
const api::resource_desc back_buffer_desc = _device->get_resource_desc(get_back_buffer(0));
_width = back_buffer_desc.texture.width;
_height = back_buffer_desc.texture.height;
_back_buffer_format = api::format_to_default_typed(back_buffer_desc.texture.format);
_back_buffer_samples = back_buffer_desc.texture.samples;
// Create resolve texture and copy pipeline (do this before creating effect resources, to ensure correct back buffer format is set up)
if (back_buffer_desc.texture.samples > 1
// Always use resolve texture in OpenGL to flip vertically and support sRGB + binding effect stencil
|| _device->get_api() == api::device_api::opengl
#if RESHADE_FX
// Some effects rely on there being an alpha channel available, so create resolve texture if that is not the case
|| (_back_buffer_format == api::format::r8g8b8x8_unorm || _back_buffer_format == api::format::b8g8r8x8_unorm)
#endif
)
{
#if RESHADE_FX
switch (_back_buffer_format)
{
case api::format::r8g8b8x8_unorm:
_back_buffer_format = api::format::r8g8b8a8_unorm;
break;
case api::format::b8g8r8x8_unorm:
_back_buffer_format = api::format::b8g8r8a8_unorm;
break;
}
#endif
const bool need_copy_pipeline =
_device->get_api() == api::device_api::d3d10 ||
_device->get_api() == api::device_api::d3d11 ||
_device->get_api() == api::device_api::d3d12;
api::resource_usage usage = api::resource_usage::render_target | api::resource_usage::copy_dest | api::resource_usage::resolve_dest;
if (need_copy_pipeline)
usage |= api::resource_usage::shader_resource;
else
usage |= api::resource_usage::copy_source;
if (!_device->create_resource(
api::resource_desc(_width, _height, 1, 1, api::format_to_typeless(_back_buffer_format), 1, api::memory_heap::gpu_only, usage),
nullptr, back_buffer_desc.texture.samples == 1 ? api::resource_usage::copy_dest : api::resource_usage::resolve_dest, &_back_buffer_resolved) ||
!_device->create_resource_view(
_back_buffer_resolved,
api::resource_usage::render_target,
api::resource_view_desc(api::format_to_default_typed(_back_buffer_format, 0)),
&_back_buffer_targets.emplace_back()) ||
!_device->create_resource_view(
_back_buffer_resolved,
api::resource_usage::render_target,
api::resource_view_desc(api::format_to_default_typed(_back_buffer_format, 1)),
&_back_buffer_targets.emplace_back()))
{
LOG(ERROR) << "Failed to create resolve texture resource!";
goto exit_failure;
}
if (need_copy_pipeline)
{
if (!_device->create_resource_view(
_back_buffer_resolved,
api::resource_usage::shader_resource,
api::resource_view_desc(_back_buffer_format),
&_back_buffer_resolved_srv))
{
LOG(ERROR) << "Failed to create resolve shader resource view!";
goto exit_failure;
}
api::sampler_desc sampler_desc = {};
sampler_desc.filter = api::filter_mode::min_mag_mip_point;
sampler_desc.address_u = api::texture_address_mode::clamp;
sampler_desc.address_v = api::texture_address_mode::clamp;
sampler_desc.address_w = api::texture_address_mode::clamp;
api::pipeline_layout_param layout_params[2];
layout_params[0] = api::descriptor_range { 0, 0, 0, 1, api::shader_stage::all, 1, api::descriptor_type::sampler };
layout_params[1] = api::descriptor_range { 0, 0, 0, 1, api::shader_stage::all, 1, api::descriptor_type::shader_resource_view };
const resources::data_resource vs = resources::load_data_resource(IDR_FULLSCREEN_VS);
const resources::data_resource ps = resources::load_data_resource(IDR_COPY_PS);
api::shader_desc vs_desc = { vs.data, vs.data_size };
api::shader_desc ps_desc = { ps.data, ps.data_size };
std::vector<api::pipeline_subobject> subobjects;
subobjects.push_back({ api::pipeline_subobject_type::vertex_shader, 1, &vs_desc });
subobjects.push_back({ api::pipeline_subobject_type::pixel_shader, 1, &ps_desc });
if (!_device->create_pipeline_layout(2, layout_params, &_copy_pipeline_layout) ||
!_device->create_pipeline(_copy_pipeline_layout, static_cast<uint32_t>(subobjects.size()), subobjects.data(), &_copy_pipeline) ||
!_device->create_sampler(sampler_desc, &_copy_sampler_state))
{
LOG(ERROR) << "Failed to create copy pipeline!";
goto exit_failure;
}
}
}
#if RESHADE_FX
// Create an empty texture, which is bound to shader resource view slots with an unknown semantic (since it is not valid to bind a zero handle in Vulkan, unless the 'VK_EXT_robustness2' extension is enabled)
if (_empty_tex == 0)
{
// 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)
if (!_device->create_resource(
api::resource_desc(1, 1, 1, 1, api::format::r16_float, 1, api::memory_heap::gpu_only, api::resource_usage::shader_resource),
nullptr, api::resource_usage::shader_resource, &_empty_tex))
{
LOG(ERROR) << "Failed to create empty texture resource!";
goto exit_failure;
}
_device->set_resource_name(_empty_tex, "ReShade empty texture");
if (!_device->create_resource_view(_empty_tex, api::resource_usage::shader_resource, api::resource_view_desc(api::format::r16_float), &_empty_srv))
{
LOG(ERROR) << "Failed to create empty texture shader resource view!";
goto exit_failure;
}
}
// Create effect color and stencil resource
if (_effect_stencil_format == api::format::unknown)
{
// Find a supported stencil format with the smallest footprint (since the depth component is not used)
constexpr api::format possible_stencil_formats[] = {
api::format::s8_uint,
api::format::d16_unorm_s8_uint,
api::format::d24_unorm_s8_uint,
api::format::d32_float_s8_uint
};
for (const api::format format : possible_stencil_formats)
{
if (_device->check_format_support(format, api::resource_usage::depth_stencil))
{
_effect_stencil_format = format;
break;
}
}
}
if (!update_effect_color_and_stencil_tex(_width, _height, _back_buffer_format, _effect_stencil_format))
goto exit_failure;
#endif
// Create render targets for the back buffer resources
for (uint32_t i = 0; i < get_back_buffer_count(); ++i)
{
const api::resource back_buffer_resource = get_back_buffer(i);
if (!_device->create_resource_view(
back_buffer_resource,
api::resource_usage::render_target,
api::resource_view_desc(
back_buffer_desc.texture.samples > 1 ? api::resource_view_type::texture_2d_multisample : api::resource_view_type::texture_2d,
api::format_to_default_typed(back_buffer_desc.texture.format, 0), 0, 1, 0, 1),
&_back_buffer_targets.emplace_back()) ||
!_device->create_resource_view(
back_buffer_resource,
api::resource_usage::render_target,
api::resource_view_desc(
back_buffer_desc.texture.samples > 1 ? api::resource_view_type::texture_2d_multisample : api::resource_view_type::texture_2d,
api::format_to_default_typed(back_buffer_desc.texture.format, 1), 0, 1, 0, 1),
&_back_buffer_targets.emplace_back()))
{
LOG(ERROR) << "Failed to create back buffer render targets!";
goto exit_failure;
}
}
#if RESHADE_GUI
if (!init_imgui_resources())
goto exit_failure;
// if (_is_vr && !init_gui_vr())
// goto exit_failure;
#endif
if (window != nullptr && !_is_vr)
_input = input::register_window(window);
else
_input.reset();
// GTK 3 enables transparency for windows, which messes with effects that do not return an alpha value, so disable that again
if (window != nullptr)
utils::set_window_transparency(window, global_config().get("APP", "EnableTransparency"));
// Reset frame count to zero so effects are loaded in 'update_effects'
_frame_count = 0;
_is_initialized = true;
_last_reload_time = std::chrono::high_resolution_clock::now(); // Intentionally set to current time, so that duration to last reload is valid even when there is no reload on init
_preset_save_successfull = true;
_last_screenshot_save_successfull = true;
#if RESHADE_ADDON
invoke_addon_event<addon_event::init_effect_runtime>(this);
#endif
LOG(INFO) << "Recreated runtime environment on runtime " << this << " (" << _config_path << ").";
return true;
exit_failure:
#if RESHADE_FX
_device->destroy_resource(_empty_tex);
_empty_tex = {};
_device->destroy_resource_view(_empty_srv);
_empty_srv = {};
_device->destroy_resource(_effect_color_tex);
_effect_color_tex = {};
_device->destroy_resource_view(_effect_color_srv[0]);
_effect_color_srv[0] = {};
_device->destroy_resource_view(_effect_color_srv[1]);
_effect_color_srv[1] = {};
_device->destroy_resource(_effect_stencil_tex);
_effect_stencil_tex = {};
_device->destroy_resource_view(_effect_stencil_dsv);
_effect_stencil_dsv = {};
#endif
_device->destroy_pipeline(_copy_pipeline);
_copy_pipeline = {};
_device->destroy_pipeline_layout(_copy_pipeline_layout);
_copy_pipeline_layout = {};
_device->destroy_sampler(_copy_sampler_state);
_copy_sampler_state = {};
_device->destroy_resource(_back_buffer_resolved);
_back_buffer_resolved = {};
_device->destroy_resource_view(_back_buffer_resolved_srv);
_back_buffer_resolved_srv = {};
for (const api::resource_view view : _back_buffer_targets)
_device->destroy_resource_view(view);
_back_buffer_targets.clear();
#if RESHADE_GUI
// if (_is_vr)
// deinit_gui_vr();
destroy_imgui_resources();
#endif
return false;
}
void reshade::runtime::on_reset()
{
if (_is_initialized)
// Update initialization state immediately, so that any effect loading still in progress can abort early
_is_initialized = false;
else
return; // Nothing to do if the runtime was already destroyed or not successfully initialized in the first place
#if RESHADE_FX
// Already performs a wait for idle, so no need to do it again before destroying resources below
destroy_effects();
_device->destroy_resource(_empty_tex);
_empty_tex = {};
_device->destroy_resource_view(_empty_srv);
_empty_srv = {};
_device->destroy_resource(_effect_color_tex);
_effect_color_tex = {};
_device->destroy_resource_view(_effect_color_srv[0]);
_effect_color_srv[0] = {};
_device->destroy_resource_view(_effect_color_srv[1]);
_effect_color_srv[1] = {};
_device->destroy_resource(_effect_stencil_tex);
_effect_stencil_tex = {};
_device->destroy_resource_view(_effect_stencil_dsv);
_effect_stencil_dsv = {};
#else
for (std::thread &thread : _worker_threads)
if (thread.joinable())
thread.join();
_worker_threads.clear();
#endif
_device->destroy_pipeline(_copy_pipeline);
_copy_pipeline = {};
_device->destroy_pipeline_layout(_copy_pipeline_layout);
_copy_pipeline_layout = {};
_device->destroy_sampler(_copy_sampler_state);
_copy_sampler_state = {};
_device->destroy_resource(_back_buffer_resolved);
_back_buffer_resolved = {};
_device->destroy_resource_view(_back_buffer_resolved_srv);
_back_buffer_resolved_srv = {};
for (const api::resource_view view : _back_buffer_targets)
_device->destroy_resource_view(view);
_back_buffer_targets.clear();
_width = _height = 0;
#if RESHADE_GUI
// if (_is_vr)
// deinit_gui_vr();
destroy_imgui_resources();
#endif
#if RESHADE_ADDON
invoke_addon_event<addon_event::destroy_effect_runtime>(this);
#endif
LOG(INFO) << "Destroyed runtime environment on runtime " << this << " (" << _config_path << ").";
}
void reshade::runtime::on_present()
{
assert(is_initialized());
#if RESHADE_ADDON
_is_in_present_call = true;
_should_block_effect_reload = false;
#endif
api::command_list *const cmd_list = _graphics_queue->get_immediate_command_list();
uint32_t back_buffer_index = get_current_back_buffer_index();
const api::resource back_buffer_resource = get_back_buffer(back_buffer_index);
// Resolve MSAA back buffer if MSAA is active or copy when format conversion is required
if (_back_buffer_resolved != 0)
{
if (_back_buffer_samples == 1)
{
cmd_list->barrier(back_buffer_resource, api::resource_usage::present, api::resource_usage::copy_source);
cmd_list->copy_texture_region(back_buffer_resource, 0, nullptr, _back_buffer_resolved, 0, nullptr);
cmd_list->barrier(_back_buffer_resolved, api::resource_usage::copy_dest, api::resource_usage::render_target);
}
else
{
cmd_list->barrier(back_buffer_resource, api::resource_usage::present, api::resource_usage::resolve_source);
cmd_list->resolve_texture_region(back_buffer_resource, 0, nullptr, _back_buffer_resolved, 0, 0, 0, 0, _back_buffer_format);
cmd_list->barrier(_back_buffer_resolved, api::resource_usage::resolve_dest, api::resource_usage::render_target);
}
}
#if RESHADE_FX
update_effects();
if (_effects_enabled && !_effects_rendered_this_frame)
{
if (_should_save_screenshot && _screenshot_save_before)
save_screenshot(" original");
if (_back_buffer_resolved != 0)
{
runtime::render_effects(cmd_list, _back_buffer_targets[0], _back_buffer_targets[1]);
}
else
{
cmd_list->barrier(back_buffer_resource, api::resource_usage::present, api::resource_usage::render_target);
runtime::render_effects(cmd_list, _back_buffer_targets[back_buffer_index * 2], _back_buffer_targets[back_buffer_index * 2 + 1]);
cmd_list->barrier(back_buffer_resource, api::resource_usage::render_target, api::resource_usage::present);
}
}
#endif
if (_should_save_screenshot)
save_screenshot();
_frame_count++;
const auto current_time = std::chrono::high_resolution_clock::now();
_last_frame_duration = current_time - _last_present_time; _last_present_time = current_time;
#ifdef NDEBUG
// Lock input so it cannot be modified by other threads while we are reading it here
const std::shared_lock<std::shared_mutex> input_lock = (_input != nullptr) ?
_input->lock() : std::shared_lock<std::shared_mutex>();
#endif
#if RESHADE_GUI
// Draw overlay
// if (_is_vr)
// draw_gui_vr();
// else
// draw_gui();
if (_should_save_screenshot && _screenshot_save_gui && (_show_overlay
#if RESHADE_FX
|| (_preview_texture != 0 && _effects_enabled)
#endif
))
save_screenshot(" overlay");
#endif
// All screenshots were created at this point, so reset request
_should_save_screenshot = false;
// Handle keyboard shortcuts
if (!_ignore_shortcuts && _input != nullptr)
{
#if RESHADE_FX
if (_input->is_key_pressed(_effects_key_data, _force_shortcut_modifiers))
_effects_enabled = !_effects_enabled;
#endif
if (_input->is_key_pressed(_screenshot_key_data, _force_shortcut_modifiers))
{
_screenshot_count++;
_should_save_screenshot = true; // Remember that we want to save a screenshot next frame
}
#if RESHADE_FX
// Do not allow the following shortcuts while effects are being loaded or initialized (since they affect that state)
if (!is_loading())
{
if (_input->is_key_pressed(_reload_key_data, _force_shortcut_modifiers))
reload_effects();
if (_input->is_key_pressed(_performance_mode_key_data, _force_shortcut_modifiers))
{
_performance_mode = !_performance_mode;
save_config();
reload_effects();
}
if (const bool reversed = _input->is_key_pressed(_prev_preset_key_data, _force_shortcut_modifiers);
reversed || _input->is_key_pressed(_next_preset_key_data, _force_shortcut_modifiers))
{
// The preset shortcut key was pressed down, so start the transition
if (switch_to_next_preset(_current_preset_path.parent_path(), reversed))
save_config();
}
else
{
for (const preset_shortcut &shortcut : _preset_shortcuts)
{
if (_input->is_key_pressed(shortcut.key_data, _force_shortcut_modifiers))
{
if (switch_to_next_preset(shortcut.preset_path))
save_config();
break;
}
}
}
// Continuously update preset values while a transition is in progress
if (_is_in_between_presets_transition)
load_current_preset();
}
#endif
}
// Stretch main render target back into MSAA back buffer if MSAA is active or copy when format conversion is required
if (_back_buffer_resolved != 0)
{
const api::resource resources[2] = { back_buffer_resource, _back_buffer_resolved };
const api::resource_usage state_old[2] = { api::resource_usage::copy_source | api::resource_usage::resolve_source, api::resource_usage::render_target };
const api::resource_usage state_final[2] = { api::resource_usage::present, api::resource_usage::resolve_dest };
if (_device->get_api() == api::device_api::d3d10 ||
_device->get_api() == api::device_api::d3d11 ||
_device->get_api() == api::device_api::d3d12)
{
const api::resource_usage state_new[2] = { api::resource_usage::render_target, api::resource_usage::shader_resource };
cmd_list->barrier(2, resources, state_old, state_new);
cmd_list->bind_pipeline(api::pipeline_stage::all_graphics, _copy_pipeline);
cmd_list->push_descriptors(api::shader_stage::pixel, _copy_pipeline_layout, 0, api::descriptor_set_update { {}, 0, 0, 1, api::descriptor_type::sampler, &_copy_sampler_state });
cmd_list->push_descriptors(api::shader_stage::pixel, _copy_pipeline_layout, 1, api::descriptor_set_update { {}, 0, 0, 1, api::descriptor_type::shader_resource_view, &_back_buffer_resolved_srv });
const api::viewport viewport = { 0.0f, 0.0f, static_cast<float>(_width), static_cast<float>(_height), 0.0f, 1.0f };
cmd_list->bind_viewports(0, 1, &viewport);
const api::rect scissor_rect = { 0, 0, static_cast<int32_t>(_width), static_cast<int32_t>(_height) };
cmd_list->bind_scissor_rects(0, 1, &scissor_rect);
const bool srgb_write_enable = (_back_buffer_format == api::format::r8g8b8a8_unorm_srgb || _back_buffer_format == api::format::b8g8r8a8_unorm_srgb);
cmd_list->bind_render_targets_and_depth_stencil(1, &_back_buffer_targets[2 + back_buffer_index * 2 + srgb_write_enable]);
cmd_list->draw(3, 1, 0, 0);
cmd_list->barrier(2, resources, state_new, state_final);
}
else
{
const api::resource_usage state_new[2] = { api::resource_usage::copy_dest, api::resource_usage::copy_source };
cmd_list->barrier(2, resources, state_old, state_new);
cmd_list->copy_texture_region(_back_buffer_resolved, 0, nullptr, back_buffer_resource, 0, nullptr);
cmd_list->barrier(2, resources, state_new, state_final);
}
}
#if RESHADE_ADDON
invoke_addon_event<addon_event::reshade_present>(this);
_is_in_present_call = false;
#endif
#if RESHADE_FX
_effects_rendered_this_frame = false;
#endif
// Update input status
if (_input != nullptr)
_input->next_frame();
if (_input_gamepad != nullptr)
_input_gamepad->next_frame();
// Save modified INI files
if (!ini_file::flush_cache())
_preset_save_successfull = false;
#if RESHADE_ADDON_LITE
// Detect high network traffic
extern volatile long g_network_traffic;
static int cooldown = 0, traffic = 0;
if (cooldown-- > 0)
{
traffic += g_network_traffic > 0;
}
else
{
const bool was_enabled = addon_enabled;
addon_enabled = traffic < 10;
traffic = 0;
cooldown = 60;
#if RESHADE_FX
if (addon_enabled != was_enabled)
{
if (was_enabled)
_backup_texture_semantic_bindings = _texture_semantic_bindings;
for (const auto &info : _backup_texture_semantic_bindings)
{
if (info.second.first == _effect_color_srv[0] && info.second.second == _effect_color_srv[1])
continue;
update_texture_bindings(info.first.c_str(), addon_enabled ? info.second.first : api::resource_view { 0 }, addon_enabled ? info.second.second : api::resource_view { 0 });
}
}
#endif
}
if (std::numeric_limits<long>::max() != g_network_traffic)
g_network_traffic = 0;
#endif
}
void reshade::runtime::load_config()
{
const ini_file &config = ini_file::load_cache(_config_path);
if (config.get("INPUT", "GamepadNavigation"))
_input_gamepad = input_gamepad::load();
else
_input_gamepad.reset();
config.get("INPUT", "ForceShortcutModifiers", _force_shortcut_modifiers);
config.get("INPUT", "KeyScreenshot", _screenshot_key_data);
#if RESHADE_FX
config.get("INPUT", "KeyEffects", _effects_key_data);
config.get("INPUT", "KeyNextPreset", _next_preset_key_data);
config.get("INPUT", "KeyPerformanceMode", _performance_mode_key_data);
config.get("INPUT", "KeyPreviousPreset", _prev_preset_key_data);
config.get("INPUT", "KeyReload", _reload_key_data);
config.get("GENERAL", "NoDebugInfo", _no_debug_info);
config.get("GENERAL", "NoEffectCache", _no_effect_cache);
config.get("GENERAL", "NoReloadOnInit", _no_reload_on_init);
config.get("GENERAL", "NoReloadOnInitForNonVR", _no_reload_for_non_vr);
config.get("GENERAL", "EffectSearchPaths", _effect_search_paths);
config.get("GENERAL", "PerformanceMode", _performance_mode);
config.get("GENERAL", "PreprocessorDefinitions", _global_preprocessor_definitions);
config.get("GENERAL", "SkipLoadingDisabledEffects", _effect_load_skipping);
config.get("GENERAL", "TextureSearchPaths", _texture_search_paths);
config.get("GENERAL", "IntermediateCachePath", _effect_cache_path);
config.get("GENERAL", "StartupPresetPath", _startup_preset_path);
config.get("GENERAL", "PresetPath", _current_preset_path);
config.get("GENERAL", "PresetTransitionDuration", _preset_transition_duration);
// Fall back to temp directory if cache path does not exist
std::error_code ec;
if (_effect_cache_path.empty() || !resolve_path(_effect_cache_path, ec))
{
_effect_cache_path = std::filesystem::temp_directory_path(ec) / "ReShade";
std::filesystem::create_directory(_effect_cache_path, ec);
if (ec)
LOG(ERROR) << "Failed to create effect cache directory " << _effect_cache_path << " with error code " << ec.value() << '!';
}
// Use startup preset instead of last selection
if (!_startup_preset_path.empty() && resolve_preset_path(_startup_preset_path, ec))
_current_preset_path = _startup_preset_path;
// Use default if the preset file does not exist yet
else if (!resolve_preset_path(_current_preset_path, ec))
_current_preset_path = g_reshade_base_path / L"ReShadePreset.ini";
std::vector<unsigned int> preset_key_data;
std::vector<std::filesystem::path> preset_shortcut_paths;
config.get("GENERAL", "PresetShortcutKeys", preset_key_data);
config.get("GENERAL", "PresetShortcutPaths", preset_shortcut_paths);
_preset_shortcuts.clear();
for (size_t i = 0; i < preset_shortcut_paths.size() && (i * 4 + 4) <= preset_key_data.size(); ++i)
{
preset_shortcut shortcut;
shortcut.preset_path = preset_shortcut_paths[i];
std::copy_n(&preset_key_data[i * 4], 4, shortcut.key_data);
_preset_shortcuts.push_back(std::move(shortcut));
}
#endif
config.get("SCREENSHOT", "SavePath", _screenshot_path);
config.get("SCREENSHOT", "SoundPath", _screenshot_sound_path);
config.get("SCREENSHOT", "ClearAlpha", _screenshot_clear_alpha);
config.get("SCREENSHOT", "FileFormat", _screenshot_format);
config.get("SCREENSHOT", "FileNaming", _screenshot_name);
config.get("SCREENSHOT", "JPEGQuality", _screenshot_jpeg_quality);
#if RESHADE_FX
config.get("SCREENSHOT", "SaveBeforeShot", _screenshot_save_before);
config.get("SCREENSHOT", "SavePresetFile", _screenshot_include_preset);
#endif
#if RESHADE_GUI
config.get("SCREENSHOT", "SaveOverlayShot", _screenshot_save_gui);
#endif
config.get("SCREENSHOT", "PostSaveCommand", _screenshot_post_save_command);
config.get("SCREENSHOT", "PostSaveCommandArguments", _screenshot_post_save_command_arguments);
config.get("SCREENSHOT", "PostSaveCommandWorkingDirectory", _screenshot_post_save_command_working_directory);
config.get("SCREENSHOT", "PostSaveCommandNoWindow", _screenshot_post_save_command_no_window);
#if RESHADE_GUI
load_config_gui(config);
#endif
}
void reshade::runtime::save_config() const
{
ini_file &config = ini_file::load_cache(_config_path);
config.set("INPUT", "ForceShortcutModifiers", _force_shortcut_modifiers);
config.set("INPUT", "KeyScreenshot", _screenshot_key_data);
#if RESHADE_FX
config.set("INPUT", "KeyEffects", _effects_key_data);
config.set("INPUT", "KeyNextPreset", _next_preset_key_data);
config.set("INPUT", "KeyPerformanceMode", _performance_mode_key_data);
config.set("INPUT", "KeyPreviousPreset", _prev_preset_key_data);
config.set("INPUT", "KeyReload", _reload_key_data);
config.set("GENERAL", "NoDebugInfo", _no_debug_info);
config.set("GENERAL", "NoEffectCache", _no_effect_cache);
config.set("GENERAL", "NoReloadOnInit", _no_reload_on_init);
config.set("GENERAL", "NoReloadOnInitForNonVR", _no_reload_for_non_vr);
config.set("GENERAL", "EffectSearchPaths", _effect_search_paths);
config.set("GENERAL", "PerformanceMode", _performance_mode);
config.set("GENERAL", "PreprocessorDefinitions", _global_preprocessor_definitions);
config.set("GENERAL", "SkipLoadingDisabledEffects", _effect_load_skipping);
config.set("GENERAL", "TextureSearchPaths", _texture_search_paths);
config.set("GENERAL", "IntermediateCachePath", _effect_cache_path);
config.set("GENERAL", "StartupPresetPath", make_relative_path(_startup_preset_path));
config.set("GENERAL", "PresetPath", make_relative_path(_current_preset_path));
config.set("GENERAL", "PresetTransitionDuration", _preset_transition_duration);
std::vector<unsigned int> preset_key_data;
std::vector<std::filesystem::path> preset_shortcut_paths;
for (const preset_shortcut &shortcut : _preset_shortcuts)
{
if (shortcut.key_data[0] == 0)
continue;
preset_key_data.push_back(shortcut.key_data[0]);
preset_key_data.push_back(shortcut.key_data[1]);
preset_key_data.push_back(shortcut.key_data[2]);
preset_key_data.push_back(shortcut.key_data[3]);
preset_shortcut_paths.push_back(shortcut.preset_path);
}
config.set("GENERAL", "PresetShortcutKeys", preset_key_data);
config.set("GENERAL", "PresetShortcutPaths", preset_shortcut_paths);
#endif
config.set("SCREENSHOT", "SavePath", _screenshot_path);
config.set("SCREENSHOT", "SoundPath", _screenshot_sound_path);
config.set("SCREENSHOT", "ClearAlpha", _screenshot_clear_alpha);
config.set("SCREENSHOT", "FileFormat", _screenshot_format);
config.set("SCREENSHOT", "FileNaming", _screenshot_name);
config.set("SCREENSHOT", "JPEGQuality", _screenshot_jpeg_quality);
#if RESHADE_FX
config.set("SCREENSHOT", "SaveBeforeShot", _screenshot_save_before);
config.set("SCREENSHOT", "SavePresetFile", _screenshot_include_preset);
#endif
#if RESHADE_GUI
config.set("SCREENSHOT", "SaveOverlayShot", _screenshot_save_gui);
#endif
config.set("SCREENSHOT", "PostSaveCommand", _screenshot_post_save_command);
config.set("SCREENSHOT", "PostSaveCommandArguments", _screenshot_post_save_command_arguments);
config.set("SCREENSHOT", "PostSaveCommandWorkingDirectory", _screenshot_post_save_command_working_directory);
config.set("SCREENSHOT", "PostSaveCommandNoWindow", _screenshot_post_save_command_no_window);
#if RESHADE_GUI
save_config_gui(config);
#endif
}
#if RESHADE_FX
void reshade::runtime::load_current_preset()
{
_preset_save_successfull = true;
const ini_file &preset = ini_file::load_cache(_current_preset_path);