forked from crosire/reshade
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runtime.cpp
1671 lines (1433 loc) · 59.9 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 "dll_log.hpp"
#include "version.h"
#include "runtime.hpp"
#include "runtime_config.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 <thread>
#include <cassert>
#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;
extern std::filesystem::path g_reshade_dll_path;
extern std::filesystem::path g_target_executable_path;
static inline auto absolute_path(std::filesystem::path path)
{
std::error_code ec;
// First convert path to an absolute path
path = std::filesystem::absolute(g_reshade_dll_path.parent_path() / path, ec);
// Finally try to canonicalize the path too (this may fail though, so it is optional)
if (auto canonical_path = std::filesystem::canonical(path, ec); !ec)
path = std::move(canonical_path);
return path;
}
static inline bool check_preset_path(std::filesystem::path preset_path)
{
// First make sure the extension matches, before diving into the file system
if (preset_path.extension() != L".ini" && preset_path.extension() != L".txt")
return false;
preset_path = absolute_path(preset_path);
std::error_code ec;
const std::filesystem::file_type file_type = std::filesystem::status(preset_path, ec).type();
if (file_type == std::filesystem::file_type::directory || ec.value() == 0x7b) // 0x7b: ERROR_INVALID_NAME
return false;
if (file_type == std::filesystem::file_type::not_found)
return true; // A non-existent path is valid for a new preset
return reshade::ini_file::load_cache(preset_path).has({}, "Techniques");
}
static bool find_file(const std::vector<std::filesystem::path> &search_paths, std::filesystem::path &path)
{
std::error_code ec;
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
search_path = absolute_path(std::move(search_path)) / path;
if (std::filesystem::exists(search_path, ec)) {
path = std::move(search_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;
for (std::filesystem::path search_path : search_paths)
{
// Ignore the working directory and instead start relative paths at the DLL location
search_path = absolute_path(std::move(search_path));
for (const auto &entry : std::filesystem::directory_iterator(search_path, ec))
for (const auto &ext : extensions)
if (entry.path().extension() == ext)
files.push_back(entry.path());
}
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(),
_effects_key_data(),
_screenshot_key_data(),
_prev_preset_key_data(),
_next_preset_key_data(),
_screenshot_path(g_target_executable_path.parent_path())
{
// Default shortcut PrtScrn
_screenshot_key_data[0] = 0x2C;
_configuration_path = g_reshade_dll_path;
_configuration_path.replace_extension(L".ini");
// First look for an API-named configuration file
if (std::error_code ec; !std::filesystem::exists(_configuration_path, ec))
// On failure check for a "ReShade.ini" in the application directory
_configuration_path = g_target_executable_path.parent_path() / L"ReShade.ini";
if (std::error_code ec; !std::filesystem::exists(_configuration_path, ec))
// If neither exist create a "ReShade.ini" in the ReShade DLL directory
_configuration_path = g_reshade_dll_path.parent_path() / L"ReShade.ini";
_needs_update = check_for_update(_latest_version);
#if RESHADE_GUI
init_ui();
#endif
load_config();
}
reshade::runtime::~runtime()
{
assert(_worker_threads.empty());
assert(!_is_initialized && _techniques.empty());
#if RESHADE_GUI
deinit_ui();
#endif
}
bool reshade::runtime::on_init(input::window_handle window)
{
assert(!_is_initialized);
_input = input::register_window(window);
// 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;
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
LOG(INFO) << "Destroyed runtime environment on runtime " << this << '.';
}
void reshade::runtime::on_present()
{
// Get current time and date
time_t t = std::time(nullptr); tm tm;
localtime_s(&tm, &t);
_date[0] = tm.tm_year + 1900;
_date[1] = tm.tm_mon + 1;
_date[2] = tm.tm_mday;
_date[3] = tm.tm_hour * 3600 + tm.tm_min * 60 + tm.tm_sec;
_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_ui();
if (_should_save_screenshot && _screenshot_save_ui && _show_menu)
save_screenshot(L" ui");
#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))
_effects_enabled = !_effects_enabled;
if (_input->is_key_pressed(_screenshot_key_data))
_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))
load_effects();
if (const bool reversed = _input->is_key_pressed(_prev_preset_key_data);
_input->is_key_pressed(_next_preset_key_data) || reversed)
{
// 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;
// Detect high network traffic
static int cooldown = 0, traffic = 0;
if (cooldown-- > 0)
{
traffic += g_network_traffic > 0;
}
else
{
_has_high_network_activity = traffic > 10;
traffic = 0;
cooldown = 60;
}
// Reset frame statistics
g_network_traffic = 0;
_drawcalls = _vertices = 0;
}
bool reshade::runtime::load_effect(const std::filesystem::path &path, size_t index)
{
effect &effect = _effects[index]; // Safe to access this multi-threaded, since this is the only call working on this effect
effect.source_file = path;
effect.compile_sucess = true;
{ // Load, pre-process and compile the source file
reshadefx::preprocessor pp;
if (path.is_absolute())
pp.add_include_path(path.parent_path());
for (std::filesystem::path include_path : _effect_search_paths)
{
include_path = absolute_path(include_path);
if (!include_path.empty())
pp.add_include_path(include_path);
}
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));
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 auto &definition : preprocessor_definitions)
{
if (definition.empty())
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);
}
if (!pp.append_file(path))
{
effect.compile_sucess = false;
}
unsigned shader_model;
if (_renderer_id == 0x9000) // D3D9
shader_model = 30;
else if (_renderer_id < 0xa100) // D3D10
shader_model = 40;
else if (_renderer_id < 0xb000) // D3D11
shader_model = 41;
else if (_renderer_id < 0xc000) // D3D12
shader_model = 50;
else
shader_model = 60;
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));
else // Vulkan uses SPIR-V input
codegen.reset(reshadefx::create_codegen_spirv(true, !_no_debug_info, _performance_mode, true));
reshadefx::parser parser;
// Compile the pre-processed source code (try the compile even if the preprocessor step failed to get additional error information)
if (!parser.parse(std::move(pp.output()), codegen.get()))
{
LOG(ERROR) << "Failed to compile " << path << ":\n" << pp.errors() << parser.errors();
effect.compile_sucess = false;
}
// Append preprocessor and parser errors to the error list
effect.errors = std::move(pp.errors()) + std::move(parser.errors());
// Keep track of used preprocessor definitions (so they can be displayed in the GUI)
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.push_back({ definition.first, trim(definition.second) });
}
// 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
// Write result to effect module
codegen->write_result(effect.module);
}
// Fill all specialization constants with values from the current preset
if (_performance_mode && !_current_preset_path.empty() && effect.compile_sucess)
{
const ini_file preset(_current_preset_path); // ini_file::load_cache is not thread-safe, so load from file here
const std::string section(path.filename().u8string());
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(section, constant.name, constant.initializer_value.as_int);
break;
case reshadefx::type::t_bool:
case reshadefx::type::t_uint:
preset.get(section, constant.name, constant.initializer_value.as_uint);
break;
case reshadefx::type::t_float:
preset.get(section, 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';
}
}
// Create space for all variables (aligned to 16 bytes)
effect.uniform_data_storage.resize((effect.module.total_uniform_size + 15) & ~15);
for (uniform var : effect.module.uniforms)
{
var.effect_index = index;
// Copy initial data into uniform storage area
reset_uniform_value(var);
const std::string_view special = var.annotation_as_string("source");
if (special.empty()) /* Ignore if annotation is missing */;
else if (special == "frametime")
var.special = special_uniform::frame_time;
else if (special == "framecount")
var.special = special_uniform::frame_count;
else if (special == "random")
var.special = special_uniform::random;
else if (special == "pingpong")
var.special = special_uniform::ping_pong;
else if (special == "date")
var.special = special_uniform::date;
else if (special == "timer")
var.special = special_uniform::timer;
else if (special == "key")
var.special = special_uniform::key;
else if (special == "mousepoint")
var.special = special_uniform::mouse_point;
else if (special == "mousedelta")
var.special = special_uniform::mouse_delta;
else if (special == "mousebutton")
var.special = special_uniform::mouse_button;
else if (special == "freepie")
var.special = special_uniform::freepie;
else if (special == "overlay_open")
var.special = special_uniform::overlay_open;
else if (special == "bufready_depth")
var.special = special_uniform::bufready_depth;
effect.uniforms.push_back(std::move(var));
}
std::vector<texture> new_textures;
new_textures.reserve(effect.module.textures.size());
std::vector<technique> new_techniques;
new_techniques.reserve(effect.module.techniques.size());
for (texture texture : effect.module.textures)
{
texture.effect_index = index;
{ const std::lock_guard<std::mutex> lock(_reload_mutex); // Protect access to global texture list
// 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.empty() != (existing_texture->impl_reference == texture_reference::none))
{
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 usage; rename the variable to fix this error\n";
effect.compile_sucess = false;
break;
}
else 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; textures are shared across all effects, so either rename the variable or adjust the dimensions so they match\n";
}
existing_texture->shared = true;
continue;
}
}
if (texture.annotation_as_int("pooled"))
{
const std::lock_guard<std::mutex> lock(_reload_mutex);
// Try to find another pooled texture to share with
if (const auto existing_texture = std::find_if(_textures.begin(), _textures.end(),
[&texture](const auto &item) { return item.annotation_as_int("pooled") && 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 render targets with the pooled one
for (auto &technique_info : effect.module.techniques)
for (auto &pass_info : technique_info.passes)
for (auto &target_name : pass_info.render_target_names)
if (target_name == texture.unique_name)
target_name = existing_texture->unique_name;
existing_texture->shared = true;
continue;
}
}
if (texture.semantic == "COLOR")
texture.impl_reference = texture_reference::back_buffer;
else if (texture.semantic == "DEPTH")
texture.impl_reference = texture_reference::depth_buffer;
else if (!texture.semantic.empty())
effect.errors += "warning: " + texture.unique_name + ": unknown semantic '" + texture.semantic + "'\n";
new_textures.push_back(std::move(texture));
}
for (technique technique : effect.module.techniques)
{
technique.effect_index = index;
technique.hidden = technique.annotation_as_int("hidden") != 0;
technique.timeout = technique.annotation_as_int("timeout");
technique.timeleft = technique.timeout;
if (technique.annotation_as_int("enabled"))
enable_technique(technique);
new_techniques.push_back(std::move(technique));
}
if (effect.compile_sucess)
if (effect.errors.empty())
LOG(INFO) << "Successfully loaded " << path << '.';
else
LOG(WARN) << "Successfully loaded " << path << " with warnings:\n" << effect.errors;
{ const std::lock_guard<std::mutex> lock(_reload_mutex);
std::move(new_textures.begin(), new_textures.end(), std::back_inserter(_textures));
std::move(new_techniques.begin(), new_techniques.end(), std::back_inserter(_techniques));
_last_reload_successful &= effect.compile_sucess;
_reload_remaining_effects--;
}
return effect.compile_sucess;
}
void reshade::runtime::load_effects()
{
// Clear out any previous effects
unload_effects();
#if RESHADE_GUI
_show_splash = true; // Always show splash bar when reloading everything
#endif
_last_reload_successful = true;
// Reload preprocessor definitions from current preset before compiling
if (!_current_preset_path.empty())
{
_preset_preprocessor_definitions.clear();
const 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" });
_reload_total_effects = effect_files.size();
_reload_remaining_effects = _reload_total_effects;
if (_reload_total_effects == 0)
return; // No effect files found, so nothing more to do
// Allocate space for effects which are placed in this array during the 'load_effect' call
_effects.resize(_reload_total_effects);
// 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)
_worker_threads.emplace_back([this, effect_files, num_splits, n]() {
// 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], i);
});
}
void reshade::runtime::load_textures()
{
LOG(INFO) << "Loading image files for textures ...";
for (const texture &texture : _textures)
{
if (texture.impl == nullptr || texture.impl_reference != texture_reference::none)
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.";
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.";
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);
}
_textures_loaded = true;
}
void reshade::runtime::unload_effect(size_t index)
{
#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, index](texture &tex) {
if (tex.effect_index == index && !tex.shared) {
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(),
[index](const technique &tech) {
return tech.effect_index == index;
}), _techniques.end());
// Do not clear source file, so that an 'unload_effect' immediately followed by a 'load_effect' which accesses that works
effect &effect = _effects[index];;
effect.rendering = false;
effect.compile_sucess = false;
effect.errors.clear();
effect.preamble.clear();
effect.included_files.clear();
effect.definitions.clear();
effect.assembly.clear();
effect.uniforms.clear();
effect.uniform_data_storage.clear();
}
void reshade::runtime::unload_effects()
{
#if RESHADE_GUI
_selected_effect = std::numeric_limits<size_t>::max();
_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)
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();
}
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)
load_effects();
if (_reload_remaining_effects == 0)
{
// Clear the thread list now that they all have finished
for (std::thread &thread : _worker_threads)
thread.join(); // Threads have exited, but still need to join them prior destruction
_worker_threads.clear();
// Finished loading effects, so apply preset to figure out which ones need compiling
load_current_preset();
#if RESHADE_GUI
// Re-open last file in code editor after a reload
if (_show_code_editor && !_editor_file.empty())
if (const auto it = std::find_if(_effects.begin(), _effects.end(),
[this](const effect &fx) { return fx.source_file == _editor_file; }); it != _effects.end())
open_file_in_code_editor(it - _effects.begin(), _editor_file);
#endif
_last_reload_time = std::chrono::high_resolution_clock::now();
_reload_total_effects = 0;
_reload_remaining_effects = std::numeric_limits<size_t>::max();
}
else if (_reload_remaining_effects != std::numeric_limits<size_t>::max())
{
return; // Cannot render while effects are still being loaded
}
else
{
if (!_reload_compile_queue.empty())
{
// Pop an effect from the queue
const size_t effect_index = _reload_compile_queue.back();
_reload_compile_queue.pop_back();
effect &effect = _effects[effect_index];
// Create textures now, since they are referenced when building samplers in the 'init_effect' call below
bool success = true;
for (texture &texture : _textures)
{
if (texture.impl == nullptr && (texture.effect_index == effect_index || texture.shared))
{
if (!init_texture(texture))
{
success = false;
effect.errors += "Failed to create texture " + texture.unique_name;
break;
}
}
}
// Compile the effect with the back-end implementation
if (success && !init_effect(effect_index))
{
// De-duplicate error lines (D3DCompiler sometimes repeats the same error multiple times)
for (size_t cur_line_offset = 0, next_line_offset, end_offset;
(next_line_offset = effect.errors.find('\n', cur_line_offset)) != std::string::npos && (end_offset = effect.errors.find('\n', next_line_offset + 1)) != std::string::npos; cur_line_offset = next_line_offset + 1)
{
const std::string_view cur_line(effect.errors.c_str() + cur_line_offset, next_line_offset - cur_line_offset);
const std::string_view next_line(effect.errors.c_str() + next_line_offset + 1, end_offset - next_line_offset - 1);
if (cur_line == next_line)
{
effect.errors.erase(next_line_offset, end_offset - next_line_offset);
next_line_offset = cur_line_offset - 1;
}
}
if (effect.errors.empty())
LOG(ERROR) << "Failed initializing " << effect.source_file << '.';
else
LOG(ERROR) << "Failed initializing " << effect.source_file << ":\n" << effect.errors;
success = false;
}
if (!success) // Something went wrong, do clean up
{
// Destroy all textures belonging to this effect
for (texture &tex : _textures)
if (tex.effect_index == effect_index && !tex.shared)
destroy_texture(tex);
// Disable all techniques belonging to this effect
for (technique &tech : _techniques)
if (tech.effect_index == effect_index)
disable_technique(tech);
effect.compile_sucess = false;
_last_reload_successful = false;
}
// An effect has changed, need to reload textures
_textures_loaded = false;
}
else if (!_textures_loaded)
{
// Now that all effects were compiled, load all textures
load_textures();
}
}
#ifdef NDEBUG
// Lock input so it cannot be modified by other threads while we are reading it here
// TODO: This does not catch input happening between now and 'on_present'
const auto input_lock = _input->lock();
#endif
if (_should_save_screenshot && (_screenshot_save_before || !_effects_enabled))
save_screenshot(_effects_enabled ? L" original" : std::wstring(), !_effects_enabled);
// Nothing to do here if effects are disabled globally
if (!_effects_enabled)
return;
// Update special uniform variables
for (effect &effect : _effects)
{
if (!effect.rendering)
continue;
for (uniform &variable : effect.uniforms)
{
if (!_ignore_shortcuts && variable.toggle_key_data[0] != 0 && _input->is_key_pressed(variable.toggle_key_data))
{
assert(variable.supports_toggle_key());
// Change to next value if the associated shortcut key was pressed
switch (variable.type.base)
{
case reshadefx::type::t_bool:
{
bool data;
get_uniform_value(variable, &data, 1);
set_uniform_value(variable, !data);
break;
}
case reshadefx::type::t_int:
case reshadefx::type::t_uint:
{
int data[4];
get_uniform_value(variable, data, 4);
const std::string_view ui_items = variable.annotation_as_string("ui_items");
int num_items = 0;
for (size_t offset = 0, next; (next = ui_items.find('\0', offset)) != std::string::npos; offset = next + 1)
num_items++;
data[0] = (data[0] + 1 >= num_items) ? 0 : data[0] + 1;
set_uniform_value(variable, data, 4);
break;
}
}
save_current_preset();
}
switch (variable.special)
{
case special_uniform::frame_time:
{
set_uniform_value(variable, _last_frame_duration.count() * 1e-6f, 0.0f, 0.0f, 0.0f);
break;
}
case special_uniform::frame_count:
{
if (variable.type.is_boolean())
set_uniform_value(variable, (_framecount % 2) == 0);
else
set_uniform_value(variable, static_cast<unsigned int>(_framecount % UINT_MAX));
break;
}
case special_uniform::random:
{
const int min = variable.annotation_as_int("min");
const int max = variable.annotation_as_int("max");
set_uniform_value(variable, min + (std::rand() % (max - min + 1)));
break;
}
case special_uniform::ping_pong:
{
const float min = variable.annotation_as_float("min");
const float max = variable.annotation_as_float("max");
const float step_min = variable.annotation_as_float("step", 0);
const float step_max = variable.annotation_as_float("step", 1);
float increment = step_max == 0 ? step_min : (step_min + std::fmodf(static_cast<float>(std::rand()), step_max - step_min + 1));
const float smoothing = variable.annotation_as_float("smoothing");
float value[2] = { 0, 0 };
get_uniform_value(variable, value, 2);
if (value[1] >= 0)
{
increment = std::max(increment - std::max(0.0f, smoothing - (max - value[0])), 0.05f);
increment *= _last_frame_duration.count() * 1e-9f;
if ((value[0] += increment) >= max)
value[0] = max, value[1] = -1;
}
else
{
increment = std::max(increment - std::max(0.0f, smoothing - (value[0] - min)), 0.05f);
increment *= _last_frame_duration.count() * 1e-9f;
if ((value[0] -= increment) <= min)
value[0] = min, value[1] = +1;
}
set_uniform_value(variable, value, 2);
break;
}
case special_uniform::date:
{
set_uniform_value(variable, _date, 4);
break;
}
case special_uniform::timer:
{
set_uniform_value(variable, static_cast<unsigned int>(
std::chrono::duration_cast<std::chrono::milliseconds>(_last_present_time - _start_time).count()));
break;
}
case special_uniform::key:
{
if (const int keycode = variable.annotation_as_int("keycode");
keycode > 7 && keycode < 256)
{
if (const std::string_view mode = variable.annotation_as_string("mode");
mode == "toggle" || variable.annotation_as_int("toggle"))
{
bool current_value = false;
get_uniform_value(variable, ¤t_value, 1);
if (_input->is_key_pressed(keycode))
set_uniform_value(variable, !current_value);
}
else if (mode == "press")
set_uniform_value(variable, _input->is_key_pressed(keycode));
else
set_uniform_value(variable, _input->is_key_down(keycode));
}
break;
}
case special_uniform::mouse_point:
set_uniform_value(variable, _input->mouse_position_x(), _input->mouse_position_y());
break;
case special_uniform::mouse_delta:
set_uniform_value(variable, _input->mouse_movement_delta_x(), _input->mouse_movement_delta_y());
break;
case special_uniform::mouse_button:
{
if (const int keycode = variable.annotation_as_int("keycode");
keycode >= 0 && keycode < 5)
{
if (const std::string_view mode = variable.annotation_as_string("mode");
mode == "toggle" || variable.annotation_as_int("toggle"))
{
bool current_value = false;
get_uniform_value(variable, ¤t_value, 1);
if (_input->is_mouse_button_pressed(keycode))
set_uniform_value(variable, !current_value);
}
else if (mode == "press")
set_uniform_value(variable, _input->is_mouse_button_pressed(keycode));
else
set_uniform_value(variable, _input->is_mouse_button_down(keycode));
}
break;
}
case special_uniform::freepie:
if (freepie_io_data data;
freepie_io_read(variable.annotation_as_int("index"), &data))