forked from praydog/REFramework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathREFramework.cpp
1511 lines (1173 loc) · 48.1 KB
/
REFramework.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
#include <chrono>
#include <filesystem>
#include <windows.h>
#include <spdlog/sinks/basic_file_sink.h>
// minhook, used for AllocateBuffer
extern "C" {
#include <../buffer.h>
};
#include <imgui.h>
#include <ImGuizmo.h>
#include "re2-imgui/font_robotomedium.hpp"
#include "re2-imgui/imgui_impl_dx11.h"
#include "re2-imgui/imgui_impl_dx12.h"
#include "re2-imgui/imgui_impl_win32.h"
#include "utility/Module.hpp"
#include "utility/Patch.hpp"
#include "utility/Scan.hpp"
#include "utility/Thread.hpp"
#include "Mods.hpp"
#include "mods/PluginLoader.hpp"
#include "sdk/REGlobals.hpp"
#include "sdk/SDK.hpp"
#include "ExceptionHandler.hpp"
#include "LicenseStrings.hpp"
#include "mods/REFrameworkConfig.hpp"
#include "REFramework.hpp"
namespace fs = std::filesystem;
using namespace std::literals;
std::unique_ptr<REFramework> g_framework{};
void REFramework::hook_monitor() {
std::scoped_lock _{ m_hook_monitor_mutex };
if (g_framework == nullptr) {
return;
}
const auto now = std::chrono::steady_clock::now();
auto& d3d11 = get_d3d11_hook();
auto& d3d12 = get_d3d12_hook();
const auto renderer_type = get_renderer_type();
if (d3d11 == nullptr || d3d12 == nullptr
|| (renderer_type == REFramework::RendererType::D3D11 && d3d11 != nullptr && !d3d11->is_inside_present())
|| (renderer_type == REFramework::RendererType::D3D12 && d3d12 != nullptr && !d3d12->is_inside_present()))
{
// check if present time is more than 5 seconds ago
if (now - m_last_present_time > std::chrono::seconds(5)) {
if (m_has_last_chance) {
// the purpose of this is to make sure that the game is not frozen
// e.g. if we are debugging the game, so we don't rehook anything on accident
m_has_last_chance = false;
m_last_chance_time = now;
spdlog::info("Last chance encountered for hooking");
}
if (!m_has_last_chance && now - m_last_chance_time > std::chrono::seconds(1)) {
spdlog::info("Sending rehook request for D3D");
// hook_d3d12 always gets called first.
if (m_is_d3d11) {
hook_d3d11();
} else {
hook_d3d12();
}
// so we don't immediately go and hook it again
// add some additional time to it to give it some leeway
m_last_present_time = std::chrono::steady_clock::now() + std::chrono::seconds(5);
m_last_message_time = std::chrono::steady_clock::now() + std::chrono::seconds(5);
m_last_chance_time = std::chrono::steady_clock::now() + std::chrono::seconds(1);
m_has_last_chance = true;
}
} else {
m_last_chance_time = std::chrono::steady_clock::now();
m_has_last_chance = true;
}
if (m_initialized && m_wnd != 0 && now - m_last_message_time > std::chrono::seconds(5)) {
if (m_windows_message_hook != nullptr && m_windows_message_hook->is_hook_intact()) {
spdlog::info("Windows message hook is still intact, ignoring...");
m_last_message_time = now;
m_last_sendmessage_time = now;
m_sent_message = false;
return;
}
// send dummy message to window to check if our hook is still intact
if (!m_sent_message) {
spdlog::info("Sending initial message hook test");
auto proc = (WNDPROC)GetWindowLongPtr(m_wnd, GWLP_WNDPROC);
if (proc != nullptr) {
const auto ret = CallWindowProc(proc, m_wnd, WM_NULL, 0, 0);
spdlog::info("Hook test message sent");
}
m_last_sendmessage_time = std::chrono::steady_clock::now();
m_sent_message = true;
} else if (now - m_last_sendmessage_time > std::chrono::seconds(1)) {
spdlog::info("Sending reinitialization request for message hook");
// if we don't get a message for 5 seconds, assume the hook is broken
//m_initialized = false; // causes the hook to be re-initialized next frame
m_message_hook_requested = true;
m_last_message_time = std::chrono::steady_clock::now() + std::chrono::seconds(5);
m_last_present_time = std::chrono::steady_clock::now() + std::chrono::seconds(5);
m_sent_message = false;
}
} else {
m_sent_message = false;
}
}
}
REFramework::REFramework(HMODULE reframework_module)
: m_reframework_module{reframework_module}
, m_game_module{GetModuleHandle(0)}
, m_logger{spdlog::basic_logger_mt("REFramework", "re2_framework_log.txt", true)} {
spdlog::set_default_logger(m_logger);
spdlog::flush_on(spdlog::level::info);
spdlog::info("REFramework entry");
const auto module_size = *utility::get_module_size(m_game_module);
spdlog::info("Game Module Addr: {:x}", (uintptr_t)m_game_module);
spdlog::info("Game Module Size: {:x}", module_size);
// preallocate some memory for minhook to mitigate failures (temporarily at least... this should in theory fail when too many hooks are made)
// but, 64 slots should be enough for now.
// so... TODO: modify minhook to use absolute jumps when failing to allocate memory nearby
const auto halfway_module = (uintptr_t)m_game_module + (module_size / 2);
const auto pre_allocated_buffer = (uintptr_t)AllocateBuffer((LPVOID)halfway_module); // minhook function
spdlog::info("Preallocated buffer: {:x}", pre_allocated_buffer);
#ifdef DEBUG
spdlog::set_level(spdlog::level::debug);
#endif
// Create the typedef for RtlGetVersion
typedef LONG (*RtlGetVersionFunc)(PRTL_OSVERSIONINFOW);
const auto ntdll = GetModuleHandle("ntdll.dll");
if (ntdll != nullptr) {
// Manually get RtlGetVersion
auto rtl_get_version = (RtlGetVersionFunc)GetProcAddress(ntdll, "RtlGetVersion");
if (rtl_get_version != nullptr) {
spdlog::info("Getting OS version information...");
// Create an initial log that prints out the user's Windows OS version information
// With the major and minor version numbers
// Using RtlGetVersion()
OSVERSIONINFOW os_version_info{};
ZeroMemory(&os_version_info, sizeof(OSVERSIONINFOW));
os_version_info.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
os_version_info.dwMajorVersion = 0;
os_version_info.dwMinorVersion = 0;
os_version_info.dwBuildNumber = 0;
os_version_info.dwPlatformId = 0;
if (rtl_get_version(&os_version_info) != 0) {
spdlog::info("RtlGetVersion() failed");
} else {
// Log the Windows version information
spdlog::info("OS Version Information");
spdlog::info("\tMajor Version: {}", os_version_info.dwMajorVersion);
spdlog::info("\tMinor Version: {}", os_version_info.dwMinorVersion);
spdlog::info("\tBuild Number: {}", os_version_info.dwBuildNumber);
spdlog::info("\tPlatform Id: {}", os_version_info.dwPlatformId);
spdlog::info("Disclaimer: REFramework does not send this information to the developers or any other third party.");
spdlog::info("This information is only used to help with the development of REFramework.");
}
} else {
spdlog::info("RtlGetVersion() not found");
}
} else {
spdlog::info("ntdll.dll not found");
}
// Fixes a crash on some machines when starting the game
#if defined(RE8) || defined(MHRISE)
auto now = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point next_log = now;
// wait for the game to load (WTF MHRISE??)
// once this is done, we can assume the process is unpacked.
while (LoadLibraryA("d3d12.dll") == nullptr) {
if (now >= next_log) {
spdlog::info("[REFramework] Waiting for D3D12...");
next_log = now + 1s;
}
}
LoadLibraryA("openvr_api.dll");
LoadLibraryA("openxr_loader.dll");
LoadLibraryA("dxgi.dll");
LoadLibraryA("d3d11.dll");
utility::spoof_module_paths_in_exe_dir();
#ifdef RE8
// auto startup_patch_addr = Address{m_game_module}.get(0x3E69E50);
auto startup_patch_addr = utility::scan(m_game_module, "40 53 57 48 83 ec 28 48 83 b9 ? ? ? ? 00");
while (!startup_patch_addr) {
startup_patch_addr = utility::scan(m_game_module, "40 53 57 48 83 ec 28 48 83 b9 ? ? ? ? 00");
}
if (startup_patch_addr) {
static auto permanent_patch = Patch::create(*startup_patch_addr, {0xC3});
} else {
spdlog::info("Couldn't find RE8 crash fix patch location!");
}
#endif
#endif
// Hooking D3D12 initially because we need to retrieve the command queue before the first frame then switch to D3D11 if it failed later
// on
// addendum: now we don't need to do that, we just grab the command queue offset from the swapchain we create
/*if (!hook_d3d12()) {
spdlog::error("Failed to hook D3D12 for initial test.");
}*/
std::scoped_lock _{m_hook_monitor_mutex};
m_last_present_time = std::chrono::steady_clock::now();
m_last_message_time = std::chrono::steady_clock::now();
m_d3d_monitor_thread = std::make_unique<std::thread>([this]() {
// Load the plugins early right after executable unpacking
PluginLoader::get()->early_init();
while (true) {
this->hook_monitor();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
});
}
bool REFramework::hook_d3d11() {
//if (m_d3d11_hook == nullptr) {
m_d3d11_hook.reset();
m_d3d11_hook = std::make_unique<D3D11Hook>();
m_d3d11_hook->on_present([this](D3D11Hook& hook) { on_frame_d3d11(); });
m_d3d11_hook->on_post_present([this](D3D11Hook& hook) { on_post_present_d3d11(); });
m_d3d11_hook->on_resize_buffers([this](D3D11Hook& hook) { on_reset(); });
//}
// Making sure D3D12 is not hooked
if (!m_is_d3d12) {
if (m_d3d11_hook->hook()) {
spdlog::info("Hooked DirectX 11");
m_valid = true;
m_is_d3d11 = true;
return true;
}
// We make sure to no unhook any unwanted hooks if D3D11 didn't get hooked properly
if (m_d3d11_hook->unhook()) {
spdlog::info("D3D11 unhooked!");
} else {
spdlog::info("Cannot unhook D3D11, this might crash.");
}
m_valid = false;
m_is_d3d11 = false;
return false;
}
return false;
}
bool REFramework::hook_d3d12() {
// windows 7?
if (LoadLibraryA("d3d12.dll") == nullptr) {
spdlog::info("d3d12.dll not found, user is probably running Windows 7.");
spdlog::info("Falling back to hooking D3D11.");
m_is_d3d12 = false;
return hook_d3d11();
}
//if (m_d3d12_hook == nullptr) {
m_d3d12_hook.reset();
m_d3d12_hook = std::make_unique<D3D12Hook>();
m_d3d12_hook->on_present([this](D3D12Hook& hook) { on_frame_d3d12(); });
m_d3d12_hook->on_post_present([this](D3D12Hook& hook) { on_post_present_d3d12(); });
m_d3d12_hook->on_resize_buffers([this](D3D12Hook& hook) { on_reset(); });
m_d3d12_hook->on_resize_target([this](D3D12Hook& hook) { on_reset(); });
//}
//m_d3d12_hook->on_create_swap_chain([this](D3D12Hook& hook) { m_d3d12.command_queue = m_d3d12_hook->get_command_queue(); });
// Making sure D3D11 is not hooked
if (!m_is_d3d11) {
if (m_d3d12_hook->hook()) {
spdlog::info("Hooked DirectX 12");
m_valid = true;
m_is_d3d12 = true;
return true;
}
// We make sure to no unhook any unwanted hooks if D3D12 didn't get hooked properly
if (m_d3d12_hook->unhook()) {
spdlog::info("D3D12 Unhooked!");
} else {
spdlog::info("Cannot unhook D3D12, this might crash.");
}
m_valid = false;
m_is_d3d12 = false;
// Try to hook d3d11 instead
return hook_d3d11();
}
return false;
}
REFramework::~REFramework() {
spdlog::info("REFramework shutting down...");
std::scoped_lock _{ m_hook_monitor_mutex };
if (m_is_d3d11) {
ImGui_ImplDX11_Shutdown();
}
if (m_is_d3d12) {
ImGui_ImplDX12_Shutdown();
}
ImGui_ImplWin32_Shutdown();
if (m_initialized) {
ImGui::DestroyContext();
}
}
void REFramework::run_imgui_frame() {
std::scoped_lock _{ m_imgui_mtx };
m_has_frame = false;
if (!m_initialized) {
return;
}
const bool is_init_ok = m_error.empty() && m_game_data_initialized;
consume_input();
update_fonts();
ImGui_ImplWin32_NewFrame();
if (is_init_ok) {
// Run mod frame callbacks.
m_mods->on_pre_imgui_frame();
}
ImGui::NewFrame();
call_on_frame();
draw_ui();
m_last_draw_ui = m_draw_ui;
IMGUIZMO_NAMESPACE::BeginFrame();
ImGui::EndFrame();
ImGui::Render();
m_has_frame = true;
}
// D3D11 Draw funciton
void REFramework::on_frame_d3d11() {
std::scoped_lock _{ m_imgui_mtx };
spdlog::debug("on_frame (D3D11)");
m_renderer_type = RendererType::D3D11;
if (!m_initialized) {
if (!initialize()) {
spdlog::error("Failed to initialize REFramework on DirectX 11");
return;
}
spdlog::info("REFramework initialized");
m_initialized = true;
return;
}
if (m_message_hook_requested) {
initialize_windows_message_hook();
}
const bool is_init_ok = m_error.empty() && m_game_data_initialized;
if (is_init_ok) {
// Write default config once if it doesn't exist.
if (!std::exchange(m_created_default_cfg, true)) {
if (!fs::exists({utility::widen("re2_fw_config.txt")})) {
save_config();
}
}
}
if (!m_has_frame) {
if (!is_init_ok) {
update_fonts();
invalidate_device_objects();
ImGui_ImplDX11_NewFrame();
// hooks don't run until after initialization, so we just render the imgui window while initalizing.
run_imgui_frame();
} else {
return;
}
} else {
invalidate_device_objects();
ImGui_ImplDX11_NewFrame();
}
if (is_init_ok) {
m_mods->on_present();
}
ComPtr<ID3D11DeviceContext> context{};
float clear_color[]{0.0f, 0.0f, 0.0f, 0.0f};
m_d3d11_hook->get_device()->GetImmediateContext(&context);
context->ClearRenderTargetView(m_d3d11.blank_rt_rtv.Get(), clear_color);
context->ClearRenderTargetView(m_d3d11.rt_rtv.Get(), clear_color);
context->OMSetRenderTargets(1, m_d3d11.rt_rtv.GetAddressOf(), NULL);
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
// Set the back buffer to be the render target.
context->OMSetRenderTargets(1, m_d3d11.bb_rtv.GetAddressOf(), nullptr);
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
if (is_init_ok) {
m_mods->on_post_frame();
}
}
void REFramework::on_post_present_d3d11() {
if (!m_error.empty() || !m_initialized || !m_game_data_initialized) {
if (m_last_present_time <= std::chrono::steady_clock::now()){
m_last_present_time = std::chrono::steady_clock::now();
}
return;
}
for (auto& mod : m_mods->get_mods()) {
mod->on_post_present();
}
if (m_last_present_time <= std::chrono::steady_clock::now()){
m_last_present_time = std::chrono::steady_clock::now();
}
}
// D3D12 Draw funciton
void REFramework::on_frame_d3d12() {
std::scoped_lock _{ m_imgui_mtx };
m_renderer_type = RendererType::D3D12;
auto command_queue = m_d3d12_hook->get_command_queue();
//spdlog::debug("on_frame (D3D12)");
if (!m_initialized) {
if (!initialize()) {
spdlog::error("Failed to initialize REFramework on DirectX 12");
return;
}
spdlog::info("REFramework initialized");
m_initialized = true;
return;
}
if (command_queue == nullptr) {
spdlog::error("Null Command Queue");
return;
}
if (m_message_hook_requested) {
initialize_windows_message_hook();
}
const bool is_init_ok = m_error.empty() && m_game_data_initialized;
if (is_init_ok) {
// Write default config once if it doesn't exist.
if (!std::exchange(m_created_default_cfg, true)) {
if (!fs::exists({utility::widen("re2_fw_config.txt")})) {
save_config();
}
}
}
if (!m_has_frame) {
if (!is_init_ok) {
update_fonts();
invalidate_device_objects();
ImGui_ImplDX12_NewFrame();
// hooks don't run until after initialization, so we just render the imgui window while initalizing.
run_imgui_frame();
} else {
return;
}
} else {
invalidate_device_objects();
ImGui_ImplDX12_NewFrame();
}
if (is_init_ok) {
m_mods->on_present();
}
m_d3d12.cmd_allocator->Reset();
m_d3d12.cmd_list->Reset(m_d3d12.cmd_allocator.Get(), nullptr);
// Draw to our render target.
D3D12_RESOURCE_BARRIER barrier{};
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
barrier.Transition.pResource = m_d3d12.get_rt(D3D12::RTV::IMGUI).Get();
barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
m_d3d12.cmd_list->ResourceBarrier(1, &barrier);
float clear_color[]{0.0f, 0.0f, 0.0f, 0.0f};
auto device = m_d3d12_hook->get_device();
D3D12_CPU_DESCRIPTOR_HANDLE rts[1]{};
m_d3d12.cmd_list->ClearRenderTargetView(m_d3d12.get_cpu_rtv(device, D3D12::RTV::IMGUI), clear_color, 0, nullptr);
rts[0] = m_d3d12.get_cpu_rtv(device, D3D12::RTV::IMGUI);
m_d3d12.cmd_list->OMSetRenderTargets(1, rts, FALSE, NULL);
m_d3d12.cmd_list->SetDescriptorHeaps(1, m_d3d12.srv_desc_heap.GetAddressOf());
ImGui_ImplDX12_RenderDrawData(ImGui::GetDrawData(), m_d3d12.cmd_list.Get());
barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
m_d3d12.cmd_list->ResourceBarrier(1, &barrier);
// Draw to the back buffer.
auto swapchain = m_d3d12_hook->get_swap_chain();
auto bb_index = swapchain->GetCurrentBackBufferIndex();
barrier.Transition.pResource = m_d3d12.rts[bb_index].Get();
barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
m_d3d12.cmd_list->ResourceBarrier(1, &barrier);
rts[0] = m_d3d12.get_cpu_rtv(device, (D3D12::RTV)bb_index);
m_d3d12.cmd_list->OMSetRenderTargets(1, rts, FALSE, NULL);
m_d3d12.cmd_list->SetDescriptorHeaps(1, m_d3d12.srv_desc_heap.GetAddressOf());
ImGui_ImplDX12_RenderDrawData(ImGui::GetDrawData(), m_d3d12.cmd_list.Get());
barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT;
m_d3d12.cmd_list->ResourceBarrier(1, &barrier);
m_d3d12.cmd_list->Close();
command_queue->ExecuteCommandLists(1, (ID3D12CommandList* const*)m_d3d12.cmd_list.GetAddressOf());
if (is_init_ok) {
m_mods->on_post_frame();
}
}
void REFramework::on_post_present_d3d12() {
if (!m_error.empty() || !m_initialized || !m_game_data_initialized) {
if (m_last_present_time <= std::chrono::steady_clock::now()){
m_last_present_time = std::chrono::steady_clock::now();
}
return;
}
for (auto& mod : m_mods->get_mods()) {
mod->on_post_present();
}
if (m_last_present_time <= std::chrono::steady_clock::now()){
m_last_present_time = std::chrono::steady_clock::now();
}
}
void REFramework::on_reset() {
std::scoped_lock _{ m_imgui_mtx };
spdlog::info("Reset!");
if (m_initialized) {
// fixes text boxes not being able to receive input
imgui::reset_keystates();
}
// Crashes if we don't release it at this point.
if (m_is_d3d11) {
deinit_d3d11();
}
if (m_is_d3d12) {
deinit_d3d12();
}
if (m_game_data_initialized) {
m_mods->on_device_reset();
}
m_has_frame = false;
m_first_initialize = false;
m_initialized = false;
}
bool REFramework::on_message(HWND wnd, UINT message, WPARAM w_param, LPARAM l_param) {
m_last_message_time = std::chrono::steady_clock::now();
if (!m_initialized) {
return true;
}
bool is_mouse_moving{false};
switch (message) {
case WM_INPUT: {
// RIM_INPUT means the window has focus
if (GET_RAWINPUT_CODE_WPARAM(w_param) == RIM_INPUT) {
uint32_t size = sizeof(RAWINPUT);
RAWINPUT raw{};
// obtain size
GetRawInputData((HRAWINPUT)l_param, RID_INPUT, nullptr, &size, sizeof(RAWINPUTHEADER));
auto result = GetRawInputData((HRAWINPUT)l_param, RID_INPUT, &raw, &size, sizeof(RAWINPUTHEADER));
if (raw.header.dwType == RIM_TYPEMOUSE) {
m_accumulated_mouse_delta[0] += (float)raw.data.mouse.lLastX;
m_accumulated_mouse_delta[1] += (float)raw.data.mouse.lLastY;
// Allowing camera movement when the UI is hovered while not focused
if (raw.data.mouse.lLastX || raw.data.mouse.lLastY) {
is_mouse_moving = true;
}
}
}
} break;
case RE_TOGGLE_CURSOR: {
const auto is_internal_message = l_param != 0;
const auto return_value = is_internal_message || !m_draw_ui;
if (!is_internal_message) {
m_cursor_state = (bool)w_param;
m_cursor_state_changed = true;
}
return return_value;
} break;
default:
break;
}
ImGui_ImplWin32_WndProcHandler(wnd, message, w_param, l_param);
{
// If the user is interacting with the UI we block the message from going to the game.
const auto& io = ImGui::GetIO();
if (m_draw_ui && !m_ui_passthrough) {
// Fix of a bug that makes the input key down register but the key up will never register
// when clicking on the ui while the game is not focused
if (message == WM_INPUT && GET_RAWINPUT_CODE_WPARAM(w_param) == RIM_INPUTSINK)
return false;
if (m_is_ui_focused) {
if (io.WantCaptureMouse || io.WantCaptureKeyboard || io.WantTextInput)
return false;
} else {
if (!is_mouse_moving && (io.WantCaptureMouse || io.WantCaptureKeyboard || io.WantTextInput))
return false;
}
}
}
bool any_false = false;
if (m_game_data_initialized) {
for (auto& mod : m_mods->get_mods()) {
if (!mod->on_message(wnd, message, w_param, l_param)) {
any_false = true;
}
}
}
return !any_false;
}
// this is unfortunate.
void REFramework::on_direct_input_keys(const std::array<uint8_t, 256>& keys) {
const auto menu_key = REFrameworkConfig::get()->get_menu_key()->value();
if (keys[menu_key] && m_last_keys[menu_key] == 0) {
std::lock_guard _{m_input_mutex};
set_draw_ui(!m_draw_ui);
}
m_last_keys = keys;
}
void REFramework::save_config() {
std::scoped_lock _{m_config_mtx};
spdlog::info("Saving config re2_fw_config.txt");
utility::Config cfg{};
for (auto& mod : m_mods->get_mods()) {
mod->on_config_save(cfg);
}
if (!cfg.save("re2_fw_config.txt")) {
spdlog::info("Failed to save config");
return;
}
spdlog::info("Saved config");
}
void REFramework::set_draw_ui(bool state, bool should_save) {
std::scoped_lock _{m_config_mtx};
bool prev_state = m_draw_ui;
m_draw_ui = state;
if (m_game_data_initialized) {
REFrameworkConfig::get()->get_menu_open()->value() = state;
}
if (state != prev_state && should_save && m_game_data_initialized) {
save_config();
}
}
void REFramework::consume_input() {
m_mouse_delta[0] = m_accumulated_mouse_delta[0];
m_mouse_delta[1] = m_accumulated_mouse_delta[1];
m_accumulated_mouse_delta[0] = 0.0f;
m_accumulated_mouse_delta[1] = 0.0f;
}
int REFramework::add_font(const std::filesystem::path& filepath, int size, const std::vector<ImWchar>& ranges) {
// Look for a font already matching this description.
for (int i = 0; i < m_additional_fonts.size(); ++i) {
const auto& font = m_additional_fonts[i];
if (font.filepath == filepath && font.size == size && font.ranges == ranges) {
return i;
}
}
m_additional_fonts.emplace_back(REFramework::AdditionalFont{filepath, size, ranges, (ImFont*)nullptr});
m_fonts_need_updating = true;
return m_additional_fonts.size() - 1;
}
void REFramework::update_fonts() {
if (!m_fonts_need_updating) {
return;
}
m_fonts_need_updating = false;
auto& fonts = ImGui::GetIO().Fonts;
fonts->Clear();
fonts->AddFontFromMemoryCompressedTTF(RobotoMedium_compressed_data, RobotoMedium_compressed_size, (float)m_font_size);
for (auto& font : m_additional_fonts) {
const ImWchar* ranges = nullptr;
if (!font.ranges.empty()) {
ranges = font.ranges.data();
}
if (fs::exists(font.filepath)) {
font.font = fonts->AddFontFromFileTTF(font.filepath.string().c_str(), (float)font.size, nullptr, ranges);
} else {
font.font = fonts->AddFontFromMemoryCompressedTTF(RobotoMedium_compressed_data, RobotoMedium_compressed_size, (float)font.size, nullptr, ranges);
}
}
fonts->Build();
m_wants_device_object_cleanup = true;
}
void REFramework::invalidate_device_objects() {
if (!m_wants_device_object_cleanup) {
return;
}
if (m_renderer_type == RendererType::D3D11) {
ImGui_ImplDX11_InvalidateDeviceObjects();
} else if (m_renderer_type == RendererType::D3D12) {
ImGui_ImplDX12_InvalidateDeviceObjects();
}
m_wants_device_object_cleanup = false;
}
void REFramework::draw_ui() {
std::lock_guard _{m_input_mutex};
if (!m_draw_ui) {
m_is_ui_focused = false;
if (m_last_draw_ui) {
m_windows_message_hook->window_toggle_cursor(m_cursor_state);
}
m_dinput_hook->acknowledge_input();
// ImGui::GetIO().MouseDrawCursor = false;
return;
}
// UI Specific code:
m_is_ui_focused = ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow);
if (m_ui_option_transparent) {
auto& style = ImGui::GetStyle();
if (m_is_ui_focused) {
style.Alpha = 1.0f;
} else {
if (ImGui::IsWindowHovered(ImGuiFocusedFlags_AnyWindow)) {
style.Alpha = 0.9f;
} else {
style.Alpha = 0.8f;
}
}
} else {
auto& style = ImGui::GetStyle();
style.Alpha = 1.0f;
}
auto& io = ImGui::GetIO();
if (io.WantCaptureKeyboard) {
m_dinput_hook->ignore_input();
} else {
m_dinput_hook->acknowledge_input();
}
// ImGui::GetIO().MouseDrawCursor = true;
if (!m_last_draw_ui || m_cursor_state_changed) {
m_cursor_state_changed = false;
m_windows_message_hook->window_toggle_cursor(true);
}
ImGui::SetNextWindowPos(ImVec2(50, 50), ImGuiCond_::ImGuiCond_Once);
ImGui::SetNextWindowSize(ImVec2(300, 500), ImGuiCond_::ImGuiCond_Once);
ImGui::Begin("REFramework", &m_draw_ui);
ImGui::Text("Default Menu Key: Insert");
ImGui::Checkbox("Transparency", &m_ui_option_transparent);
ImGui::SameLine();
ImGui::Text("(?)");
if (ImGui::IsItemHovered())
ImGui::SetTooltip("Makes the UI transparent when not focused.");
ImGui::Checkbox("Input Passthrough", &m_ui_passthrough);
ImGui::SameLine();
ImGui::Text("(?)");
if (ImGui::IsItemHovered())
ImGui::SetTooltip("Allows mouse and keyboard inputs to register to the game while the UI is focused.");
// Mods:
draw_about();
if (m_error.empty() && m_game_data_initialized) {
m_mods->on_draw_ui();
} else if (!m_game_data_initialized) {
ImGui::TextWrapped("REFramework is currently initializing...");
ImGui::TextWrapped("This menu will close after initialization if you have the remember option enabled.");
} else if (!m_error.empty()) {
ImGui::TextWrapped("REFramework error: %s", m_error.c_str());
}
m_last_window_pos = ImGui::GetWindowPos();
m_last_window_size = ImGui::GetWindowSize();
ImGui::End();
// save the menu state in config
if (m_draw_ui != m_last_draw_ui) {
set_draw_ui(m_draw_ui, true);
}
// if we pressed the X button to close the menu.
if (m_last_draw_ui && !m_draw_ui) {
m_windows_message_hook->window_toggle_cursor(m_cursor_state);
}
}
void REFramework::draw_about() {
if (!ImGui::CollapsingHeader("About")) {
return;
}
ImGui::TreePush("About");
ImGui::Text("Author: praydog");
ImGui::Text("Inspired by the Kanan project.");
ImGui::Text("https://github.com/praydog/REFramework");
ImGui::Text("http://praydog.com");
if (ImGui::CollapsingHeader("Licenses")) {
ImGui::TreePush("Licenses");
struct License {
std::string name;
std::string text;
};
static std::array<License, 13> licenses{
License{ "glm", license::glm },
License{ "imgui", license::imgui },
License{ "minhook", license::minhook },
License{ "spdlog", license::spdlog },
License{ "robotomedium", license::roboto },
License{ "openvr", license::openvr },
License{ "lua", license::lua },
License{ "sol", license::sol },
License{ "json", license::json },
License{ "asmjit", license::asmjit },
License{ "zydis", utility::narrow(license::zydis) },
License{ "openxr", license::openxr },
License{ "imguizmo", license::imguizmo }
};
for (const auto& license : licenses) {
if (ImGui::CollapsingHeader(license.name.c_str())) {
ImGui::TextWrapped(license.text.c_str());
}
}
ImGui::TreePop();
}
ImGui::Separator();
if (m_game_data_initialized && m_error.empty()) {
try {
static auto version_t = sdk::find_type_definition("via.version");
static std::string clean_version{};
static std::string engine_config{};
static auto tdb_version = sdk::RETypeDB::get()->version;
if (version_t != nullptr && clean_version.empty()) {
auto m = version_t->get_method("getPrettyVersionString");
if (m != nullptr) {
auto pretty_string = m->call<::SystemString*>(sdk::get_thread_context(), nullptr);
if (pretty_string != nullptr) {
clean_version = utility::re_string::get_string(pretty_string);
}
}
}
if (version_t != nullptr && engine_config.empty()) {
auto m = version_t->get_method("getConfigName");
if (m != nullptr) {
auto config_name = m->call<::SystemString*>(sdk::get_thread_context(), nullptr);
if (config_name != nullptr) {
engine_config = utility::re_string::get_string(config_name);
}
}
}
ImGui::Text("Engine information");
ImGui::Text(" Config: %s", engine_config.c_str());
ImGui::Text(" Version: %s", clean_version.c_str());