forked from crosire/reshade
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runtime.cpp
2122 lines (1838 loc) · 80 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. All rights reserved.
* License: https://github.com/crosire/reshade#license
*/
#include "version.h"
#include "dll_log.hpp"
#include "dll_config.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_freepie.hpp"
#include <set>
#include <thread>
#include <algorithm>
#include <stb_image.h>
#include <stb_image_dds.h>
#include <stb_image_write.h>
#include <stb_image_resize.h>
extern volatile long g_network_traffic;
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
path = std::filesystem::absolute(g_reshade_base_path / path, ec);
// Finally try to canonicalize the path too
if (auto 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)
{
// 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) || reshade::ini_file::load_cache(path).has({}, "Techniques");
}
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)
// Append relative file path to absolute search path
if (search_path /= path; resolve_path(search_path))
return path = std::move(search_path), 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;
for (std::filesystem::path search_path : search_paths)
if (resolve_path(search_path))
for (const std::filesystem::directory_entry &entry : std::filesystem::directory_iterator(search_path, std::filesystem::directory_options::skip_permission_denied, ec))
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
return files;
}
reshade::runtime::runtime() :
_start_time(std::chrono::high_resolution_clock::now()),
_last_present_time(std::chrono::high_resolution_clock::now()),
_last_frame_duration(std::chrono::milliseconds(1)),
_effect_search_paths({ L".\\" }),
_texture_search_paths({ L".\\" }),
_reload_key_data(),
_performance_mode_key_data(),
_effects_key_data(),
_screenshot_key_data(),
_prev_preset_key_data(),
_next_preset_key_data(),
_config_path(g_reshade_base_path / L"ReShade.ini"),
_screenshot_path(g_reshade_base_path)
{
_needs_update = check_for_update(_latest_version);
// Default shortcut PrtScrn
_screenshot_key_data[0] = 0x2C;
// 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);
#if RESHADE_GUI
init_gui();
#endif
load_config();
}
reshade::runtime::~runtime()
{
assert(_worker_threads.empty());
assert(!_is_initialized && _techniques.empty());
#if RESHADE_GUI
deinit_gui();
#endif
}
bool reshade::runtime::on_init(input::window_handle window)
{
assert(!_is_initialized);
if (window != nullptr)
_input = input::register_window(window);
else
_input = std::make_shared<input>(nullptr);
// Reset frame count to zero so effects are loaded in 'update_and_render_effects'
_framecount = 0;
_is_initialized = true;
_last_reload_time = std::chrono::high_resolution_clock::now();
_preset_save_success = true;
_screenshot_save_success = true;
RESHADE_ADDON_EVENT(init_effect_runtime, this);
LOG(INFO) << "Recreated runtime environment on runtime " << this << '.';
return true;
}
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
unload_effects();
_width = _height = 0;
#if RESHADE_GUI
if (_imgui_font_atlas != nullptr)
destroy_texture(*_imgui_font_atlas);
_rebuild_font_atlas = true;
#endif
RESHADE_ADDON_EVENT(destroy_effect_runtime, this);
LOG(INFO) << "Destroyed runtime environment on runtime " << this << '.';
}
void reshade::runtime::on_present()
{
_framecount++;
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 auto input_lock = _input->lock();
#endif
#if RESHADE_GUI
// Draw overlay
draw_gui();
if (_should_save_screenshot && _screenshot_save_gui && (_show_overlay || (_preview_texture != nullptr && _effects_enabled)))
save_screenshot(L" overlay");
#endif
// All screenshots were created at this point, so reset request
_should_save_screenshot = false;
// Handle keyboard shortcuts
if (!_ignore_shortcuts)
{
if (_input->is_key_pressed(_effects_key_data, _force_shortcut_modifiers))
_effects_enabled = !_effects_enabled;
if (_input->is_key_pressed(_screenshot_key_data, _force_shortcut_modifiers))
_should_save_screenshot = true; // Notify 'update_and_render_effects' that we want to save a screenshot next frame
// Do not allow the next shortcuts while effects are being loaded or compiled (since they affect that state)
if (!is_loading() && _reload_compile_queue.empty())
{
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))
{
_last_preset_switching_time = current_time;
_is_in_between_presets_transition = true;
save_config();
}
}
// Continuously update preset values while a transition is in progress
if (_is_in_between_presets_transition)
load_current_preset();
}
}
// Reset input status
_input->next_frame();
// Save modified INI files
if (!ini_file::flush_cache())
_preset_save_success = false;
#if RESHADE_ADDON
// Detect high network traffic
static int cooldown = 0, traffic = 0;
if (cooldown-- > 0)
{
traffic += g_network_traffic > 0;
}
else
{
addon::enable_or_disable_addons(traffic < 10);
traffic = 0;
cooldown = 60;
}
#endif
// Reset frame statistics
g_network_traffic = 0;
}
bool reshade::runtime::load_effect(const std::filesystem::path &source_file, const reshade::ini_file &preset, size_t effect_index, bool preprocess_required)
{
std::string attributes;
attributes += "app=" + g_target_executable_path.stem().u8string() + ';';
attributes += "width=" + std::to_string(_width) + ';';
attributes += "height=" + std::to_string(_height) + ';';
attributes += "color_bit_depth=" + std::to_string(_color_bit_depth) + ';';
attributes += "version=" + std::to_string(VERSION_MAJOR * 10000 + VERSION_MINOR * 100 + VERSION_REVISION) + ';';
attributes += "performance_mode=" + std::string(_performance_mode ? "1" : "0") + ';';
attributes += "vendor=" + std::to_string(_vendor_id) + ';';
attributes += "device=" + std::to_string(_device_id) + ';';
std::set<std::filesystem::path> include_paths;
if (source_file.is_absolute())
include_paths.emplace(source_file.parent_path());
for (std::filesystem::path include_path : _effect_search_paths)
if (resolve_path(include_path))
include_paths.emplace(std::move(include_path));
for (const std::filesystem::path &include_path : include_paths)
{
std::error_code ec;
attributes += include_path.u8string();
for (const auto &entry : std::filesystem::directory_iterator(include_path, std::filesystem::directory_options::skip_permission_denied, ec))
{
const std::filesystem::path filename = entry.path().filename();
if (filename == source_file.filename() || filename.extension() == L".fxh")
{
attributes += ',';
attributes += filename.u8string();
attributes += '?';
attributes += std::to_string(entry.last_write_time(ec).time_since_epoch().count());
}
}
attributes += ';';
}
std::vector<std::string> preprocessor_definitions = _global_preprocessor_definitions;
preprocessor_definitions.insert(preprocessor_definitions.end(), _preset_preprocessor_definitions.begin(), _preset_preprocessor_definitions.end());
for (const std::string &definition : preprocessor_definitions)
attributes += definition + ';';
const size_t source_hash = std::hash<std::string>()(attributes);
effect &effect = _effects[effect_index];
const std::string effect_name = source_file.filename().u8string();
if (source_file != effect.source_file || source_hash != effect.source_hash)
{
effect = {};
effect.source_file = source_file;
effect.source_hash = source_hash;
}
if (_effect_load_skipping && !_load_option_disable_skipping && !_worker_threads.empty()) // Only skip during 'load_effects'
{
if (std::vector<std::string> techniques;
preset.get({}, "Techniques", techniques))
{
effect.skipped = std::find_if(techniques.cbegin(), techniques.cend(), [&effect_name](const std::string &technique) {
const size_t at_pos = technique.find('@') + 1;
return at_pos == 0 || technique.find(effect_name, at_pos) == at_pos; }) == techniques.cend();
if (effect.skipped)
{
if (_reload_remaining_effects != 0 && _reload_remaining_effects != std::numeric_limits<size_t>::max())
_reload_remaining_effects--;
return false;
}
}
}
bool source_cached = false; std::string source;
if (!effect.preprocessed && (preprocess_required || (source_cached = load_effect_cache(source_file, source_hash, source)) == false))
{
reshadefx::preprocessor pp;
pp.add_macro_definition("__RESHADE__", std::to_string(VERSION_MAJOR * 10000 + VERSION_MINOR * 100 + VERSION_REVISION));
pp.add_macro_definition("__RESHADE_PERFORMANCE_MODE__", _performance_mode ? "1" : "0");
pp.add_macro_definition("__VENDOR__", std::to_string(_vendor_id));
pp.add_macro_definition("__DEVICE__", std::to_string(_device_id));
pp.add_macro_definition("__RENDERER__", std::to_string(_renderer_id));
pp.add_macro_definition("__APPLICATION__", std::to_string( // Truncate hash to 32-bit, since lexer currently only supports 32-bit numbers anyway
std::hash<std::string>()(g_target_executable_path.stem().u8string()) & 0xFFFFFFFF));
pp.add_macro_definition("BUFFER_WIDTH", std::to_string(_width));
pp.add_macro_definition("BUFFER_HEIGHT", std::to_string(_height));
pp.add_macro_definition("BUFFER_RCP_WIDTH", "(1.0 / BUFFER_WIDTH)");
pp.add_macro_definition("BUFFER_RCP_HEIGHT", "(1.0 / BUFFER_HEIGHT)");
pp.add_macro_definition("BUFFER_COLOR_BIT_DEPTH", std::to_string(_color_bit_depth));
for (const std::string &definition : preprocessor_definitions)
{
if (definition.empty() || definition == "=")
continue; // Skip invalid definitions
const size_t equals_index = definition.find('=');
if (equals_index != std::string::npos)
pp.add_macro_definition(
definition.substr(0, equals_index),
definition.substr(equals_index + 1));
else
pp.add_macro_definition(definition);
}
for (const std::filesystem::path &include_path : include_paths)
pp.add_include_path(include_path);
// Add some conversion macros for compatibility with older versions of ReShade
pp.append_string(
"#define tex2Doffset(s, coords, offset) tex2D(s, coords, offset)\n"
"#define tex2Dlodoffset(s, coords, offset) tex2Dlod(s, coords, offset)\n"
"#define tex2Dgather(s, t, c) tex2Dgather##c(s, t)\n"
"#define tex2Dgatheroffset(s, t, o, c) tex2Dgather##c(s, t, o)\n"
"#define tex2Dgather0 tex2DgatherR\n"
"#define tex2Dgather1 tex2DgatherG\n"
"#define tex2Dgather2 tex2DgatherB\n"
"#define tex2Dgather3 tex2DgatherA\n");
// Load and preprocess the source file
effect.preprocessed = pp.append_file(source_file);
// Append preprocessor errors to the error list
effect.errors += pp.errors();
if (effect.preprocessed)
{
source = std::move(pp.output());
source_cached = save_effect_cache(source_file, source_hash, source);
// Keep track of used preprocessor definitions (so they can be displayed in the overlay)
effect.definitions.clear();
for (const auto &definition : pp.used_macro_definitions())
{
if (definition.first.size() <= 10 || definition.first[0] == '_' || !definition.first.compare(0, 8, "RESHADE_") || !definition.first.compare(0, 7, "BUFFER_"))
continue;
effect.definitions.emplace_back(definition.first, trim(definition.second));
}
std::sort(effect.definitions.begin(), effect.definitions.end());
// Keep track of included files
effect.included_files = pp.included_files();
std::sort(effect.included_files.begin(), effect.included_files.end()); // Sort file names alphabetically
}
}
if (!effect.compiled && !source.empty())
{
unsigned shader_model;
if (_renderer_id == 0x9000)
shader_model = 30; // D3D9
else if (_renderer_id < 0xa100)
shader_model = 40; // D3D10 (including feature level 9)
else if (_renderer_id < 0xb000)
shader_model = 41; // D3D10.1
else if (_renderer_id < 0xc000)
shader_model = 50; // D3D11
else
shader_model = 51; // D3D12
std::unique_ptr<reshadefx::codegen> codegen;
if ((_renderer_id & 0xF0000) == 0)
codegen.reset(reshadefx::create_codegen_hlsl(shader_model, !_no_debug_info, _performance_mode));
else if (_renderer_id < 0x20000)
codegen.reset(reshadefx::create_codegen_glsl(!_no_debug_info, _performance_mode, false, true));
else // Vulkan uses SPIR-V input
codegen.reset(reshadefx::create_codegen_spirv(true, !_no_debug_info, _performance_mode, false, true));
reshadefx::parser parser;
// Compile the pre-processed source code (try the compile even if the preprocessor step failed to get additional error information)
effect.compiled = parser.parse(std::move(source), codegen.get());
// Append parser errors to the error list
effect.errors += parser.errors();
// Write result to effect module
codegen->write_result(effect.module);
if (effect.compiled)
{
effect.uniforms.clear();
// Create space for all variables (aligned to 16 bytes)
effect.uniform_data_storage.resize((effect.module.total_uniform_size + 15) & ~15);
for (uniform variable : effect.module.uniforms)
{
variable.effect_index = effect_index;
// Copy initial data into uniform storage area
reset_uniform_value(variable);
const std::string_view special = variable.annotation_as_string("source");
if (special.empty()) /* Ignore if annotation is missing */;
else if (special == "frametime")
variable.special = special_uniform::frame_time;
else if (special == "framecount")
variable.special = special_uniform::frame_count;
else if (special == "random")
variable.special = special_uniform::random;
else if (special == "pingpong")
variable.special = special_uniform::ping_pong;
else if (special == "date")
variable.special = special_uniform::date;
else if (special == "timer")
variable.special = special_uniform::timer;
else if (special == "key")
variable.special = special_uniform::key;
else if (special == "mousepoint")
variable.special = special_uniform::mouse_point;
else if (special == "mousedelta")
variable.special = special_uniform::mouse_delta;
else if (special == "mousebutton")
variable.special = special_uniform::mouse_button;
else if (special == "mousewheel")
variable.special = special_uniform::mouse_wheel;
else if (special == "freepie")
variable.special = special_uniform::freepie;
else if (special == "ui_open" ||special == "overlay_open")
variable.special = special_uniform::overlay_open;
else if (special == "ui_active" || special == "overlay_active")
variable.special = special_uniform::overlay_active;
else if (special == "ui_hovered" || special == "overlay_hovered")
variable.special = special_uniform::overlay_hovered;
effect.uniforms.push_back(std::move(variable));
}
// Fill all specialization constants with values from the current preset
if (_performance_mode)
{
effect.preamble.clear();
for (reshadefx::uniform_info &constant : effect.module.spec_constants)
{
effect.preamble += "#define SPEC_CONSTANT_" + constant.name + ' ';
switch (constant.type.base)
{
case reshadefx::type::t_int:
preset.get(effect_name, constant.name, constant.initializer_value.as_int);
break;
case reshadefx::type::t_bool:
case reshadefx::type::t_uint:
preset.get(effect_name, constant.name, constant.initializer_value.as_uint);
break;
case reshadefx::type::t_float:
preset.get(effect_name, constant.name, constant.initializer_value.as_float);
break;
}
// Check if this is a split specialization constant and move data accordingly
if (constant.type.is_scalar() && constant.offset != 0)
constant.initializer_value.as_uint[0] = constant.initializer_value.as_uint[constant.offset];
for (unsigned int i = 0; i < constant.type.components(); ++i)
{
switch (constant.type.base)
{
case reshadefx::type::t_bool:
effect.preamble += constant.initializer_value.as_uint[i] ? "true" : "false";
break;
case reshadefx::type::t_int:
effect.preamble += std::to_string(constant.initializer_value.as_int[i]);
break;
case reshadefx::type::t_uint:
effect.preamble += std::to_string(constant.initializer_value.as_uint[i]);
break;
case reshadefx::type::t_float:
effect.preamble += std::to_string(constant.initializer_value.as_float[i]);
break;
}
if (i + 1 < constant.type.components())
effect.preamble += ", ";
}
effect.preamble += '\n';
}
}
}
}
if ( effect.compiled && (effect.preprocessed || source_cached))
{
const std::lock_guard<std::mutex> lock(_reload_mutex);
for (texture texture : effect.module.textures)
{
texture.effect_index = effect_index;
// Try to share textures with the same name across effects
if (const auto existing_texture = std::find_if(_textures.begin(), _textures.end(),
[&texture](const auto &item) { return item.unique_name == texture.unique_name; });
existing_texture != _textures.end())
{
// Cannot share texture if this is a normal one, but the existing one is a reference and vice versa
if (texture.semantic != existing_texture->semantic)
{
effect.errors += "error: " + texture.unique_name + ": another effect (";
effect.errors += _effects[existing_texture->effect_index].source_file.filename().u8string();
effect.errors += ") already created a texture with the same name but different semantic\n";
effect.compiled = false;
break;
}
if (texture.semantic.empty() && !existing_texture->matches_description(texture))
{
effect.errors += "warning: " + texture.unique_name + ": another effect (";
effect.errors += _effects[existing_texture->effect_index].source_file.filename().u8string();
effect.errors += ") already created a texture with the same name but different dimensions\n";
}
if (texture.semantic.empty() && (existing_texture->annotation_as_string("source") != texture.annotation_as_string("source")))
{
effect.errors += "warning: " + texture.unique_name + ": another effect (";
effect.errors += _effects[existing_texture->effect_index].source_file.filename().u8string();
effect.errors += ") already created a texture with a different image file\n";
}
if (existing_texture->semantic == "COLOR" && _color_bit_depth != 8)
{
for (const auto &sampler_info : effect.module.samplers)
{
if (sampler_info.srgb && sampler_info.texture_name == texture.unique_name)
{
effect.errors += "warning: " + sampler_info.unique_name + ": texture does not support sRGB sampling (back buffer format is not RGBA8)";
}
}
}
if (std::find(existing_texture->shared.begin(), existing_texture->shared.end(), effect_index) == existing_texture->shared.end())
existing_texture->shared.push_back(effect_index);
// Always make shared textures render targets, since they may be used as such in a different effect
existing_texture->render_target = true;
existing_texture->storage_access = true;
continue;
}
if (texture.annotation_as_int("pooled") && texture.semantic.empty())
{
// Try to find another pooled texture to share with (and do not share within the same effect)
if (const auto existing_texture = std::find_if(_textures.begin(), _textures.end(),
[&texture](const auto &item) { return item.annotation_as_int("pooled") && item.effect_index != texture.effect_index && item.matches_description(texture); });
existing_texture != _textures.end())
{
// Overwrite referenced texture in samplers with the pooled one
for (auto &sampler_info : effect.module.samplers)
if (sampler_info.texture_name == texture.unique_name)
sampler_info.texture_name = existing_texture->unique_name;
// Overwrite referenced texture in storages with the pooled one
for (auto &storage_info : effect.module.storages)
if (storage_info.texture_name == texture.unique_name)
storage_info.texture_name = existing_texture->unique_name;
// Overwrite referenced texture in render targets with the pooled one
for (auto &technique_info : effect.module.techniques)
{
for (auto &pass_info : technique_info.passes)
{
std::replace(std::begin(pass_info.render_target_names), std::end(pass_info.render_target_names),
texture.unique_name, existing_texture->unique_name);
for (auto &sampler_info : pass_info.samplers)
if (sampler_info.texture_name == texture.unique_name)
sampler_info.texture_name = existing_texture->unique_name;
for (auto &storage_info : pass_info.storages)
if (storage_info.texture_name == texture.unique_name)
storage_info.texture_name = existing_texture->unique_name;
}
}
if (std::find(existing_texture->shared.begin(), existing_texture->shared.end(), effect_index) == existing_texture->shared.end())
existing_texture->shared.push_back(effect_index);
existing_texture->render_target = true;
existing_texture->storage_access = true;
continue;
}
}
if (!texture.semantic.empty() && (texture.semantic != "COLOR" && texture.semantic != "DEPTH"))
effect.errors += "warning: " + texture.unique_name + ": unknown semantic '" + texture.semantic + "'\n";
// This is the first effect using this texture
texture.shared.push_back(effect_index);
_textures.push_back(std::move(texture));
}
for (technique technique : effect.module.techniques)
{
technique.effect_index = effect_index;
technique.hidden = technique.annotation_as_int("hidden") != 0;
if (technique.annotation_as_int("enabled"))
enable_technique(technique);
_techniques.push_back(std::move(technique));
}
}
if (_reload_remaining_effects != 0 && _reload_remaining_effects != std::numeric_limits<size_t>::max())
_reload_remaining_effects--;
else
_reload_remaining_effects = 0; // Force effect initialization in 'update_and_render_effects'
if ( effect.compiled && (effect.preprocessed || source_cached))
{
if (effect.errors.empty())
LOG(INFO) << "Successfully loaded " << source_file << '.';
else
LOG(WARN) << "Successfully loaded " << source_file << " with warnings:\n" << effect.errors;
return true;
}
else
{
_last_reload_successfull = false;
if (effect.errors.empty())
LOG(ERROR) << "Failed to load " << source_file << '!';
else
LOG(ERROR) << "Failed to load " << source_file << ":\n" << effect.errors;
return false;
}
}
void reshade::runtime::load_effects()
{
// Reload preprocessor definitions from current preset before compiling
_preset_preprocessor_definitions.clear();
ini_file &preset = ini_file::load_cache(_current_preset_path);
preset.get({}, "PreprocessorDefinitions", _preset_preprocessor_definitions);
// Build a list of effect files by walking through the effect search paths
const std::vector<std::filesystem::path> effect_files =
find_files(_effect_search_paths, { L".fx" });
if (effect_files.empty())
return; // No effect files found, so nothing more to do
// Have to be initialized at this point or else the threads spawned below will immediately exit without reducing the remaining effects count
assert(_is_initialized);
// Allocate space for effects which are placed in this array during the 'load_effect' call
const size_t offset = _effects.size();
_effects.resize(offset + effect_files.size());
_reload_remaining_effects = effect_files.size();
// Now that we have a list of files, load them in parallel
// Split workload into batches instead of launching a thread for every file to avoid launch overhead and stutters due to too many threads being in flight
const size_t num_splits = std::min<size_t>(effect_files.size(), std::max<size_t>(std::thread::hardware_concurrency(), 2u) - 1);
// Keep track of the spawned threads, so the runtime cannot be destroyed while they are still running
for (size_t n = 0; n < num_splits; ++n)
// Create copy of preset instead of reference, so it stays valid even if 'ini_file::load_cache' is called while effects are still being loaded
_worker_threads.emplace_back([this, effect_files, offset, num_splits, n, preset]() {
// Abort loading when initialization state changes (indicating that 'on_reset' was called in the meantime)
for (size_t i = 0; i < effect_files.size() && _is_initialized; ++i)
if (i * num_splits / effect_files.size() == n)
load_effect(effect_files[i], preset, offset + i);
});
}
void reshade::runtime::load_textures()
{
_last_texture_reload_successfull = true;
LOG(INFO) << "Loading image files for textures ...";
for (texture &texture : _textures)
{
if (texture.impl == nullptr || !texture.semantic.empty())
continue; // Ignore textures that are not created yet and those that are handled in the runtime implementation
std::filesystem::path source_path = std::filesystem::u8path(
texture.annotation_as_string("source"));
// Ignore textures that have no image file attached to them (e.g. plain render targets)
if (source_path.empty())
continue;
// Search for image file using the provided search paths unless the path provided is already absolute
if (!find_file(_texture_search_paths, source_path))
{
LOG(ERROR) << "Source " << source_path << " for texture '" << texture.unique_name << "' could not be found in any of the texture search paths!";
_last_texture_reload_successfull = false;
continue;
}
unsigned char *filedata = nullptr;
int width = 0, height = 0, channels = 0;
if (FILE *file; _wfopen_s(&file, source_path.c_str(), L"rb") == 0)
{
// Read texture data into memory in one go since that is faster than reading chunk by chunk
std::vector<uint8_t> mem(static_cast<size_t>(std::filesystem::file_size(source_path)));
fread(mem.data(), 1, mem.size(), file);
fclose(file);
if (stbi_dds_test_memory(mem.data(), static_cast<int>(mem.size())))
filedata = stbi_dds_load_from_memory(mem.data(), static_cast<int>(mem.size()), &width, &height, &channels, STBI_rgb_alpha);
else
filedata = stbi_load_from_memory(mem.data(), static_cast<int>(mem.size()), &width, &height, &channels, STBI_rgb_alpha);
}
if (filedata == nullptr)
{
LOG(ERROR) << "Source " << source_path << " for texture '" << texture.unique_name << "' could not be loaded! Make sure it is of a compatible file format.";
_last_texture_reload_successfull = false;
continue;
}
// Need to potentially resize image data to the texture dimensions
if (texture.width != uint32_t(width) || texture.height != uint32_t(height))
{
LOG(INFO) << "Resizing image data for texture '" << texture.unique_name << "' from " << width << "x" << height << " to " << texture.width << "x" << texture.height << " ...";
std::vector<uint8_t> resized(texture.width * texture.height * 4);
stbir_resize_uint8(filedata, width, height, 0, resized.data(), texture.width, texture.height, 0, 4);
upload_texture(texture, resized.data());
}
else
{
upload_texture(texture, filedata);
}
stbi_image_free(filedata);
texture.loaded = true;
}
_textures_loaded = true;
}
void reshade::runtime::unload_effect(size_t effect_index)
{
assert(effect_index < _effects.size());
#if RESHADE_GUI
_preview_texture = nullptr;
#endif
// Lock here to be safe in case another effect is still loading
const std::lock_guard<std::mutex> lock(_reload_mutex);
// Destroy textures belonging to this effect
_textures.erase(std::remove_if(_textures.begin(), _textures.end(),
[this, effect_index](texture &tex) {
tex.shared.erase(std::remove(tex.shared.begin(), tex.shared.end(), effect_index), tex.shared.end());
if (tex.shared.empty()) {
destroy_texture(tex);
return true;
}
return false;
}), _textures.end());
// Clean up techniques belonging to this effect
_techniques.erase(std::remove_if(_techniques.begin(), _techniques.end(),
[effect_index](const technique &tech) {
return tech.effect_index == effect_index;
}), _techniques.end());
_effects[effect_index].rendering = 0;
// Do not clear effect here, since it is common to be re-used immediately
}
void reshade::runtime::unload_effects()
{
#if RESHADE_GUI
_preview_texture = nullptr;
_effect_filter[0] = '\0'; // And reset filter too, since the list of techniques might have changed
#endif
// Make sure no threads are still accessing effect data
for (std::thread &thread : _worker_threads)
if (thread.joinable())
thread.join();
_worker_threads.clear();
// Destroy all textures
for (texture &tex : _textures)
destroy_texture(tex);
_textures.clear();
_textures_loaded = false;
// Clean up all techniques
_techniques.clear();
// Reset the effect list after all resources have been destroyed
_effects.clear();
}
bool reshade::runtime::reload_effect(size_t effect_index, bool preprocess_required)
{
#if RESHADE_GUI
_show_splash = false; // Hide splash bar when reloading a single effect file
#endif
const std::filesystem::path source_file = _effects[effect_index].source_file;
unload_effect(effect_index);
return load_effect(source_file, ini_file::load_cache(_current_preset_path), effect_index, preprocess_required);
}
void reshade::runtime::reload_effects()
{
// Clear out any previous effects
unload_effects();
#if RESHADE_GUI
_show_splash = true; // Always show splash bar when reloading everything
_reload_count++;
#endif
_last_reload_successfull = true;
load_effects();
}
bool reshade::runtime::load_effect_cache(const std::filesystem::path &source_file, const size_t hash, std::string &source) const
{
if (_no_effect_cache)
return false;
std::filesystem::path path = g_reshade_base_path / _intermediate_cache_path;
path /= std::filesystem::u8path("reshade-" + source_file.stem().u8string() + '-' + std::to_string(_renderer_id) + '-' + std::to_string(hash) + ".i");
const HANDLE file = CreateFileW(path.c_str(), FILE_GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
if (file == INVALID_HANDLE_VALUE)
return false;
DWORD size = GetFileSize(file, nullptr);
source.resize(size);
const BOOL result = ReadFile(file, source.data(), size, &size, nullptr);
CloseHandle(file);
return result != FALSE;
}
bool reshade::runtime::load_effect_cache(const std::filesystem::path &source_file, const std::string &entry_point, const size_t hash, std::vector<char> &cso, std::string &dasm) const
{
if (_no_effect_cache)
return false;
std::filesystem::path path = g_reshade_base_path / _intermediate_cache_path;
path /= std::filesystem::u8path("reshade-" + source_file.stem().u8string() + '-' + entry_point + '-' + std::to_string(_renderer_id) + '-' + std::to_string(hash) + ".cso");
{ const HANDLE file = CreateFileW(path.c_str(), FILE_GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
if (file == INVALID_HANDLE_VALUE)
return false;
DWORD size = GetFileSize(file, nullptr);
cso.resize(size);
const BOOL result = ReadFile(file, cso.data(), size, &size, nullptr);
CloseHandle(file);
if (result == FALSE)
return false;
}
path.replace_extension(L".asm");
{ const HANDLE file = CreateFileW(path.c_str(), FILE_GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
if (file == INVALID_HANDLE_VALUE)
return false;
DWORD size = GetFileSize(file, nullptr);
dasm.resize(size);
const BOOL result = ReadFile(file, dasm.data(), size, &size, nullptr);
CloseHandle(file);
if (result == FALSE)
return false;
}
return true;
}
bool reshade::runtime::save_effect_cache(const std::filesystem::path &source_file, const size_t hash, const std::string &source) const
{
if (_no_effect_cache)
return false;
std::filesystem::path path = g_reshade_base_path / _intermediate_cache_path;
path /= std::filesystem::u8path("reshade-" + source_file.stem().u8string() + '-' + std::to_string(_renderer_id) + '-' + std::to_string(hash) + ".i");
const HANDLE file = CreateFileW(path.c_str(), FILE_GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_NEW, FILE_ATTRIBUTE_ARCHIVE | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
if (file == INVALID_HANDLE_VALUE)
return false;
DWORD size = static_cast<DWORD>(source.size());
const BOOL result = WriteFile(file, source.data(), size, &size, nullptr);
CloseHandle(file);
return result != FALSE;
}
bool reshade::runtime::save_effect_cache(const std::filesystem::path &source_file, const std::string &entry_point, const size_t hash, const std::vector<char> &cso, const std::string &dasm) const
{
if (_no_effect_cache)
return false;
std::filesystem::path path = g_reshade_base_path / _intermediate_cache_path;
path /= std::filesystem::u8path("reshade-" + source_file.stem().u8string() + '-' + entry_point + '-' + std::to_string(_renderer_id) + '-' + std::to_string(hash) + ".cso");
{ const HANDLE file = CreateFileW(path.c_str(), FILE_GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_NEW, FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
if (file == INVALID_HANDLE_VALUE)
return false;
DWORD size = static_cast<DWORD>(cso.size());
const BOOL result = WriteFile(file, cso.data(), size, &size, nullptr);
CloseHandle(file);
if (result == FALSE)
return false;
}
path.replace_extension(L".asm");
{ const HANDLE file = CreateFileW(path.c_str(), FILE_GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_NEW, FILE_ATTRIBUTE_ARCHIVE | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
if (file == INVALID_HANDLE_VALUE)
return false;
DWORD size = static_cast<DWORD>(dasm.size());
const BOOL result = WriteFile(file, dasm.c_str(), size, &size, NULL);
CloseHandle(file);
if (result == FALSE)
return false;
}
return true;
}
void reshade::runtime::clear_effect_cache()
{
// Find all cached effect files and delete them
std::error_code ec;
for (const std::filesystem::directory_entry &entry : std::filesystem::directory_iterator(g_reshade_base_path / _intermediate_cache_path, std::filesystem::directory_options::skip_permission_denied, ec))
{
if (entry.is_directory(ec))
continue;
const std::filesystem::path filename = entry.path().filename();
const std::filesystem::path extension = entry.path().extension();
if (filename.native().compare(0, 8, L"reshade-") != 0 || (extension != L".i" && extension != L".cso" && extension != L".asm"))
continue;
DeleteFileW(entry.path().c_str());
}
}
void reshade::runtime::update_and_render_effects()
{
// Delay first load to the first render call to avoid loading while the application is still initializing
if (_framecount == 0 && !_no_reload_on_init)
reload_effects();
if (_reload_remaining_effects == 0)
{
// Clear the thread list now that they all have finished
for (std::thread &thread : _worker_threads)
if (thread.joinable())
thread.join(); // Threads have exited, but still need to join them prior to destruction
_worker_threads.clear();
// Finished loading effects, so apply preset to figure out which ones need compiling
load_current_preset();
_last_reload_time = std::chrono::high_resolution_clock::now();
_reload_remaining_effects = std::numeric_limits<size_t>::max();
// Reset all effect loading options
_load_option_disable_skipping = false;