-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptimizerCore.cpp
More file actions
840 lines (720 loc) · 33.8 KB
/
Copy pathOptimizerCore.cpp
File metadata and controls
840 lines (720 loc) · 33.8 KB
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
#include "OptimizerCore.hpp"
#include <iostream>
#include <sstream>
#include <iomanip>
#include <bitset>
#include <algorithm>
namespace Corelock {
// ============================================================================
// Constructor & Destructor
// ============================================================================
GameOptimizer::GameOptimizer(OptimizerConfig config)
: config_(std::move(config)) {
}
GameOptimizer::~GameOptimizer() {
Stop();
}
// ============================================================================
// Lifecycle Management
// ============================================================================
bool GameOptimizer::Start() {
if (isRunning_.load()) {
Log(LogLevel::Warning, "Start() called, but optimizer is already running.");
return false;
}
scanTriggerEvent_.Reset(::CreateEventW(nullptr, FALSE, FALSE, nullptr));
if (!scanTriggerEvent_.IsValid()) {
Log(LogLevel::Warning, "Failed to create Win32 scan trigger event.");
}
isRunning_.store(true);
workerThread_ = std::jthread([this](std::stop_token token) {
WorkerThread(token);
});
Log(LogLevel::Info, "Optimizer background monitor started successfully.");
return true;
}
void GameOptimizer::Stop() {
if (!isRunning_.load()) {
return;
}
Log(LogLevel::Info, "Stopping optimizer background monitor...");
if (scanTriggerEvent_.IsValid()) {
::SetEvent(scanTriggerEvent_.Get());
}
if (workerThread_.joinable()) {
workerThread_.request_stop();
workerThread_.join();
}
scanTriggerEvent_.Reset();
isRunning_.store(false);
Log(LogLevel::Info, "Optimizer stopped.");
}
void GameOptimizer::TriggerImmediateScan() {
if (scanTriggerEvent_.IsValid()) {
::SetEvent(scanTriggerEvent_.Get());
Log(LogLevel::Info, "Immediate process scan triggered.");
}
}
bool GameOptimizer::IsRunning() const noexcept {
return isRunning_.load();
}
bool GameOptimizer::IsTargetOptimized() const noexcept {
return isOptimized_.load();
}
std::optional<ProcessStateSnapshot> GameOptimizer::GetActiveSnapshot() const {
std::lock_guard<std::mutex> lock(stateMutex_);
return activeSnapshot_;
}
// ============================================================================
// Worker Thread Loop (Asynchronous Zero-CPU Monitoring)
// ============================================================================
void GameOptimizer::WorkerThread(std::stop_token stopToken) {
// Create manual-reset stop event for zero-CPU asynchronous interruptible waits
UniqueHandle stopEvent(::CreateEventW(nullptr, TRUE, FALSE, nullptr));
if (!stopEvent.IsValid()) {
Log(LogLevel::Error, "Failed to create Win32 stop event. Error: " + FormatWin32Error(::GetLastError()));
isRunning_.store(false);
return;
}
// Connect stopToken to stopEvent: instant signal on request_stop()
std::stop_callback stopCallback(stopToken, [&stopEvent]() {
::SetEvent(stopEvent.Get());
});
std::string targetNameNarrow = WideToNarrow(config_.targetProcessName);
Log(LogLevel::Info, "Monitoring process lifecycle for: '" + targetNameNarrow + "'");
while (!stopToken.stop_requested()) {
auto maybePid = FindTargetProcessId(config_.targetProcessName);
if (!maybePid.has_value()) {
// Target not running: wait for pollInterval OR manual scanTriggerEvent with 0% CPU consumption
HANDLE waitHandles[2] = { stopEvent.Get(), scanTriggerEvent_.Get() };
DWORD waitCount = scanTriggerEvent_.IsValid() ? 2 : 1;
DWORD waitResult = ::WaitForMultipleObjects(waitCount, waitHandles, FALSE, static_cast<DWORD>(config_.pollInterval.count()));
if (waitResult == WAIT_OBJECT_0) {
// Stop requested during sleep
break;
}
// If WAIT_OBJECT_0 + 1 (trigger event) or WAIT_TIMEOUT, loop to check for process
continue;
}
DWORD pid = *maybePid;
Log(LogLevel::Info, "Target process detected: '" + targetNameNarrow + "' (PID: " + std::to_string(pid) + ")");
// Acquire process handle with minimum required access rights
// PROCESS_SET_INFORMATION: SetPriorityClass, SetProcessAffinityMask
// PROCESS_QUERY_LIMITED_INFORMATION: GetPriorityClass, GetProcessAffinityMask, GetProcessTimes
// SYNCHRONIZE: WaitForSingleObject / WaitForMultipleObjects
DWORD desiredAccess = PROCESS_SET_INFORMATION | PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE;
UniqueHandle hProcess(::OpenProcess(desiredAccess, FALSE, pid));
if (!hProcess.IsValid()) {
DWORD err = ::GetLastError();
Log(LogLevel::Error, "Failed to open process PID " + std::to_string(pid) +
". Error: " + FormatWin32Error(err) +
" (Elevation / Administrator rights may be required if the game is running as Admin).");
// Wait before retrying to prevent busy-looping if permissions fail
HANDLE waitHandles[2] = { stopEvent.Get(), scanTriggerEvent_.Get() };
DWORD waitCount = scanTriggerEvent_.IsValid() ? 2 : 1;
DWORD waitResult = ::WaitForMultipleObjects(waitCount, waitHandles, FALSE, static_cast<DWORD>(config_.pollInterval.count()));
if (waitResult == WAIT_OBJECT_0) {
break;
}
continue;
}
// Initialize snapshot for this session
ProcessStateSnapshot snapshot{};
snapshot.processId = pid;
if (OptimizeProcess(hProcess.Get(), pid, snapshot)) {
{
std::lock_guard<std::mutex> lock(stateMutex_);
activeSnapshot_ = snapshot;
}
isOptimized_.store(true);
Log(LogLevel::Success, "Target process successfully optimized! Entering zero-CPU monitoring state.");
// Wait on stop event, process exit, AND manual re-scan trigger
HANDLE waitHandles[3] = { stopEvent.Get(), hProcess.Get(), scanTriggerEvent_.Get() };
DWORD waitCount = scanTriggerEvent_.IsValid() ? 3 : 2;
while (!stopToken.stop_requested()) {
DWORD waitResult = ::WaitForMultipleObjects(waitCount, waitHandles, FALSE, INFINITE);
if (waitResult == WAIT_OBJECT_0) {
// Stop requested while game is still actively running
Log(LogLevel::Info, "Optimizer shutdown requested while game is still running. Reverting states...");
RestoreProcessState(hProcess.Get(), snapshot, /*processIsAlive=*/true);
{
std::lock_guard<std::mutex> lock(stateMutex_);
activeSnapshot_.reset();
}
isOptimized_.store(false);
return;
} else if (waitResult == WAIT_OBJECT_0 + 1) {
// Target process terminated
Log(LogLevel::Info, "Target process (PID: " + std::to_string(pid) + ") terminated. Executing fault-tolerant restoration...");
RestoreProcessState(hProcess.Get(), snapshot, /*processIsAlive=*/false);
{
std::lock_guard<std::mutex> lock(stateMutex_);
activeSnapshot_.reset();
}
isOptimized_.store(false);
Log(LogLevel::Info, "Restoration complete. Resuming monitoring for next launch...");
break;
} else if (waitResult == WAIT_OBJECT_0 + 2) {
// User triggered manual re-scan / re-check while game is running
Log(LogLevel::Info, "Re-verifying process optimization state...");
// Re-apply affinity mask in case the game reset its own affinity
DWORD_PTR currentAffinity = 0;
DWORD_PTR sysAffinity = 0;
if (::GetProcessAffinityMask(hProcess.Get(), ¤tAffinity, &sysAffinity)) {
DWORD_PTR targetAff = ComputeTargetAffinity(currentAffinity, sysAffinity);
if (currentAffinity != targetAff) {
::SetProcessAffinityMask(hProcess.Get(), targetAff);
Log(LogLevel::Success, "Re-applied affinity mask: " + AffinityMaskToString(targetAff));
}
}
} else {
Log(LogLevel::Error, "Unexpected wait result in WaitForMultipleObjects: " + std::to_string(waitResult));
break;
}
}
} else {
Log(LogLevel::Warning, "Optimization phase failed. Retrying in next polling cycle.");
HANDLE waitHandles[2] = { stopEvent.Get(), scanTriggerEvent_.Get() };
DWORD waitCount = scanTriggerEvent_.IsValid() ? 2 : 1;
DWORD waitResult = ::WaitForMultipleObjects(waitCount, waitHandles, FALSE, static_cast<DWORD>(config_.pollInterval.count()));
if (waitResult == WAIT_OBJECT_0) {
break;
}
}
}
isRunning_.store(false);
Log(LogLevel::Info, "Worker thread terminated cleanly.");
}
// ============================================================================
// Process Discovery via Toolhelp32 Snapshot
// ============================================================================
std::optional<DWORD> GameOptimizer::FindTargetProcessId(std::wstring_view processName) {
if (processName.empty()) {
return std::nullopt;
}
// Extract bare filename in case user passed or selected a full path (e.g. C:\Games\cs2.exe)
std::wstring target(processName);
size_t slashPos = target.find_last_of(L"\\/");
if (slashPos != std::wstring::npos) {
target = target.substr(slashPos + 1);
}
// Trim any trailing/leading whitespace
while (!target.empty() && iswspace(target.front())) target.erase(target.begin());
while (!target.empty() && iswspace(target.back())) target.pop_back();
if (target.empty()) {
return std::nullopt;
}
bool hasExeExt = (target.size() >= 4 && ::_wcsicmp(target.c_str() + target.size() - 4, L".exe") == 0);
std::wstring targetWithExe = hasExeExt ? target : (target + L".exe");
UniqueHandle snapshot(::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0));
if (!snapshot.IsValid()) {
return std::nullopt;
}
PROCESSENTRY32W entry{};
entry.dwSize = sizeof(PROCESSENTRY32W);
if (!::Process32FirstW(snapshot.Get(), &entry)) {
return std::nullopt;
}
DWORD selfPid = ::GetCurrentProcessId();
do {
if (entry.th32ProcessID <= 4 || entry.th32ProcessID == selfPid) {
continue; // Skip system idle, system, and our own process
}
// Case-insensitive comparison against filename (with and without .exe)
if (::_wcsicmp(entry.szExeFile, target.c_str()) == 0 ||
::_wcsicmp(entry.szExeFile, targetWithExe.c_str()) == 0) {
return entry.th32ProcessID;
}
} while (::Process32NextW(snapshot.Get(), &entry));
return std::nullopt;
}
// ============================================================================
// Core Optimization Actions
// ============================================================================
bool GameOptimizer::OptimizeProcess(HANDLE hProcess, DWORD pid, ProcessStateSnapshot& snapshot) {
Log(LogLevel::Info, "--- Capturing Pre-Optimization State Snapshot ---");
// 1. Capture Original Priority Class
DWORD originalPriority = ::GetPriorityClass(hProcess);
if (originalPriority == 0) {
DWORD err = ::GetLastError();
Log(LogLevel::Error, "Failed to query priority class for PID " + std::to_string(pid) + ". Error: " + FormatWin32Error(err));
return false;
}
snapshot.originalPriorityClass = originalPriority;
Log(LogLevel::Info, "Original Priority Class: 0x" + std::to_string(originalPriority));
// 2. Capture Original Process and System Affinity Masks
DWORD_PTR procAffinity = 0;
DWORD_PTR sysAffinity = 0;
if (!::GetProcessAffinityMask(hProcess, &procAffinity, &sysAffinity)) {
DWORD err = ::GetLastError();
Log(LogLevel::Error, "Failed to query affinity mask for PID " + std::to_string(pid) + ". Error: " + FormatWin32Error(err));
return false;
}
snapshot.originalProcessAffinity = procAffinity;
snapshot.systemAffinity = sysAffinity;
Log(LogLevel::Info, "Original Process Affinity: " + AffinityMaskToString(procAffinity));
Log(LogLevel::Info, "System Available Affinity: " + AffinityMaskToString(sysAffinity));
// 3. Capture and Switch System Power Plan
if (config_.enableDynamicPowerPlan) {
GUID* pActiveScheme = nullptr;
DWORD pwrStatus = ::PowerGetActiveScheme(nullptr, &pActiveScheme);
if (pwrStatus == ERROR_SUCCESS && pActiveScheme != nullptr) {
snapshot.originalPowerScheme = *pActiveScheme;
snapshot.powerSchemeCaptured = true;
Log(LogLevel::Info, "Original Active Power Scheme: " + GuidToString(*pActiveScheme));
::LocalFree(pActiveScheme);
// Switch to High Performance Scheme
DWORD switchStatus = ::PowerSetActiveScheme(nullptr, &HighPerformanceSchemeGuid);
if (switchStatus == ERROR_SUCCESS) {
snapshot.powerSchemeSwitched = true;
Log(LogLevel::Success, "Dynamic Power Plan: Switched to High Performance (" + GuidToString(HighPerformanceSchemeGuid) + ")");
} else {
Log(LogLevel::Warning, "Dynamic Power Plan: Failed to set High Performance scheme. Error: " + FormatWin32Error(switchStatus));
}
} else {
Log(LogLevel::Warning, "Dynamic Power Plan: Could not query active power scheme. Error: " + FormatWin32Error(pwrStatus));
}
}
// 4. Multimedia Class Scheduler Service (MMCSS) Integration
if (config_.enableMmcss) {
DWORD taskIndex = 0;
HANDLE hMmcss = ::AvSetMmThreadCharacteristicsW(L"Games", &taskIndex);
if (hMmcss != nullptr) {
mmcssTask_.Reset(hMmcss);
snapshot.mmcssActivated = true;
Log(LogLevel::Success, "MMCSS: Associated monitoring thread with 'Games' profile (Task Index: " + std::to_string(taskIndex) + ")");
} else {
DWORD err = ::GetLastError();
Log(LogLevel::Warning, "MMCSS: AvSetMmThreadCharacteristicsW failed. Error: " + FormatWin32Error(err));
}
}
// 5. Windows 1ms High-Resolution System Scheduler Timer (timeBeginPeriod)
if (config_.enableHighResolutionTimer) {
MMRESULT timerStatus = ::timeBeginPeriod(1);
if (timerStatus == TIMERR_NOERROR) {
snapshot.highResolutionTimerActive = true;
Log(LogLevel::Success, "Kernel Scheduler Timer: 1ms high-resolution timer engaged (timeBeginPeriod).");
} else {
Log(LogLevel::Warning, "Kernel Scheduler Timer: Failed to set 1ms timer period. Status: " + std::to_string(timerStatus));
}
}
Log(LogLevel::Info, "--- Applying Process Optimizations ---");
// 6. Elevate Priority Class (HIGH_PRIORITY_CLASS; avoid REALTIME)
if (config_.targetPriorityClass != snapshot.originalPriorityClass) {
if (::SetPriorityClass(hProcess, config_.targetPriorityClass)) {
snapshot.priorityElevated = true;
Log(LogLevel::Success, "Process Priority: Elevated to HIGH_PRIORITY_CLASS (0x00000080)");
} else {
DWORD err = ::GetLastError();
Log(LogLevel::Error, "Process Priority: Failed to elevate priority class. Error: " + FormatWin32Error(err));
}
} else {
Log(LogLevel::Info, "Process Priority: Target already configured with requested priority class.");
}
// 7. Calculate and Apply CPU Affinity Mask (Core Isolation)
DWORD_PTR targetAffinity = ComputeTargetAffinity(procAffinity, sysAffinity);
if (targetAffinity != procAffinity) {
if (::SetProcessAffinityMask(hProcess, targetAffinity)) {
snapshot.affinityModified = true;
Log(LogLevel::Success, "CPU Affinity Isolation: Applied new mask -> " + AffinityMaskToString(targetAffinity));
} else {
DWORD err = ::GetLastError();
Log(LogLevel::Error, "CPU Affinity Isolation: Failed to set mask. Error: " + FormatWin32Error(err));
}
} else {
Log(LogLevel::Info, "CPU Affinity Isolation: Target process already running with desired affinity mask.");
}
return true;
}
// ============================================================================
// State Restoration Machine (Fault-Tolerant Rollback)
// ============================================================================
void GameOptimizer::RestoreProcessState(HANDLE hProcess, ProcessStateSnapshot& snapshot, bool processIsAlive) {
Log(LogLevel::Info, "--- Initiating State Rollback ---");
// Revert Process Priority and Affinity if process is still running
if (processIsAlive && hProcess != nullptr) {
if (snapshot.priorityElevated) {
if (::SetPriorityClass(hProcess, snapshot.originalPriorityClass)) {
Log(LogLevel::Info, "Restored original process priority class (0x" + std::to_string(snapshot.originalPriorityClass) + ").");
} else {
Log(LogLevel::Warning, "Failed to restore process priority. Error: " + FormatWin32Error(::GetLastError()));
}
snapshot.priorityElevated = false;
}
if (snapshot.affinityModified) {
if (::SetProcessAffinityMask(hProcess, snapshot.originalProcessAffinity)) {
Log(LogLevel::Info, "Restored original process affinity mask (" + AffinityMaskToString(snapshot.originalProcessAffinity) + ").");
} else {
Log(LogLevel::Warning, "Failed to restore process affinity mask. Error: " + FormatWin32Error(::GetLastError()));
}
snapshot.affinityModified = false;
}
} else {
Log(LogLevel::Info, "Target process has exited; kernel automatically reclaimed process priority and affinity.");
}
// Revert System Power Scheme
if (snapshot.powerSchemeSwitched && snapshot.powerSchemeCaptured) {
DWORD status = ::PowerSetActiveScheme(nullptr, &snapshot.originalPowerScheme);
if (status == ERROR_SUCCESS) {
Log(LogLevel::Success, "Restored original Windows power plan: " + GuidToString(snapshot.originalPowerScheme));
snapshot.powerSchemeSwitched = false;
} else {
Log(LogLevel::Warning, "Failed to revert power plan. Error: " + FormatWin32Error(status));
}
}
// Revert MMCSS Task Characteristics
if (snapshot.mmcssActivated) {
mmcssTask_.Reset();
snapshot.mmcssActivated = false;
Log(LogLevel::Info, "Reverted MMCSS scheduling characteristics.");
}
// Revert High-Resolution Kernel Scheduler Timer
if (snapshot.highResolutionTimerActive) {
::timeEndPeriod(1);
snapshot.highResolutionTimerActive = false;
Log(LogLevel::Info, "Restored default Windows kernel scheduler timer resolution.");
}
}
// ============================================================================
// Affinity Mask Computation & Topology Awareness
// ============================================================================
DWORD_PTR GameOptimizer::ComputeTargetAffinity([[maybe_unused]] DWORD_PTR currentAffinity, DWORD_PTR systemAffinity) {
switch (config_.affinityPolicy) {
case AffinityPolicy::AllCores:
return systemAffinity;
case AffinityPolicy::IsolateLogicalCpu0: {
// Mask out bit 0 (Logical Core 0)
DWORD_PTR isolated = systemAffinity & ~static_cast<DWORD_PTR>(1);
if (isolated != 0) {
return isolated;
}
// Fallback to system affinity if system only has 1 core
Log(LogLevel::Warning, "Single-core CPU detected; cannot isolate CPU 0. Falling back to all cores.");
return systemAffinity;
}
case AffinityPolicy::IsolatePhysicalCore0: {
// Detect and mask out all logical threads sharing Physical Core 0
DWORD_PTR core0Mask = GetPhysicalCore0Mask(systemAffinity);
DWORD_PTR isolated = systemAffinity & ~core0Mask;
if (isolated != 0) {
return isolated;
}
Log(LogLevel::Warning, "Insufficient physical cores to isolate Core 0. Falling back to Logical CPU 0 isolation.");
DWORD_PTR fallback = systemAffinity & ~static_cast<DWORD_PTR>(1);
return (fallback != 0) ? fallback : systemAffinity;
}
case AffinityPolicy::IsolateECores: {
// Run exclusively on Performance Cores (P-Cores)
DWORD_PTR pCores = GetPerformanceCoresMask(systemAffinity);
if (pCores != 0 && pCores != systemAffinity) {
return pCores;
}
Log(LogLevel::Warning, "No distinct E-Cores detected on this CPU. Falling back to all cores.");
return systemAffinity;
}
case AffinityPolicy::CustomMask: {
// Ensure custom mask only selects cores present on the system
DWORD_PTR sanitized = config_.customAffinityMask & systemAffinity;
if (sanitized != 0) {
return sanitized;
}
Log(LogLevel::Warning, "Custom affinity mask (0x" + AffinityMaskToString(config_.customAffinityMask) +
") contains no active system cores. Falling back to system affinity.");
return systemAffinity;
}
default:
return systemAffinity;
}
}
DWORD_PTR GameOptimizer::GetPhysicalCore0Mask(DWORD_PTR systemAffinity) {
DWORD bufferSize = 0;
// Determine required buffer size for logical processor relationship info
::GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &bufferSize);
if (bufferSize == 0) {
// Fallback: bit 0 only
return static_cast<DWORD_PTR>(1);
}
std::vector<uint8_t> buffer(bufferSize);
auto* pInfo = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data());
if (!::GetLogicalProcessorInformationEx(RelationProcessorCore, pInfo, &bufferSize)) {
return static_cast<DWORD_PTR>(1);
}
DWORD offset = 0;
while (offset < bufferSize) {
auto* current = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data() + offset);
if (current->Size == 0) {
break; // Guard against potential infinite loop if size is zero
}
if (current->Relationship == RelationProcessorCore) {
// Examine group masks for this physical core
for (WORD g = 0; g < current->Processor.GroupCount; ++g) {
const auto& groupMask = current->Processor.GroupMask[g];
// In group 0, check if this physical core owns logical core 0 (bit 0)
if (groupMask.Group == 0 && (groupMask.Mask & 1ULL) != 0) {
return static_cast<DWORD_PTR>(groupMask.Mask) & systemAffinity;
}
}
}
offset += current->Size;
}
// Default fallback: bit 0
return static_cast<DWORD_PTR>(1);
}
DWORD_PTR GameOptimizer::GetPerformanceCoresMask(DWORD_PTR systemAffinity) {
DWORD bufferSize = 0;
::GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &bufferSize);
if (bufferSize == 0) {
return systemAffinity;
}
std::vector<uint8_t> buffer(bufferSize);
auto* pInfo = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data());
if (!::GetLogicalProcessorInformationEx(RelationProcessorCore, pInfo, &bufferSize)) {
return systemAffinity;
}
// Pass 1: Find highest EfficiencyClass (P-Cores)
BYTE maxEfficiencyClass = 0;
DWORD offset = 0;
while (offset < bufferSize) {
auto* current = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data() + offset);
if (current->Size == 0) break;
if (current->Relationship == RelationProcessorCore) {
if (current->Processor.EfficiencyClass > maxEfficiencyClass) {
maxEfficiencyClass = current->Processor.EfficiencyClass;
}
}
offset += current->Size;
}
// If all cores have the same efficiency class (e.g. 0), non-hybrid CPU
if (maxEfficiencyClass == 0) {
return systemAffinity;
}
// Pass 2: Accumulate mask of cores matching maxEfficiencyClass
DWORD_PTR pCoreMask = 0;
offset = 0;
while (offset < bufferSize) {
auto* current = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data() + offset);
if (current->Size == 0) break;
if (current->Relationship == RelationProcessorCore) {
if (current->Processor.EfficiencyClass == maxEfficiencyClass) {
for (WORD g = 0; g < current->Processor.GroupCount; ++g) {
const auto& groupMask = current->Processor.GroupMask[g];
if (groupMask.Group == 0) {
pCoreMask |= static_cast<DWORD_PTR>(groupMask.Mask);
}
}
}
}
offset += current->Size;
}
pCoreMask &= systemAffinity;
return (pCoreMask != 0) ? pCoreMask : systemAffinity;
}
bool GameOptimizer::HasHybridArchitecture() {
DWORD bufferSize = 0;
::GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &bufferSize);
if (bufferSize == 0) {
return false;
}
std::vector<uint8_t> buffer(bufferSize);
auto* pInfo = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data());
if (!::GetLogicalProcessorInformationEx(RelationProcessorCore, pInfo, &bufferSize)) {
return false;
}
BYTE minClass = 255;
BYTE maxClass = 0;
DWORD offset = 0;
while (offset < bufferSize) {
auto* current = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data() + offset);
if (current->Size == 0) break;
if (current->Relationship == RelationProcessorCore) {
BYTE eff = current->Processor.EfficiencyClass;
if (eff < minClass) minClass = eff;
if (eff > maxClass) maxClass = eff;
}
offset += current->Size;
}
return (maxClass > minClass);
}
std::optional<ProcessLiveTelemetry> GameOptimizer::GetLiveTelemetry() const {
if (!isOptimized_.load()) {
return std::nullopt;
}
DWORD pid = 0;
{
std::lock_guard<std::mutex> lock(stateMutex_);
if (!activeSnapshot_.has_value()) {
return std::nullopt;
}
pid = activeSnapshot_->processId;
}
UniqueHandle hProcess(::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid));
if (!hProcess.IsValid()) {
return std::nullopt;
}
ProcessLiveTelemetry telemetry{};
// 1. Working Set Memory
PROCESS_MEMORY_COUNTERS memCounters{};
memCounters.cb = sizeof(memCounters);
if (::K32GetProcessMemoryInfo(hProcess.Get(), &memCounters, sizeof(memCounters))) {
telemetry.workingSetBytes = memCounters.WorkingSetSize;
}
// 2. CPU Usage Calculation
FILETIME creationTime{}, exitTime{}, kernelTime{}, userTime{};
FILETIME sysIdleTime{}, sysKernelTime{}, sysUserTime{};
if (::GetProcessTimes(hProcess.Get(), &creationTime, &exitTime, &kernelTime, &userTime) &&
::GetSystemTimes(&sysIdleTime, &sysKernelTime, &sysUserTime)) {
ULARGE_INTEGER procK, procU, sysK, sysU;
procK.LowPart = kernelTime.dwLowDateTime; procK.HighPart = kernelTime.dwHighDateTime;
procU.LowPart = userTime.dwLowDateTime; procU.HighPart = userTime.dwHighDateTime;
sysK.LowPart = sysKernelTime.dwLowDateTime; sysK.HighPart = sysKernelTime.dwHighDateTime;
sysU.LowPart = sysUserTime.dwLowDateTime; sysU.HighPart = sysUserTime.dwHighDateTime;
ULONGLONG curProc = procK.QuadPart + procU.QuadPart;
ULONGLONG curSys = sysK.QuadPart + sysU.QuadPart;
if (prevSystemCpuTime_ != 0 && curSys > prevSystemCpuTime_) {
ULONGLONG procDiff = (curProc >= prevProcessCpuTime_) ? (curProc - prevProcessCpuTime_) : 0;
ULONGLONG sysDiff = curSys - prevSystemCpuTime_;
// Total system logical processors
SYSTEM_INFO sysInfo{};
::GetSystemInfo(&sysInfo);
double totalProcessors = (sysInfo.dwNumberOfProcessors > 0) ? static_cast<double>(sysInfo.dwNumberOfProcessors) : 1.0;
telemetry.cpuUsagePercent = (static_cast<double>(procDiff) / static_cast<double>(sysDiff)) * 100.0 * totalProcessors;
if (telemetry.cpuUsagePercent < 0.0) telemetry.cpuUsagePercent = 0.0;
if (telemetry.cpuUsagePercent > 100.0) telemetry.cpuUsagePercent = 100.0;
}
prevProcessCpuTime_ = curProc;
prevSystemCpuTime_ = curSys;
}
// 3. Thread Count
UniqueHandle threadSnap(::CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0));
if (threadSnap.IsValid()) {
THREADENTRY32 te{};
te.dwSize = sizeof(THREADENTRY32);
if (::Thread32First(threadSnap.Get(), &te)) {
uint32_t count = 0;
do {
if (te.th32OwnerProcessID == pid) {
++count;
}
} while (::Thread32Next(threadSnap.Get(), &te));
telemetry.threadCount = count;
}
}
return telemetry;
}
// ============================================================================
// Utilities & Logging
// ============================================================================
std::string GameOptimizer::FormatWin32Error(DWORD errorCode) {
if (errorCode == 0) {
return "Operation completed successfully (0).";
}
LPSTR messageBuffer = nullptr;
DWORD size = ::FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
errorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPSTR>(&messageBuffer),
0,
nullptr
);
std::string result;
if (size > 0 && messageBuffer != nullptr) {
result = messageBuffer;
// Trim trailing newlines
while (!result.empty() && (result.back() == '\r' || result.back() == '\n')) {
result.pop_back();
}
::LocalFree(messageBuffer);
} else {
result = "Unknown Win32 error";
}
std::ostringstream ss;
ss << result << " (Error Code: " << errorCode << " / 0x" << std::hex << errorCode << ")";
return ss.str();
}
std::string GameOptimizer::GuidToString(const GUID& guid) {
char buffer[64];
std::snprintf(buffer, sizeof(buffer),
"{%08lX-%04hX-%04hX-%02X%02X-%02X%02X%02X%02X%02X%02X}",
guid.Data1, guid.Data2, guid.Data3,
guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
return std::string(buffer);
}
std::string GameOptimizer::AffinityMaskToString(DWORD_PTR mask) {
std::ostringstream ss;
ss << "0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(sizeof(DWORD_PTR) * 2) << mask;
// Generate active core list representation, e.g. [1, 2, 3, 4, 5, 6, 7]
std::vector<int> activeCores;
for (size_t i = 0; i < sizeof(DWORD_PTR) * 8; ++i) {
if ((mask & (static_cast<DWORD_PTR>(1) << i)) != 0) {
activeCores.push_back(static_cast<int>(i));
}
}
ss << " (Cores: ";
if (activeCores.empty()) {
ss << "None";
} else {
for (size_t i = 0; i < activeCores.size(); ++i) {
ss << activeCores[i];
if (i + 1 < activeCores.size()) {
ss << ", ";
}
}
}
ss << ")";
return ss.str();
}
void GameOptimizer::Log(LogLevel level, std::string_view message) const {
if (config_.logger) {
config_.logger(level, message);
return;
}
// Default console logger with timestamps and level tags
auto now = std::chrono::system_clock::now();
auto timeT = std::chrono::system_clock::to_time_t(now);
std::tm tm{};
::localtime_s(&tm, &timeT);
std::ostringstream prefix;
prefix << "[" << std::setfill('0') << std::setw(2) << tm.tm_hour << ":"
<< std::setfill('0') << std::setw(2) << tm.tm_min << ":"
<< std::setfill('0') << std::setw(2) << tm.tm_sec << "] ";
switch (level) {
case LogLevel::Trace: prefix << "[TRACE] "; break;
case LogLevel::Info: prefix << "[INFO] "; break;
case LogLevel::Success: prefix << "[SUCCESS] "; break;
case LogLevel::Warning: prefix << "[WARNING] "; break;
case LogLevel::Error: prefix << "[ERROR] "; break;
}
if (level == LogLevel::Error) {
std::cerr << prefix.str() << message << std::endl;
} else {
std::cout << prefix.str() << message << std::endl;
}
}
std::string GameOptimizer::WideToNarrow(std::wstring_view wstr) {
if (wstr.empty()) {
return {};
}
int size = ::WideCharToMultiByte(CP_UTF8, 0, wstr.data(), static_cast<int>(wstr.size()), nullptr, 0, nullptr, nullptr);
if (size <= 0) {
return {};
}
std::string result(size, 0);
::WideCharToMultiByte(CP_UTF8, 0, wstr.data(), static_cast<int>(wstr.size()), result.data(), size, nullptr, nullptr);
return result;
}
std::wstring GameOptimizer::NarrowToWide(std::string_view str) {
if (str.empty()) {
return {};
}
int size = ::MultiByteToWideChar(CP_UTF8, 0, str.data(), static_cast<int>(str.size()), nullptr, 0);
if (size <= 0) {
return {};
}
std::wstring result(size, 0);
::MultiByteToWideChar(CP_UTF8, 0, str.data(), static_cast<int>(str.size()), result.data(), size);
return result;
}
} // namespace Corelock