From 1c3f17ff30bc2c2ebd0435a8ba1aace5292c0a62 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:58:41 -0500 Subject: [PATCH 01/15] OptiScaler plugin path: honour the launcher's model choice (Model L, K) With WrongGPU.asi hooked in OptiScaler's menu, the plugin's saved entry could only be M, K or AMD, defaulted to M, and always decided the model: a launcher choice of Model L (model=L in wronggpu.ini, L's UpscalerIndex) ran Model M (or a remembered K) with no warning. - The plugin learns Model L (its menu entry, wronggpu-asi.ini selection=wronggpu-l) and records when the player clicked (chosen=). New exports: WrongGpuAsiQueryChoiceV1 (model, explicit or default, time) and WrongGpuAsiShowModelV1 (the front end tells the menu which model runs). The old query reports L as M. - The launcher writes model_chosen= into wronggpu.ini whenever it changes the model item of runtime_options (any model letter). - The front end decides with model_precedence.h: the launcher's choice wins over the plugin's default entry and the reverse; two explicit different choices: the more recent wins (equal or missing times: the plugin's), with one "model choice conflict:" line naming both. - Model L without its file keeps the existing refusal (AMD's FSR upscales); a model the front end lacks runs as Model M, with a note. Tests: front end (precedence cases, L file missing, negative control), plugin thunk/selection file/exports, launcher model_chosen. Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/fsr/CMakeLists.txt | 10 +- clean/fsr/asi/README.md | 14 +- clean/fsr/asi/asi_abi.h | 30 ++- clean/fsr/asi/asi_thunk.h | 121 +++++++--- clean/fsr/asi/exports_asi.def | 2 + clean/fsr/asi/wronggpu_asi.cpp | 78 +++++-- clean/fsr/src/asi_bridge.cpp | 29 ++- clean/fsr/src/asi_bridge.h | 13 +- clean/fsr/src/config.cpp | 4 + clean/fsr/src/config.h | 3 + clean/fsr/src/dllmain.cpp | 8 +- clean/fsr/src/frontend.cpp | 78 +++++-- clean/fsr/src/frontend.h | 12 +- clean/fsr/src/model_precedence.h | 101 +++++++++ clean/fsr/tests/test_asi_status.cpp | 22 ++ clean/fsr/tests/test_asi_thunk.cpp | 81 ++++++- clean/fsr/tests/test_frontend.cpp | 219 ++++++++++++++++++- clean/installer/src/wg_core/profile.cpp | 12 +- clean/installer/src/wg_core/profile.h | 6 +- clean/installer/tests/model_choice_tests.cpp | 24 +- 20 files changed, 777 insertions(+), 90 deletions(-) create mode 100644 clean/fsr/src/model_precedence.h diff --git a/clean/fsr/CMakeLists.txt b/clean/fsr/CMakeLists.txt index c9ad07d3..f81a70df 100644 --- a/clean/fsr/CMakeLists.txt +++ b/clean/fsr/CMakeLists.txt @@ -111,7 +111,12 @@ endif() # WrongGPU OptiScaler ASI plugin: thunk logic (any OS) and the offline anchor scan of an OptiScaler binary # (any OS; skips when WRONGGPU_OPTISCALER_BIN is not set). Header-only resolver/thunk, no extra libraries. add_executable(test_asi_thunk tests/test_asi_thunk.cpp) +target_compile_definitions(test_asi_thunk PRIVATE WRONGGPU_MODEL_L=${WG_MODEL_L_VALUE}) add_test(NAME fsr_asi_thunk_unit COMMAND test_asi_thunk) +# The plugin's menu and saved choice with Model L (and Model K), whatever this build's switches: the 0.6.5 shape. +add_executable(test_asi_thunk_kl tests/test_asi_thunk.cpp) +target_compile_definitions(test_asi_thunk_kl PRIVATE WRONGGPU_MODEL_K_OVERRIDE=1 WRONGGPU_MODEL_L=1) +add_test(NAME fsr_asi_thunk_kl_unit COMMAND test_asi_thunk_kl) add_executable(test_asi_patch tests/test_asi_patch.cpp) add_test(NAME fsr_asi_patch_unit COMMAND test_asi_patch) add_executable(test_asi_lifetime tests/test_asi_lifetime.cpp) @@ -120,7 +125,7 @@ add_executable(test_asi_scan tests/test_asi_scan.cpp) add_test(NAME fsr_asi_scan_unit COMMAND test_asi_scan) set_tests_properties(fsr_asi_scan_unit PROPERTIES SKIP_RETURN_CODE 77) if(MSVC) - set_property(TARGET test_asi_thunk test_asi_scan test_asi_patch test_asi_lifetime PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + set_property(TARGET test_asi_thunk test_asi_thunk_kl test_asi_scan test_asi_patch test_asi_lifetime PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") endif() if(WIN32) @@ -141,6 +146,7 @@ if(WIN32) endif() target_link_options(test_fsr30 PRIVATE ${WG_STATIC_RUNTIME}) target_link_options(test_asi_thunk PRIVATE ${WG_STATIC_RUNTIME}) + target_link_options(test_asi_thunk_kl PRIVATE ${WG_STATIC_RUNTIME}) target_link_options(test_asi_scan PRIVATE ${WG_STATIC_RUNTIME}) target_link_options(test_asi_patch PRIVATE ${WG_STATIC_RUNTIME}) target_link_options(test_asi_lifetime PRIVATE ${WG_STATIC_RUNTIME}) @@ -255,7 +261,7 @@ if(WIN32) set_target_properties(wronggpu_asi PROPERTIES PREFIX "" OUTPUT_NAME WrongGPU SUFFIX ".asi" MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") target_include_directories(wronggpu_asi PRIVATE src) - target_compile_definitions(wronggpu_asi PRIVATE _CRT_SECURE_NO_WARNINGS NOMINMAX) + target_compile_definitions(wronggpu_asi PRIVATE _CRT_SECURE_NO_WARNINGS NOMINMAX WRONGGPU_MODEL_L=${WG_MODEL_L_VALUE}) if(MSVC) target_compile_options(wronggpu_asi PRIVATE /W4 /wd4100 /Zi) target_link_options(wronggpu_asi PRIVATE /DEBUG:FULL /INCREMENTAL:NO) diff --git a/clean/fsr/asi/README.md b/clean/fsr/asi/README.md index 6a511070..1f909e2e 100644 --- a/clean/fsr/asi/README.md +++ b/clean/fsr/asi/README.md @@ -21,6 +21,17 @@ What the front end does with the plugin's entry (`src/frontend.cpp`, `TestAsiPlu whatever the FFX box names; "FSR 3.X(/4)" runs AMD: the AMD version the FFX box names, else AMD's newest listed version. The FFX box's list is the same with and without the plugin (WrongGPU first). +Which model runs (0.6.5, `src/model_precedence.h`, `TestAsiLauncherPrecedence`): the plugin's saved entry is weighed +against the launcher's model choice, the last `model=` item of wronggpu.ini's `runtime_options`. Each side records when +it was chosen: the plugin writes `chosen=` into `wronggpu-asi.ini` on every click in the menu, +and the launcher writes `model_chosen=` into wronggpu.ini whenever it changes the model item. A choice is a +*default* when nobody made it (no file, or Model M with no time on either side). The launcher's choice wins over the +plugin's default; the plugin's explicit choice wins over the launcher's default; when both are explicit and differ, the +more recent one wins (equal or missing times: the plugin's, the choice made in the game), and the front end logs one +`model choice conflict:` line naming both and the winner. The front end tells the plugin which model runs +(`WrongGpuAsiShowModelV1`), so the menu marks that entry. Model L's own entry ("WrongGPU Model L") is in the menu of a +build with `WG_MODEL_L`; a model the front end was built without runs as Model M, with a note in the log. + ## How it works 1. OptiScaler loads the plugin and calls its exported `InitializeASI()`. `opti_module.h` finds OptiScaler's module @@ -41,7 +52,8 @@ The FFX box's list is the same with and without the plugin (WrongGPU first). none of OptiScaler's data. 4. WrongGPU's front end (`amd_fidelityfx_dx12.dll`) finds the plugin by module and asks it (`WrongGpuAsiQuery`, `asi_abi.h`) which model is selected. The FFX list always starts with WrongGPU entries followed by AMD entries; - when hooked, the front end creates Model M / Model K / AMD according to the plugin selection. + when hooked, the front end creates Model M / K / L or AMD from the plugin's selection weighed against the launcher's + model choice (`WrongGpuAsiQueryChoiceV1`; see "Which model runs" above). If a required anchor is missing or ambiguous, or a stub cannot be placed, nothing is patched and the plugin reports "not hooked". Call sites are prepared and revalidated before publication. A failed write rolls back sites whose diff --git a/clean/fsr/asi/asi_abi.h b/clean/fsr/asi/asi_abi.h index 157a480f..37b6993c 100644 --- a/clean/fsr/asi/asi_abi.h +++ b/clean/fsr/asi/asi_abi.h @@ -12,8 +12,8 @@ // Query result. `hooked` is 1 after the prepared menu call-patch transaction commits; it does not promise // complete menu adaptation. The FFX list still contains WrongGPU and AMD entries. Zero means inactive: the -// front end then behaves as if no plugin were present. `model` is 0 (OptiScaler's own FSR 3.X / AMD), 'M' or 'K'. -// Returns the ABI version (>= 1), or 0 on error. Signature: int WrongGpuAsiQuery(int* hooked, char* model). +// front end then behaves as if no plugin were present. `model` is 0 (OptiScaler's own FSR 3.X / AMD), 'M' or 'K' +// (a saved Model L reads as 'M' here, for an older front end; WrongGpuAsiQueryChoiceV1 below reports it). Returns the ABI version (>= 1), or 0 on error. Signature: int WrongGpuAsiQuery(int* hooked, char* model). typedef int (*PfnWrongGpuAsiQuery)(int* hooked, char* model); // Additive WrongGPU-owned diagnostic API; this is NOT a host plugin or RR frame ABI. @@ -56,7 +56,7 @@ typedef int (*PfnWrongGpuAsiQuery)(int* hooked, char* model); // Before any host write, the plugin pins its own module until process termination. Pin failure // leaves host call sites untouched. Query-only loads do not pin. Neither query promises host // lifetime, executing-thread atomicity, or safe live unhook/unload. -// Selection is 0 (AMD), 'M', or 'K'; it is NOT evidence of the effective rendering backend. +// Selection is 0 (AMD), 'M', 'K' or 'L' (the saved choice); it is NOT evidence of the effective rendering backend. // Fields are independent observations during initialization/selection changes, not a transactional snapshot. // rr_ready is always zero in this implementation; rr_blockers is a bitmask of the reasons above. typedef struct WrongGpuAsiStatusV1 { @@ -75,3 +75,27 @@ typedef struct WrongGpuAsiStatusV1 { } WrongGpuAsiStatusV1; typedef int (*PfnWrongGpuAsiQueryStatusV1)(WrongGpuAsiStatusV1* status, uint32_t caller_size); + +// The player's saved choice with what the front end needs to weigh it against the launcher's model choice (0.6.5; +// src/model_precedence.h). model: 0 (AMD), 'M', 'K' or 'L'. explicit_choice: 1 when the player chose it in the menu (or +// a file of an earlier version names a non-default entry), 0 for the default entry (no file, or Model M with no time). +// chosen_at: when the player clicked it, seconds since 1970-01-01 UTC; 0 = not recorded. Same size/version rules and +// return codes as WrongGpuAsiQueryStatusV1. A front end that finds no such export uses WrongGpuAsiQuery and treats +// Model M as the default entry and K / AMD as explicit choices with no recorded time. +#define WRONGGPU_ASI_CHOICE_QUERY "WrongGpuAsiQueryChoiceV1" +#define WRONGGPU_ASI_CHOICE_VERSION 1u +typedef struct WrongGpuAsiChoiceV1 { + uint32_t size; + uint32_t version; + uint32_t hooked; + uint32_t model; + uint32_t explicit_choice; + uint32_t reserved; + uint64_t chosen_at; +} WrongGpuAsiChoiceV1; +typedef int (*PfnWrongGpuAsiQueryChoiceV1)(WrongGpuAsiChoiceV1* choice, uint32_t caller_size); + +// The front end reports which model it runs (0 AMD, 'M', 'K', 'L'), so the plugin's menu marks that entry; 1 returns +// to marking the saved choice. Display only: nothing is saved. +#define WRONGGPU_ASI_SHOW_MODEL "WrongGpuAsiShowModelV1" +typedef void (*PfnWrongGpuAsiShowModelV1)(char model); diff --git a/clean/fsr/asi/asi_thunk.h b/clean/fsr/asi/asi_thunk.h index 312d5174..0032029e 100644 --- a/clean/fsr/asi/asi_thunk.h +++ b/clean/fsr/asi/asi_thunk.h @@ -6,31 +6,44 @@ // // It writes none of OptiScaler's data. When the player clicks a WrongGPU item, the Selectable thunk returns "clicked" // for OptiScaler's own "FSR 3.X" entry, so OptiScaler's unchanged code sets its backend to FSR 3.X (which loads -// WrongGPU's FidelityFX DLL); the plugin only remembers which entry the player chose, and the front end reads that -// back. The WrongGPU labels are plain UI text. +// WrongGPU's FidelityFX DLL); the plugin only remembers which entry the player chose (and when), and the front end +// reads that back. The front end decides which model runs (the plugin's choice or the launcher's: frontend +// model_precedence.h) and tells the plugin, so the menu marks the model that actually runs. The WrongGPU labels are +// plain UI text. #include #include +#include +#include #include #include #ifndef WRONGGPU_MODEL_K #define WRONGGPU_MODEL_K 1 #endif +#ifndef WRONGGPU_MODEL_L +#define WRONGGPU_MODEL_L 0 +#endif namespace wgasi { constexpr char kModelAmd = 0; // no WrongGPU model: OptiScaler's own FSR 3.X (AMD) is selected constexpr char kModelM = 'M'; constexpr char kModelK = 'K'; +constexpr char kModelL = 'L'; constexpr char kDefaultModel = kModelM; // WrongGPU is the default entry wherever the plugin hooks +constexpr char kShowSaved = 1; // PluginState::shown: no model reported by the front end, mark the saved one -// The entries the plugin adds in front of OptiScaler's FSR 3.X entry. A build without Model K has one, "WrongGPU". +// The entries the plugin adds in front of OptiScaler's FSR 3.X entry. A build with only Model M has one, "WrongGPU". struct Entry { char model; const char* label; }; -#if WRONGGPU_MODEL_K +#if WRONGGPU_MODEL_K && WRONGGPU_MODEL_L +constexpr Entry kEntries[] = {{kModelM, "WrongGPU Model M"}, {kModelK, "WrongGPU Model K"}, {kModelL, "WrongGPU Model L"}}; +#elif WRONGGPU_MODEL_K constexpr Entry kEntries[] = {{kModelM, "WrongGPU Model M"}, {kModelK, "WrongGPU Model K"}}; +#elif WRONGGPU_MODEL_L +constexpr Entry kEntries[] = {{kModelM, "WrongGPU Model M"}, {kModelL, "WrongGPU Model L"}}; #else constexpr Entry kEntries[] = {{kModelM, "WrongGPU"}}; #endif @@ -42,47 +55,77 @@ inline const char* LabelOf(char model) { return nullptr; } -// Shared plugin state. `hooked` is read by the front end through the exported query; `model` is the player's current -// choice within OptiScaler's FSR 3.X entry. +// Shared plugin state. `hooked` is read by the front end through the exported query. `model` is the player's saved +// choice within OptiScaler's FSR 3.X entry; `explicitChoice` says whether the player (or an earlier version's file) +// actually chose it, as opposed to the default entry; `chosenAt` is when the player clicked it (seconds since +// 1970-01-01 UTC, 0 = not recorded: a file written before 0.6.5, or by an installer). `shown` is the model the front +// end reported as running (kShowSaved until it reports one): the menu marks that one, so a launcher choice that won +// over the plugin's default is what the player sees checked. struct PluginState { std::atomic hooked{false}; std::atomic model{kDefaultModel}; + std::atomic explicitChoice{false}; + std::atomic chosenAt{0}; + std::atomic shown{kShowSaved}; }; +inline char ShownModel(const PluginState& st) { + const char s = st.shown.load(); + return s == kShowSaved ? st.model.load() : s; +} + inline bool IsFsr3xLabel(const char* label) { return label && (std::strcmp(label, "FSR 3.X") == 0 || std::strcmp(label, "FSR 3.X/4") == 0); } // The Selectable thunk. `sel` is the real ImGui::Selectable(label, selected, flags, size). For OptiScaler's FSR 3.X -// entry it draws the WrongGPU items first, then the original entry, records any click as the selected model, and -// returns true (click) to OptiScaler when any of them was clicked so OptiScaler switches to its FSR 3.X backend. -// `selected` (OptiScaler's backend is FSR 3.X) marks the WrongGPU item or the FSR 3.X item, whichever is chosen. -// Every other entry passes through unchanged. +// entry it draws the WrongGPU items first, then the original entry, records any click as the player's explicit choice +// (made at `now`, seconds since 1970 UTC), and returns true (click) to OptiScaler when any of them was clicked so +// OptiScaler switches to its FSR 3.X backend. `selected` (OptiScaler's backend is FSR 3.X) marks the WrongGPU item or +// the FSR 3.X item of the model shown (ShownModel). Every other entry passes through unchanged. *clickedOut (when +// given) is set to true on a click on one of these items, so the caller saves the choice. template -bool SelectableThunkLogic(SelFn&& sel, const char* label, bool selected, int flags, const void* size, PluginState& st) { +bool SelectableThunkLogic(SelFn&& sel, const char* label, bool selected, int flags, const void* size, PluginState& st, + uint64_t now = 0, bool* clickedOut = nullptr) { + if (clickedOut) *clickedOut = false; if (!IsFsr3xLabel(label)) return sel(label, selected, flags, size); - const char model = st.model.load(); + const char model = ShownModel(st); char clicked = 1; // 1: nothing clicked for (const Entry& e : kEntries) if (sel(e.label, selected && model == e.model, flags, size) && clicked == 1) clicked = e.model; if (sel(label, selected && model == kModelAmd, flags, size) && clicked == 1) clicked = kModelAmd; if (clicked == 1) return false; st.model.store(clicked); + st.explicitChoice.store(true); + st.chosenAt.store(now); + st.shown.store(kShowSaved); // the player's click is the newest choice: it runs and is marked + if (clickedOut) *clickedOut = true; return true; } -// The BeginCombo thunk: when a WrongGPU model is selected and OptiScaler would show its FSR 3.X name as the closed +// The BeginCombo thunk: when a WrongGPU model is shown and OptiScaler would show its FSR 3.X name as the closed // combo's preview, show the WrongGPU entry's name instead. `bc` is the real ImGui::BeginCombo(label, preview, flags). template bool BeginComboThunkLogic(BcFn&& bc, const char* label, const char* preview, int flags, PluginState& st) { if (IsFsr3xLabel(preview)) - if (const char* own = LabelOf(st.model.load())) preview = own; + if (const char* own = LabelOf(ShownModel(st))) preview = own; return bc(label, preview, flags); } -// The remembered choice (wronggpu-asi.ini next to the plugin): "selection=wronggpu", "wronggpu-k" or "amd". Anything -// else, or no file, is the default (WrongGPU). Model K in a build without it reads as WrongGPU. -inline char ParseSelection(const std::string& text) { +// The remembered choice (wronggpu-asi.ini next to the plugin): "selection=wronggpu" (Model M), "wronggpu-k", +// "wronggpu-l" or "amd", and since 0.6.5 "chosen=", the time of the player's click. +struct Selection { + char model = kDefaultModel; + bool explicitChoice = false; // false: the default entry (no file, no selection line, an unknown value, or + // Model M with no recorded time: what installers write and what 0.6.0 saved for M) + uint64_t chosenAt = 0; // 0: not recorded +}; + +// Anything else, or no file, is the default (WrongGPU Model M, not an explicit choice). A model this build lacks +// (Model K or L) reads as the default too, so the launcher's choice decides. +inline Selection ParseSelectionFile(const std::string& text) { + Selection s; + bool stated = false; size_t at = 0; while (at < text.size()) { size_t end = text.find('\n', at); @@ -91,19 +134,43 @@ inline char ParseSelection(const std::string& text) { for (size_t i = at; i < end; ++i) if (!std::isspace(static_cast(text[i]))) line += char(std::tolower(static_cast(text[i]))); at = end + 1; - if (line.rfind("selection=", 0) != 0) continue; - const std::string v = line.substr(10); - if (v == "amd") return kModelAmd; - if (v == "wronggpu-k") return LabelOf(kModelK) ? kModelK : kModelM; - return kDefaultModel; + if (!stated && line.rfind("selection=", 0) == 0) { + stated = true; + const std::string v = line.substr(10); + if (v == "amd") s.model = kModelAmd; + else if (v == "wronggpu-k" && LabelOf(kModelK)) s.model = kModelK; + else if (v == "wronggpu-l" && LabelOf(kModelL)) s.model = kModelL; + else if (v == "wronggpu") s.model = kModelM; + else stated = false; // an unknown entry, or one this build lacks: the default + } else if (line.rfind("chosen=", 0) == 0) { + const std::string v = line.substr(7); + uint64_t t = 0; + bool digits = !v.empty() && v.size() <= 19; + for (char c : v) digits = digits && c >= '0' && c <= '9'; + if (digits) t = std::strtoull(v.c_str(), nullptr, 10); + s.chosenAt = t; + } } - return kDefaultModel; + if (!stated) return Selection{}; + s.explicitChoice = s.model != kDefaultModel || s.chosenAt != 0; + return s; +} + +// The model alone (the earlier interface). +inline char ParseSelection(const std::string& text) { return ParseSelectionFile(text).model; } + +inline const char* SelectionValue(char model) { + return model == kModelAmd ? "amd" : model == kModelK ? "wronggpu-k" : model == kModelL ? "wronggpu-l" : "wronggpu"; } -inline std::string FormatSelection(char model) { - const char* v = model == kModelAmd ? "amd" : model == kModelK ? "wronggpu-k" : "wronggpu"; - return std::string("; WrongGPU OptiScaler plugin: the entry last selected in OptiScaler's upscaler list\r\n") + - "; (wronggpu or amd). Deleting this file selects WrongGPU.\r\nselection=" + v + "\r\n"; +// `chosenAt` 0 writes no time (the default entry's file, as installers write it). +inline std::string FormatSelection(char model, uint64_t chosenAt = 0) { + std::string text = std::string("; WrongGPU OptiScaler plugin: the entry last selected in OptiScaler's upscaler list\r\n") + + "; (wronggpu, wronggpu-k, wronggpu-l or amd) and when (chosen: seconds since 1970 UTC).\r\n" + "; Deleting this file selects WrongGPU's default; the launcher's model choice then decides.\r\n" + "selection=" + SelectionValue(model) + "\r\n"; + if (chosenAt) text += "chosen=" + std::to_string(chosenAt) + "\r\n"; + return text; } } // namespace wgasi diff --git a/clean/fsr/asi/exports_asi.def b/clean/fsr/asi/exports_asi.def index 52127332..315f0654 100644 --- a/clean/fsr/asi/exports_asi.def +++ b/clean/fsr/asi/exports_asi.def @@ -4,3 +4,5 @@ EXPORTS InitializeASI WrongGpuAsiQuery WrongGpuAsiQueryStatusV1 + WrongGpuAsiQueryChoiceV1 + WrongGpuAsiShowModelV1 diff --git a/clean/fsr/asi/wronggpu_asi.cpp b/clean/fsr/asi/wronggpu_asi.cpp index 9adb88e2..d9a79241 100644 --- a/clean/fsr/asi/wronggpu_asi.cpp +++ b/clean/fsr/asi/wronggpu_asi.cpp @@ -1,8 +1,9 @@ // SPDX-License-Identifier: MIT // WrongGPU.asi: an OptiScaler plugin (its own DLL, our own code only) that makes WrongGPU appear as its own entry -// ("WrongGPU"; with Model K: "WrongGPU Model M", "WrongGPU Model K") in OptiScaler's MAIN DX12 upscaler dropdown, -// leaving OptiScaler's "FSR 3.X(/4)" entry to mean AMD's upscaler again. WrongGPU is the default entry; the player's -// choice is remembered in wronggpu-asi.ini next to the plugin. +// ("WrongGPU"; with Model K and/or L: "WrongGPU Model M", "WrongGPU Model K", "WrongGPU Model L") in OptiScaler's MAIN +// DX12 upscaler dropdown, leaving OptiScaler's "FSR 3.X(/4)" entry to mean AMD's upscaler again. WrongGPU is the default +// entry; the player's choice (and when it was made) is remembered in wronggpu-asi.ini next to the plugin. The front end +// weighs it against the launcher's model choice (src/model_precedence.h) and reports back the model it runs. // // How: OptiScaler calls our exported InitializeASI() after loading us (see its LoadAsiPlugins). The module that // called us is OptiScaler itself (its image holds the menu code), so we identify it by InitializeASI's return @@ -68,21 +69,30 @@ bool PinOwnModule() noexcept { // The remembered choice: wronggpu-asi.ini in PluginDataDir() (asi_thunk.h, ParseSelection / FormatSelection). std::wstring SelectionPath() { return wgasi::PluginDataDir() + L"wronggpu-asi.ini"; } -char LoadSelection() { +wgasi::Selection LoadSelection() { std::string text; HANDLE h = CreateFileW(SelectionPath().c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (h != INVALID_HANDLE_VALUE) { - char buf[512]; + char buf[1024]; DWORD got = 0; if (ReadFile(h, buf, sizeof buf, &got, nullptr)) text.assign(buf, got); CloseHandle(h); } - return wgasi::ParseSelection(text); + return wgasi::ParseSelectionFile(text); } -void SaveSelection(char model) { - const std::string text = wgasi::FormatSelection(model); +// Seconds since 1970-01-01 UTC (the launcher stamps its model choice on the same clock). +uint64_t NowUnixSeconds() { + FILETIME ft; + GetSystemTimeAsFileTime(&ft); + const uint64_t t = (uint64_t(ft.dwHighDateTime) << 32) | ft.dwLowDateTime; // 100 ns since 1601 + const uint64_t epoch = 116444736000000000ull; // 1970-01-01 in that unit + return t > epoch ? (t - epoch) / 10000000ull : 0; +} + +void SaveSelection(char model, uint64_t chosenAt) { + const std::string text = wgasi::FormatSelection(model, chosenAt); HANDLE h = CreateFileW(SelectionPath().c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (h == INVALID_HANDLE_VALUE) return; @@ -92,14 +102,16 @@ void SaveSelection(char model) { } extern "C" bool WgSelectableThunk(const char* label, bool selected, int flags, const void* size) { - const char before = g_state.model.load(); + bool ours = false; const bool clicked = wgasi::SelectableThunkLogic( [](const char* l, bool s, int f, const void* z) { return g_realSelectable(l, s, f, z); }, - label, selected, flags, size, g_state); - const char after = g_state.model.load(); - if (after != before) { // a click on another entry of the FSR 3.X group: remember it (rare; on the menu thread) - SaveSelection(after); - AsiLog::Get().Writef("selected: %s", after == wgasi::kModelAmd ? label : wgasi::LabelOf(after)); + label, selected, flags, size, g_state, NowUnixSeconds(), &ours); + if (ours) { // a click on an entry of the FSR 3.X group: the player's explicit choice, with its time (rare; menu thread) + const char after = g_state.model.load(); + const uint64_t at = g_state.chosenAt.load(); + SaveSelection(after, at); + AsiLog::Get().Writef("selected: %s (chosen=%llu)", after == wgasi::kModelAmd ? label : wgasi::LabelOf(after), + static_cast(at)); } return clicked; } @@ -222,7 +234,16 @@ void Hook(const void* caller) { g_realBeginCombo = r.beginCombo ? reinterpret_cast(const_cast(optiBase) + r.beginCombo) : nullptr; // Selection I/O and all allocations happen before any call site can enter our thunks. - g_state.model.store(LoadSelection()); + { + const wgasi::Selection saved = LoadSelection(); + g_state.model.store(saved.model); + g_state.explicitChoice.store(saved.explicitChoice); + g_state.chosenAt.store(saved.chosenAt); + log.Writef("saved choice: %s (%s, chosen=%llu)", + saved.model == wgasi::kModelAmd ? "AMD (FSR 3.X)" : wgasi::LabelOf(saved.model), + saved.explicitChoice ? "explicit" : "default entry: the launcher's model choice decides", + static_cast(saved.chosenAt)); + } uint8_t* stubs = AllocNear(optiBase + r.addDx12Lo); if (!stubs) { g_diagnostics.Outcome(WG_ASI_MENU_UNAVAILABLE, WG_ASI_REASON_STUB_ALLOCATION_FAILED); @@ -290,12 +311,37 @@ extern "C" __declspec(dllexport) __declspec(noinline) void InitializeASI() { }); } +// The earlier query (ABI 1): an older front end knows 0, 'M' and 'K' only, so Model L reads as Model M there. extern "C" __declspec(dllexport) int WrongGpuAsiQuery(int* hooked, char* model) { if (hooked) *hooked = g_state.hooked.load() ? 1 : 0; - if (model) *model = g_state.model.load(); + if (model) { + const char m = g_state.model.load(); + *model = m == wgasi::kModelL ? wgasi::kModelM : m; + } return int(WRONGGPU_ASI_ABI); } +extern "C" __declspec(dllexport) int WrongGpuAsiQueryChoiceV1(WrongGpuAsiChoiceV1* choice, uint32_t caller_size) { + if (!choice) return WG_ASI_STATUS_INVALID_ARGUMENT; + if (caller_size < sizeof(WrongGpuAsiChoiceV1) || choice->size < sizeof(WrongGpuAsiChoiceV1) || choice->size > caller_size) + return WG_ASI_STATUS_INVALID_SIZE; + if (choice->version != WRONGGPU_ASI_CHOICE_VERSION) return WG_ASI_STATUS_UNSUPPORTED_VERSION; + WrongGpuAsiChoiceV1 v{}; + v.size = sizeof(v); + v.version = WRONGGPU_ASI_CHOICE_VERSION; + v.hooked = g_state.hooked.load() ? 1u : 0u; + v.model = static_cast(g_state.model.load()); + v.explicit_choice = g_state.explicitChoice.load() ? 1u : 0u; + v.chosen_at = g_state.chosenAt.load(); + *choice = v; + return WG_ASI_STATUS_OK; +} + +// The front end reports the model it runs (0 AMD, 'M', 'K', 'L'), so the menu marks that one; 1 = the saved choice. +extern "C" __declspec(dllexport) void WrongGpuAsiShowModelV1(char model) { + if (model == wgasi::kShowSaved || model == wgasi::kModelAmd || wgasi::LabelOf(model)) g_state.shown.store(model); +} + extern "C" __declspec(dllexport) int WrongGpuAsiQueryStatusV1(WrongGpuAsiStatusV1* status, uint32_t caller_size) { return g_diagnostics.Query(status, caller_size, g_state.hooked.load(), g_state.model.load()); } diff --git a/clean/fsr/src/asi_bridge.cpp b/clean/fsr/src/asi_bridge.cpp index 736a533a..ce4443ed 100644 --- a/clean/fsr/src/asi_bridge.cpp +++ b/clean/fsr/src/asi_bridge.cpp @@ -11,17 +11,40 @@ namespace wgwin { -bool QueryAsiPlugin(char* model) { - if (model) *model = 0; +bool QueryAsiPlugin(wgfsr::PluginModelChoice* choice) { + if (choice) *choice = wgfsr::PluginModelChoice{}; HMODULE m = GetModuleHandleW(WRONGGPU_ASI_MODULE); // present only if OptiScaler loaded our plugin; no reference taken if (!m) return false; + if (auto query = reinterpret_cast(reinterpret_cast(GetProcAddress(m, WRONGGPU_ASI_CHOICE_QUERY)))) { + WrongGpuAsiChoiceV1 c{}; + c.size = sizeof(c); + c.version = WRONGGPU_ASI_CHOICE_VERSION; + if (query(&c, sizeof(c)) != WG_ASI_STATUS_OK) return false; + if (choice) { + choice->model = char(c.model); + choice->explicitChoice = c.explicit_choice != 0; + choice->chosenAt = c.chosen_at; + } + return c.hooked != 0; + } auto query = reinterpret_cast(reinterpret_cast(GetProcAddress(m, WRONGGPU_ASI_QUERY))); if (!query) return false; int hooked = 0; char mdl = 0; if (query(&hooked, &mdl) < int(WRONGGPU_ASI_ABI)) return false; // older/unknown ABI: ignore - if (model) *model = mdl; + if (choice) { // an earlier plugin: its default entry is Model M; any other entry was chosen, at an unknown time + choice->model = mdl; + choice->explicitChoice = mdl != 'M'; + choice->chosenAt = 0; + } return hooked != 0; } +void ShowAsiModel(char model) { + HMODULE m = GetModuleHandleW(WRONGGPU_ASI_MODULE); + if (!m) return; + if (auto show = reinterpret_cast(reinterpret_cast(GetProcAddress(m, WRONGGPU_ASI_SHOW_MODEL)))) + show(model); +} + } // namespace wgwin diff --git a/clean/fsr/src/asi_bridge.h b/clean/fsr/src/asi_bridge.h index a1e1dbff..40d5e125 100644 --- a/clean/fsr/src/asi_bridge.h +++ b/clean/fsr/src/asi_bridge.h @@ -2,10 +2,17 @@ #pragma once // Front-end side of the WrongGPU ASI plugin interface (clean/fsr/asi/asi_abi.h): find WrongGPU.asi if it is loaded // in the process and ask it which upscaler entry the player selected in OptiScaler's menu. No link to the plugin. +#include "model_precedence.h" + namespace wgwin { -// Sets *model to 0 (AMD FSR), 'M' or 'K'. Returns true only when the plugin is present and has hooked the host's -// menu (so the front end should list AMD-only versions and let the plugin choose the model). False otherwise. -bool QueryAsiPlugin(char* model); +// Fills *choice: the plugin's saved entry (0 AMD FSR, 'M', 'K', 'L'), whether the player chose it, and when +// (WrongGpuAsiQueryChoiceV1; a plugin without it: WrongGpuAsiQuery, with Model M as its default entry and K / AMD as +// explicit choices with no recorded time). Returns true only when the plugin is present and has hooked the host's +// menu (so the plugin's choice, weighed against the launcher's, decides the model). False otherwise. +bool QueryAsiPlugin(wgfsr::PluginModelChoice* choice); + +// Tells the plugin which model runs (its menu marks that entry). Nothing happens without the plugin or the export. +void ShowAsiModel(char model); } // namespace wgwin diff --git a/clean/fsr/src/config.cpp b/clean/fsr/src/config.cpp index 7574bdbe..b39c276d 100644 --- a/clean/fsr/src/config.cpp +++ b/clean/fsr/src/config.cpp @@ -345,6 +345,10 @@ Config ParseConfig(const std::string& text, std::string* warnings) { if (ok) c.splitTimeoutMs = static_cast(f); } else if (key == "runtime_options") { c.runtimeOptions = NormalizeOptions(value); + } else if (key == "model_chosen") { + // Written by the launcher with the model item (model_precedence.h): seconds since 1970 UTC. + ok = !value.empty() && value.size() <= 19 && value.find_first_not_of("0123456789") == std::string::npos; + if (ok) c.modelChosenAt = std::strtoull(value.c_str(), nullptr, 10); } else if (key == "overlay") { ok = lv == "on" || lv == "badge" || lv == "off"; if (ok) c.overlay = lv; diff --git a/clean/fsr/src/config.h b/clean/fsr/src/config.h index 54b76ce2..5645d130 100644 --- a/clean/fsr/src/config.h +++ b/clean/fsr/src/config.h @@ -79,6 +79,9 @@ struct Config { // Extra "key=value;key=value" text for the upscaler (the network runtime's own keys, e.g. timing_log=1;sync=pipelined), // appended to BackendOptions() after the front end's keys. Normalized: items trimmed, empty items dropped. std::string runtimeOptions; + // [fsr] model_chosen: when the launcher last changed the model item of runtime_options (seconds since 1970 UTC; + // 0 = not recorded). Weighed against the OptiScaler menu plugin's saved choice (model_precedence.h). + uint64_t modelChosenAt = 0; // In-game overlay (overlay.h): "on" (the full panel for 10 s after WrongGPU starts upscaling, then a one-line badge), // "badge" (the badge only), "off". overlayKey toggles it: insert, home, end, delete, pageup, pagedown, pause, diff --git a/clean/fsr/src/dllmain.cpp b/clean/fsr/src/dllmain.cpp index 0043b32d..a1b8151d 100644 --- a/clean/fsr/src/dllmain.cpp +++ b/clean/fsr/src/dllmain.cpp @@ -234,9 +234,11 @@ FrontEnd& Get() { return CompareApi(dll); }; } - // If WrongGPU.asi has hooked OptiScaler's menu, it (not an FFX version override) chooses the model, and - // WrongGPU's own versions are left out of the FFX sub-box. Absent or not hooked: hosted mode as before. - p.asiPlugin = [](char* model) { return QueryAsiPlugin(model); }; + // If WrongGPU.asi has hooked OptiScaler's menu, its saved entry weighed against the launcher's model choice + // (not an FFX version override) chooses the model (model_precedence.h). Absent or not hooked: hosted mode as + // before. + p.asiPlugin = [](wgfsr::PluginModelChoice* choice) { return QueryAsiPlugin(choice); }; + p.asiShowModel = [](char model) { ShowAsiModel(model); }; } p.menu = Menu(); g_frontEnd = new FrontEnd(p, config); diff --git a/clean/fsr/src/frontend.cpp b/clean/fsr/src/frontend.cpp index ace7a686..bfd3ebad 100644 --- a/clean/fsr/src/frontend.cpp +++ b/clean/fsr/src/frontend.cpp @@ -2,6 +2,7 @@ #include "frontend.h" #include +#include #include #include #include @@ -565,28 +566,57 @@ ffxReturnCode_t FrontEnd::CreateUpscale(ffxContext* context, ffxCreateContextDes } } - // OptiScaler ASI plugin (clean/fsr/asi): when it has hooked the host's MAIN upscaler list, its entry decides. - // "WrongGPU" -> WrongGPU, whatever the FFX sub-box names. "FSR 3.X(/4)" -> AMD: the version the FFX sub-box names - // when that is one of AMD's, else AMD's newest listed version (FSR 4 when the AMD provider has it). - char asiModel = 0; - const bool asiHooked = config_.hosted && platform_.asiPlugin && platform_.asiPlugin(&asiModel); + // OptiScaler ASI plugin (clean/fsr/asi): when it has hooked the host's MAIN upscaler list, the FFX sub-box no + // longer chooses: the plugin's saved entry and the launcher's model choice (wronggpu.ini runtime_options' model item + // with model_chosen) do, by model_precedence.h (the launcher's choice wins over the plugin's default entry; on a + // conflict the more recent explicit choice wins, with one log line). A WrongGPU model -> WrongGPU, whatever the FFX + // sub-box names. AMD ("FSR 3.X(/4)") -> AMD: the version the FFX sub-box names when that is one of AMD's, else AMD's + // newest listed version (FSR 4 when the AMD provider has it). + PluginModelChoice asiChoice; + const bool asiHooked = config_.hosted && platform_.asiPlugin && platform_.asiPlugin(&asiChoice); bool forceAmd = false; if (asiHooked) { - if (asiModel == 'M' || asiModel == 'K') { -#if WRONGGPU_MODEL_K - const char model = asiModel; -#else - const char model = 'M'; // a plugin built with Model K, with a front end without it: Model M -#endif - u->selectedModel = model; - u->modelProviderId = model == 'K' ? kWrongGpuKProviderVersionId : kWrongGpuProviderVersionId; - u->modelProviderName = model == 'K' ? "WrongGPU Model K" : "WrongGPU Model M"; + const ModelDecision decision = DecideModel(asiChoice, LauncherChoice()); + if (decision.conflict) { + bool first = false; + { + std::lock_guard lock(mutex_); + first = !modelLogged_.count(decision.line); + modelLogged_[decision.line] = true; + } + if (first) Log(tag + " " + decision.line); + } + // "selected in the host's upscaler list" (the launcher's log reader looks for it): the plugin's menu marks the + // model that runs (asiShowModel), also when the launcher's choice decided. + const std::string by = decision.winner == ModelWinner::Launcher + ? std::string(" (the launcher's model choice: wronggpu.ini runtime_options model=") + decision.model + ")" + : std::string(); + char model = decision.model; + if (model != kChoiceAmd) { + const int32_t m = ModelOfName(std::string(1, model)); + const WgEntryDef* sr = m >= 0 ? SrEntryOfModel(m) : nullptr; + if (!sr) { // a model this build of the front end lacks (CMake WG_MODEL_K / WG_MODEL_L): Model M, said once + const std::string line = "note: OptiScaler plugin: " + ChoiceName(model) + " is not part of this build of the front end; Model M is used"; + bool first = false; + { + std::lock_guard lock(mutex_); + first = !modelLogged_.count(line); + modelLogged_[line] = true; + } + if (first) Log(tag + " " + line); + model = 'M'; + sr = SrEntryOfModel(ModelOfName("M")); + } + u->selectedModel = model; // passed on as model= (CreateUpscale, below) + u->modelProviderId = sr ? sr->id : kWrongGpuProviderVersionId; + u->modelProviderName = sr ? EntryProviderName(*sr) : kWrongGpuVersionName; u->hasOverride = false; // an AMD version in the FFX sub-box must not route this context to AMD - Log(tag + " OptiScaler plugin: " + u->modelProviderName + " selected in the host's upscaler list"); + Log(tag + " OptiScaler plugin: " + u->modelProviderName + " selected in the host's upscaler list" + by); } else { forceAmd = true; - Log(tag + " OptiScaler plugin: AMD FSR selected in the host's upscaler list"); + Log(tag + " OptiScaler plugin: AMD FSR selected in the host's upscaler list" + by); } + if (platform_.asiShowModel) platform_.asiShowModel(model); } // One folder per choice (registry option entry_source = folders): this DLL's folder IS the choice; the host's @@ -1366,6 +1396,22 @@ bool FrontEnd::ConfiguredModel(int32_t* model, std::string* described) { return true; } +LauncherModelChoice FrontEnd::LauncherChoice() const { + // The launcher's choice: the last model item of wronggpu.ini's runtime_options (the launcher writes model= + // there; a build without Model K / L has already dropped those items, IgnoreModelK / IgnoreModelL) and + // model_chosen, when the launcher last changed it. WG_RUNTIME_OPTIONS is a developer's override, not a choice: it + // is checked against the decided model further on (CreateUpscale). + LauncherModelChoice c; + bool found = false; + const std::string v = OptionValue(config_.runtimeOptions, "model", &found); + if (found && v.size() == 1) { + const char m = char(std::toupper(static_cast(v[0]))); + if (m == 'M' || m == 'K' || m == 'L') c.model = m; + } + c.chosenAt = config_.modelChosenAt; + return c; +} + void FrontEnd::ApplyEntry(const WgEntryDef& e, UpscaleContext& u, const std::string& tag, const char* source) { int32_t model = e.slot == WG_OPT_SR_MODEL ? e.value : -1; std::string described; diff --git a/clean/fsr/src/frontend.h b/clean/fsr/src/frontend.h index e33a9b74..bfecb324 100644 --- a/clean/fsr/src/frontend.h +++ b/clean/fsr/src/frontend.h @@ -16,6 +16,7 @@ #include "amd_compare.h" #include "async_create.h" #include "config.h" +#include "model_precedence.h" #include "status.h" #include "ffx_headers.h" #include "param_map.h" @@ -89,9 +90,12 @@ struct Platform { std::function deviceLost; // OptiScaler ASI plugin bridge (clean/fsr/asi): when WrongGPU.asi is loaded and has hooked OptiScaler's menu, // WrongGPU is its own entry in the host's MAIN upscaler list, not a version in the FFX sub-box. Returns true when - // hooked (then the version query lists AMD only and this plugin, not an FFX override, chooses the model) and sets - // *model to 0 (AMD FSR), 'M' or 'K'. Null or returns false: no plugin / unknown host build; hosted mode as before. - std::function asiPlugin; + // hooked (then the plugin's saved choice, weighed against the launcher's model choice by model_precedence.h, not an + // FFX override, chooses the model) and fills *choice: model 0 (AMD FSR), 'M', 'K' or 'L', whether the player chose + // it, and when. Null or returns false: no plugin / unknown host build; hosted mode as before. + std::function asiPlugin; + // Tells the plugin which model the context runs (0 AMD, 'M', 'K', 'L'), so its menu marks that entry. May be empty. + std::function asiShowModel; // Registry options and the menu's choices (shared settings block). Empty members: defaults, nothing written. MenuSettings menu; }; @@ -203,6 +207,8 @@ class FrontEnd { // The configured SR model (sr_model: block > environment > ini) for a context no entry chose; false: not set // anywhere (the model then comes from runtime_options / the runtime's default, as before the registry). bool ConfiguredModel(int32_t* model, std::string* described); + // The launcher's model choice in wronggpu.ini (model_precedence.h), weighed against the OptiScaler plugin's. + LauncherModelChoice LauncherChoice() const; // AMD's DLL behind a forwarded context (the one that created it), else AMD's original. const OriginalApi* ApiOf(void* context); // `u` runs on AMD while its upscaler's create runs (u.pending): takes the upscaler over when the create has finished. diff --git a/clean/fsr/src/model_precedence.h b/clean/fsr/src/model_precedence.h new file mode 100644 index 00000000..d46d3d72 --- /dev/null +++ b/clean/fsr/src/model_precedence.h @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: MIT +#pragma once +// Which model runs when WrongGPU's OptiScaler menu plugin (clean/fsr/asi) has hooked the host's upscaler list: the +// plugin's saved choice or the launcher's (0.6.5). Plain C++, no Windows headers, so the unit tests can check it on +// any host (tests/test_model_precedence.cpp; the front end's own tests check it through CreateUpscale). +// +// The two choices: +// - the plugin's: the entry the player last clicked in OptiScaler's upscaler list (wronggpu-asi.ini: selection= and, +// since 0.6.5, chosen= with the click's time); +// - the launcher's: the last model item of wronggpu.ini's runtime_options (model=M / K / L), which the launcher +// writes, with model_chosen= (the time the launcher last changed that item; since 0.6.5). +// Times are seconds since 1970-01-01 UTC on this PC's clock; 0 means "not recorded" (files of earlier versions, +// installers, a hand-edited file). +// +// A choice is a DEFAULT when nobody chose it: on the plugin's side no file, no selection line, or Model M with no +// time (what installers seed and what earlier versions saved); on the launcher's side no model item, or model=M with +// no time (the installer's model=M). Anything else is EXPLICIT. +// +// The rule: +// 1. both default: Model M (as before); +// 2. only one explicit: that one (the launcher's choice wins over the plugin's default, and the reverse); +// 3. both explicit and the same model: that model; +// 4. both explicit and different (a CONFLICT): the more recent one, by its time; with equal times (also both not +// recorded) the plugin's, the choice the player made in the game. The front end logs one line naming both choices +// and which one won. +// AMD (the plugin's "FSR 3.X(/4)" entry, model 0) is a choice like the models. The launcher's "WrongGPU off" +// (upscaler = amd) is not a model choice: it is a master switch and still turns WrongGPU off whatever is chosen here. +#include +#include + +namespace wgfsr { + +constexpr char kChoiceAmd = 0; // AMD's FSR (the plugin's FSR 3.X entry) +constexpr char kChoiceNone = '-'; // the launcher stated no model + +struct PluginModelChoice { + char model = 'M'; // 0 (AMD), 'M', 'K', 'L' + bool explicitChoice = false; // false: the plugin's default entry + uint64_t chosenAt = 0; +}; + +struct LauncherModelChoice { + char model = kChoiceNone; // 'M', 'K', 'L' (the last model item), or kChoiceNone + uint64_t chosenAt = 0; // wronggpu.ini model_chosen + bool Explicit() const { return model != kChoiceNone && (model != 'M' || chosenAt != 0); } +}; + +enum class ModelWinner { Default, Plugin, Launcher }; + +struct ModelDecision { + char model = 'M'; + ModelWinner winner = ModelWinner::Default; + bool conflict = false; + std::string line; // the conflict line (empty without a conflict) +}; + +inline std::string ChoiceName(char model) { + if (model == kChoiceAmd) return "AMD FSR"; + if (model == kChoiceNone) return "no model"; + return std::string("Model ") + model; +} + +inline std::string ChoiceTime(uint64_t t) { return t ? "chosen=" + std::to_string(t) : "no time recorded"; } + +inline ModelDecision DecideModel(const PluginModelChoice& plugin, const LauncherModelChoice& launcher) { + ModelDecision d; + const bool p = plugin.explicitChoice, l = launcher.Explicit(); + if (!p && !l) { + d.model = launcher.model == kChoiceNone ? 'M' : launcher.model; // (an unstamped model=M: Model M) + return d; + } + if (p && !l) { + d.model = plugin.model; + d.winner = ModelWinner::Plugin; + return d; + } + if (!p && l) { + d.model = launcher.model; + d.winner = ModelWinner::Launcher; + return d; + } + if (plugin.model == launcher.model) { + d.model = plugin.model; + d.winner = ModelWinner::Plugin; + return d; + } + const bool launcherNewer = launcher.chosenAt > plugin.chosenAt; + d.conflict = true; + d.winner = launcherNewer ? ModelWinner::Launcher : ModelWinner::Plugin; + d.model = launcherNewer ? launcher.model : plugin.model; + d.line = "model choice conflict: OptiScaler menu plugin chose " + ChoiceName(plugin.model) + " (wronggpu-asi.ini, " + + ChoiceTime(plugin.chosenAt) + "), the launcher chose " + ChoiceName(launcher.model) + + " (wronggpu.ini runtime_options, model_chosen " + (launcher.chosenAt ? std::to_string(launcher.chosenAt) : "not recorded") + + "); " + (launcherNewer ? "the launcher's" : "the plugin's") + " choice wins (" + + (launcher.chosenAt == plugin.chosenAt ? "same time or none recorded: the in-game choice is kept" + : "the more recent explicit choice") + + "): " + ChoiceName(d.model) + " runs"; + return d; +} + +} // namespace wgfsr diff --git a/clean/fsr/tests/test_asi_status.cpp b/clean/fsr/tests/test_asi_status.cpp index 7bdc000a..ad787a58 100644 --- a/clean/fsr/tests/test_asi_status.cpp +++ b/clean/fsr/tests/test_asi_status.cpp @@ -117,6 +117,28 @@ int main(int argc, char** argv) { CHECK(s.selected_model == 'M' && s.rr_ready == 0); } } + // 0.6.5: the saved choice for the precedence against the launcher (asi_abi.h WrongGpuAsiQueryChoiceV1), and the + // front end's report of the model that runs (display only; never saved, never hooks anything). + auto choice = reinterpret_cast(GetProcAddress(module, WRONGGPU_ASI_CHOICE_QUERY)); + auto show = reinterpret_cast(GetProcAddress(module, WRONGGPU_ASI_SHOW_MODEL)); + CHECK(choice != nullptr && show != nullptr); + if (choice && show) { + CHECK(choice(nullptr, sizeof(WrongGpuAsiChoiceV1)) == WG_ASI_STATUS_INVALID_ARGUMENT); + WrongGpuAsiChoiceV1 c{}; + c.size = sizeof(c); + c.version = WRONGGPU_ASI_CHOICE_VERSION; + CHECK(choice(&c, sizeof(c) - 1) == WG_ASI_STATUS_INVALID_SIZE); + c.version = 99; + CHECK(choice(&c, sizeof(c)) == WG_ASI_STATUS_UNSUPPORTED_VERSION); + c.version = WRONGGPU_ASI_CHOICE_VERSION; + CHECK(choice(&c, sizeof(c)) == WG_ASI_STATUS_OK); + // never initialised: the default entry, not chosen, no time, not hooked + CHECK(c.hooked == 0 && c.model == 'M' && c.explicit_choice == 0 && c.chosen_at == 0); + show('L'); + show('Z'); // not an entry: ignored + show(1); + CHECK(choice(&c, sizeof(c)) == WG_ASI_STATUS_OK && c.model == 'M' && c.explicit_choice == 0); + } CHECK(FreeLibrary(module) != 0); // No initialization or patches ever occurred. CHECK(GetModuleHandleA(argv[1]) == nullptr); // Query-only loading did not permanently pin it. } diff --git a/clean/fsr/tests/test_asi_thunk.cpp b/clean/fsr/tests/test_asi_thunk.cpp index fdf5551f..59887e1d 100644 --- a/clean/fsr/tests/test_asi_thunk.cpp +++ b/clean/fsr/tests/test_asi_thunk.cpp @@ -6,6 +6,10 @@ #include #include +#ifdef WRONGGPU_MODEL_K_OVERRIDE // test_asi_thunk_kl: Model K on, whatever the build's WG_MODEL_K says +#undef WRONGGPU_MODEL_K +#define WRONGGPU_MODEL_K 1 +#endif #include "../asi/asi_thunk.h" using namespace wgasi; @@ -63,8 +67,13 @@ void TestDefaultIsWrongGpu() { CHECK(sel.calls.size() == kEntryCount + 1); CHECK(sel.calls[0].label == kEntries[0].label && sel.calls[0].selected); CHECK(sel.calls.back().label == "FSR 3.X" && !sel.calls.back().selected); -#if WRONGGPU_MODEL_K +#if WRONGGPU_MODEL_K && WRONGGPU_MODEL_L + CHECK(kEntryCount == 3 && sel.calls[0].label == "WrongGPU Model M" && sel.calls[1].label == "WrongGPU Model K" && + sel.calls[2].label == "WrongGPU Model L"); +#elif WRONGGPU_MODEL_K CHECK(kEntryCount == 2 && sel.calls[0].label == "WrongGPU Model M" && sel.calls[1].label == "WrongGPU Model K"); +#elif WRONGGPU_MODEL_L + CHECK(kEntryCount == 2 && sel.calls[0].label == "WrongGPU Model M" && sel.calls[1].label == "WrongGPU Model L"); #else CHECK(kEntryCount == 1 && sel.calls[0].label == "WrongGPU"); #endif @@ -150,6 +159,74 @@ void TestSelectionFile() { CHECK(ParseSelection(FormatSelection(kModelAmd)) == kModelAmd); CHECK(ParseSelection(FormatSelection(kModelM)) == kModelM); CHECK(FormatSelection(kModelM).find("selection=wronggpu\r\n") != std::string::npos); + CHECK(ParseSelection("selection=wronggpu-l") == (WRONGGPU_MODEL_L ? kModelL : kModelM)); +} + +// 0.6.5: the saved choice says whether the player chose it and when (chosen=), so the front end can weigh it against +// the launcher's model choice (src/model_precedence.h). +void TestSelectionExplicitAndTime() { + Selection s = ParseSelectionFile(""); + CHECK(s.model == kModelM && !s.explicitChoice && s.chosenAt == 0); // no file: the default entry + s = ParseSelectionFile("; c\r\nselection=wronggpu\r\n"); // what installers seed / 0.6.0 saved for M + CHECK(s.model == kModelM && !s.explicitChoice && s.chosenAt == 0); + s = ParseSelectionFile("selection=wronggpu\r\nchosen=1763150000\r\n"); // a click on Model M, with its time + CHECK(s.model == kModelM && s.explicitChoice && s.chosenAt == 1763150000ull); + s = ParseSelectionFile("chosen=77\r\nselection=amd\r\n"); // order does not matter + CHECK(s.model == kModelAmd && s.explicitChoice && s.chosenAt == 77); + s = ParseSelectionFile("selection=amd\r\n"); // an earlier version's AMD: explicit, no time + CHECK(s.model == kModelAmd && s.explicitChoice && s.chosenAt == 0); + s = ParseSelectionFile("selection=wronggpu\r\nchosen=soon\r\n"); // a bad time: not recorded + CHECK(s.model == kModelM && !s.explicitChoice && s.chosenAt == 0); + s = ParseSelectionFile("selection=garbage\r\nchosen=5\r\n"); // an unknown entry: the default, whatever the time + CHECK(s.model == kModelM && !s.explicitChoice && s.chosenAt == 0); + s = ParseSelectionFile("selection=wronggpu-k\r\n"); + CHECK(WRONGGPU_MODEL_K ? (s.model == kModelK && s.explicitChoice) : (s.model == kModelM && !s.explicitChoice)); + s = ParseSelectionFile("selection=wronggpu-l\r\nchosen=9\r\n"); // Model L; in a build without it, the default + CHECK(WRONGGPU_MODEL_L ? (s.model == kModelL && s.explicitChoice && s.chosenAt == 9) : (s.model == kModelM && !s.explicitChoice)); + // round trip of every entry with and without a time + for (const Entry& e : kEntries) { + const Selection t = ParseSelectionFile(FormatSelection(e.model, 1234)); + CHECK(t.model == e.model && t.explicitChoice && t.chosenAt == 1234); + const Selection u = ParseSelectionFile(FormatSelection(e.model)); + CHECK(u.model == e.model && u.chosenAt == 0 && u.explicitChoice == (e.model != kModelM)); + } + CHECK(FormatSelection(kModelL, 5).find("selection=wronggpu-l\r\nchosen=5\r\n") != std::string::npos); + CHECK(FormatSelection(kModelM).find("chosen=") == std::string::npos); +} + +// A click records an explicit choice with its time and reports it; the menu marks the model the front end reported +// (ShownModel) until the next click. +void TestClickRecordsTimeAndShownModel() { + PluginState st; + FakeSelectable none; + bool clicked = true; + const int size = 0; + SelectableThunkLogic(none, "FSR 3.X", true, 0, &size, st, 100, &clicked); + CHECK(!clicked && !st.explicitChoice.load() && st.chosenAt.load() == 0); // drawing alone records nothing + // the front end reports that another model runs (the launcher's choice won over the plugin's default) + st.shown.store(kEntries[kEntryCount - 1].model); + FakeSelectable marks; + SelectableThunkLogic(marks, "FSR 3.X", true, 0, &size, st); + for (size_t i = 0; i < kEntryCount; ++i) CHECK(marks.calls[i].selected == (i == kEntryCount - 1)); + FakeBeginCombo bc; + BeginComboThunkLogic(bc, "", "FSR 3.X", 0, st); + CHECK(bc.preview == kEntries[kEntryCount - 1].label); + // the player clicks Model M: explicit, timed, and marked again + FakeSelectable click; + click.clickLabel = kEntries[0].label; + CHECK(SelectableThunkLogic(click, "FSR 3.X", true, 0, &size, st, 1763150000ull, &clicked)); + CHECK(clicked && st.model.load() == kModelM && st.explicitChoice.load() && st.chosenAt.load() == 1763150000ull); + CHECK(st.shown.load() == kShowSaved && ShownModel(st) == kModelM); + // a click on the entry already saved is still an explicit choice with a new time + FakeSelectable again; + again.clickLabel = kEntries[0].label; + CHECK(SelectableThunkLogic(again, "FSR 3.X", true, 0, &size, st, 1763150500ull, &clicked) && clicked); + CHECK(st.chosenAt.load() == 1763150500ull); +#if WRONGGPU_MODEL_L + FakeSelectable l; + l.clickLabel = "WrongGPU Model L"; + CHECK(SelectableThunkLogic(l, "FSR 3.X", true, 0, &size, st, 1763151000ull, &clicked) && clicked && st.model.load() == kModelL); +#endif } } // namespace @@ -163,6 +240,8 @@ int main() { TestClickAmd(); TestPreviewRelabel(); TestSelectionFile(); + TestSelectionExplicitAndTime(); + TestClickRecordsTimeAndShownModel(); std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } diff --git a/clean/fsr/tests/test_frontend.cpp b/clean/fsr/tests/test_frontend.cpp index 3bff71db..0b2c4367 100644 --- a/clean/fsr/tests/test_frontend.cpp +++ b/clean/fsr/tests/test_frontend.cpp @@ -233,10 +233,13 @@ static bool g_compare = false; // Platform::compareAmd static std::vector g_statuses; // Platform::status static std::vector> g_timed; // Platform::gpuTimer -// Fake WrongGPU.asi bridge (clean/fsr/asi): g_asiHooked/g_asiModel stand in for the plugin's WrongGpuAsiQuery. +// Fake WrongGPU.asi bridge (clean/fsr/asi): g_asiHooked/g_asiModel/... stand in for the plugin's WrongGpuAsiQueryChoiceV1. static bool g_asiPresent = false; // the plugin bridge is wired at all static bool g_asiHooked = false; // and it reports a successful hook -static char g_asiModel = 0; // 0 (AMD), 'M', 'K' +static char g_asiModel = 0; // 0 (AMD), 'M', 'K', 'L' +static int g_asiExplicit = -1; // -1: as an earlier plugin reports it (Model M = default entry, others explicit); 0/1 +static uint64_t g_asiChosenAt = 0; // when the player clicked it (0 = not recorded) +static std::vector g_asiShown; // Platform::asiShowModel calls // Fake shared settings (Platform::menu, settings_bridge.h in the DLL): values set "somewhere" (block / env / ini), // the writes of the menu's choices, whether this module is the writer, the folder sidecar's entry. @@ -277,8 +280,17 @@ static std::unique_ptr MakeFrontEnd(const Config& config) { p.menu.folderEntry = g_folderEntry; } p.original = []() -> const OriginalApi* { return g_originalAvailable ? g_originalApi : nullptr; }; - if (g_asiPresent) - p.asiPlugin = [](char* model) { if (model) *model = g_asiModel; return g_asiHooked; }; + if (g_asiPresent) { + p.asiPlugin = [](PluginModelChoice* c) { + if (c) { + c->model = g_asiModel; + c->explicitChoice = g_asiExplicit < 0 ? g_asiModel != 'M' : g_asiExplicit != 0; + c->chosenAt = g_asiChosenAt; + } + return g_asiHooked; + }; + p.asiShowModel = [](char model) { g_asiShown.push_back(model); }; + } p.compareApi = []() -> const OriginalApi* { return g_compareApi; }; p.backend = [](const Config&, std::string&) -> const WgUpscalerBackend* { return g_useBackend; }; p.services = [](const WgUpscalerBackend* b, void* device) -> const WgFrontEndServices* { @@ -371,6 +383,9 @@ static void Reset() { g_asiPresent = false; g_asiHooked = false; g_asiModel = 0; + g_asiExplicit = -1; + g_asiChosenAt = 0; + g_asiShown.clear(); g_createInfo = WgCreateInfo{}; g_compare = false; g_statuses.clear(); @@ -2555,13 +2570,22 @@ static void TestAsiPluginNotHooked() { // The installer's Preset K with the plugin hooked (0.5.0): wronggpu.ini says runtime_options = model=K, OptiScaler.ini // UpscalerIndex=1, and the installer seeds the plugin's wronggpu-asi.ini with selection=wronggpu-k, so the plugin -// reports 'K' and the context runs Model K. The plugin's entry decides over the ini: without that seed its default -// entry (Model M) would run, and a later choice of Model M in OptiScaler's list runs Model M. +// reports 'K' and the context runs Model K. Since 0.6.5 the plugin's default entry (Model M with no time) no longer +// decides over the launcher's model=K (the 0.6.5 audit: the plugin's default hid the launcher's choice); a later choice +// of Model M in OptiScaler's list (a click with its time) still runs Model M, with the conflict line. static void TestAsiPluginPresetK() { #if WRONGGPU_MODEL_K const bool present = g_asiPresent, hooked = g_asiHooked; const char saved = g_asiModel; - for (char plugin : {'K', 'M'}) { + struct Case { + char plugin; + int explicitChoice; + uint64_t at; + char runs; + bool conflict; + }; + for (const Case& k : {Case{'K', -1, 0, 'K', false}, Case{'M', 1, 1000, 'M', true}, Case{'M', 0, 0, 'K', false}}) { + const char plugin = k.runs; // the model expected to run Reset(); g_resources[kOutput] = {dxgi::R16G16B16A16_FLOAT, 2560, 1440}; std::string warnings; @@ -2571,7 +2595,9 @@ static void TestAsiPluginPresetK() { c.upscaler = UpscalerChoice::Network; g_asiPresent = true; g_asiHooked = true; - g_asiModel = plugin; + g_asiModel = k.plugin; + g_asiExplicit = k.explicitChoice; + g_asiChosenAt = k.at; auto fe = MakeFrontEnd(c); UpscaleCreate create(FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE, true); create.version.versionId = kWrongGpuKProviderVersionId; // the FFX sub-box at UpscalerIndex=1 @@ -2588,6 +2614,8 @@ static void TestAsiPluginPresetK() { const std::string options = g_createInfo.options ? g_createInfo.options : ""; CHECK(options.size() >= 7 && options.compare(options.size() - 7, 7, std::string("model=") + plugin) == 0); CHECK(CountLog((std::string("OptiScaler plugin: ") + expected + " selected").c_str()) == 1); + CHECK(CountLog("model choice conflict") == (k.conflict ? 1u : 0u)); + CHECK(g_asiShown.size() == 1 && g_asiShown[0] == k.runs); CHECK(fe->DestroyContext(&ctx, kMemCb) == FFX_API_RETURN_OK); } g_asiPresent = present; @@ -2596,6 +2624,180 @@ static void TestAsiPluginPresetK() { #endif } +// 0.6.5 audit (the A8 blocker): with the plugin hooked, the launcher's model choice (wronggpu.ini runtime_options' +// model item, with model_chosen) decides over the plugin's default entry; on a conflict between two explicit choices +// the more recent one runs and one line names both (model_precedence.h). Every case goes through CreateUpscale with a +// hosted create, and checks the provider the context reports, the runtime option passed on, and the log. +struct AsiRun { + std::string provider; // QUERY_GET_PROVIDER_VERSION's name, "" when the context went to AMD + std::string options; // the runtime's create options ("" when nothing was created) + bool amd = false; // AMD's FSR was asked to create a context + int runtimeCreates = 0; // creates the runtime saw +}; +static AsiRun RunAsi(const char* ini, char plugin, int explicitChoice, uint64_t at, std::vector modelFiles = {}, + bool lookup = false) { + Reset(); + g_resources[kOutput] = {dxgi::R16G16B16A16_FLOAT, 2560, 1440}; + std::string warnings; + Config c = ParseConfig(ini, &warnings); + CHECK(warnings.empty()); + c.hosted = true; + c.upscaler = UpscalerChoice::Network; + c.contextParkMs = 0; + g_asiPresent = true; + g_asiHooked = true; + g_asiModel = plugin; + g_asiExplicit = explicitChoice; + g_asiChosenAt = at; + if (lookup) { + g_modelOn = true; + g_modelPlaces = {{"G:\\game\\WrongGPU\\model", "the game's data folder", false}}; + g_modelFiles = modelFiles; + } + auto fe = MakeFrontEnd(c); + AsiRun r; + const size_t amd = g_amd.size(); + const int creates = g_createCalls; + g_createOptions.clear(); + UpscaleCreate create(FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE, true); + create.version.versionId = kWrongGpuProviderVersionId; // the FFX sub-box names Model M: it does not decide here + ffxContext ctx = nullptr; + CHECK(fe->CreateContext(&ctx, &create.upscale.header, kMemCb) == FFX_API_RETURN_OK && ctx); + r.amd = g_amd.size() > amd; + r.runtimeCreates = g_createCalls - creates; + r.options = g_createOptions; + if (fe->OwnContextCount() == 1 && !r.amd) { + ffxQueryGetProviderVersion q{}; + q.header.type = FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION; + if (fe->Query(&ctx, &q.header) == FFX_API_RETURN_OK && q.versionName) r.provider = q.versionName; + } + CHECK(fe->DestroyContext(&ctx, kMemCb) == FFX_API_RETURN_OK); + return r; +} + +static bool EndsWith(const std::string& s, const std::string& tail) { + return s.size() >= tail.size() && s.compare(s.size() - tail.size(), tail.size(), tail) == 0; +} + +static void TestAsiLauncherPrecedence() { + const bool present = g_asiPresent, hooked = g_asiHooked; + const char saved = g_asiModel; + // The pure rule (model_precedence.h), independent of which models this build has. + { + PluginModelChoice pd; // the plugin's default entry + LauncherModelChoice none, l{'L', 2000}, k{'K', 0}, m0{'M', 0}, m{'M', 3000}; + CHECK(DecideModel(pd, none).model == 'M' && DecideModel(pd, none).winner == ModelWinner::Default); + CHECK(DecideModel(pd, m0).model == 'M' && DecideModel(pd, m0).winner == ModelWinner::Default); + CHECK(DecideModel(pd, l).model == 'L' && DecideModel(pd, l).winner == ModelWinner::Launcher && !DecideModel(pd, l).conflict); + CHECK(DecideModel(pd, k).model == 'K' && DecideModel(pd, k).winner == ModelWinner::Launcher); // unstamped K: explicit + PluginModelChoice pk{'K', true, 1000}, pkNew{'K', true, 5000}, pkOld{'K', true, 0}, pa{kChoiceAmd, true, 1000}; + ModelDecision d = DecideModel(pk, l); // explicit K older than the launcher's L + CHECK(d.model == 'L' && d.winner == ModelWinner::Launcher && d.conflict); + CHECK(d.line.find("OptiScaler menu plugin chose Model K") != std::string::npos && + d.line.find("the launcher chose Model L") != std::string::npos && + d.line.find("the launcher's choice wins (the more recent explicit choice): Model L runs") != std::string::npos); + d = DecideModel(pkNew, l); // explicit K newer than the launcher's L + CHECK(d.model == 'K' && d.winner == ModelWinner::Plugin && d.conflict && + d.line.find("the plugin's choice wins (the more recent explicit choice): Model K runs") != std::string::npos); + d = DecideModel(pkOld, LauncherModelChoice{'L', 0}); // neither recorded a time: the in-game choice is kept + CHECK(d.model == 'K' && d.conflict && d.line.find("same time or none recorded") != std::string::npos); + d = DecideModel(pkOld, l); // an earlier version's K (no time) against a timed launcher L: the launcher's + CHECK(d.model == 'L' && d.conflict); + d = DecideModel(pa, l); + CHECK(d.model == 'L' && d.conflict && d.line.find("chose AMD FSR") != std::string::npos); + d = DecideModel(pa, m); // the launcher went back to Model M after the player chose AMD in the game + CHECK(d.model == 'M' && d.winner == ModelWinner::Launcher && d.conflict); + d = DecideModel(pk, LauncherModelChoice{'K', 9000}); // the same model: no conflict + CHECK(d.model == 'K' && !d.conflict && d.line.empty()); + CHECK(DecideModel(pa, none).model == kChoiceAmd && DecideModel(pa, m0).model == kChoiceAmd); + } + // Config: model_chosen is read; a bad value is said and ignored. + { + std::string w; + CHECK(ParseConfig("[fsr]\nruntime_options = model=L\nmodel_chosen = 1763150000\n", &w).modelChosenAt == 1763150000ull && w.empty()); + CHECK(ParseConfig("[fsr]\nmodel_chosen = soon\n", &w).modelChosenAt == 0 && w.find("bad value") != std::string::npos); + } + AsiRun r; +#if WRONGGPU_MODEL_L + // (a) the plugin's default entry + the launcher's Model L -> Model L, no conflict line (the audit's case: before this + // fix Model M ran and read Model M's file). + r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", 'M', 0, 0); + CHECK(r.provider == "WrongGPU Model L" && EndsWith(r.options, "model=L") && !r.amd); + CHECK(CountLog("OptiScaler plugin: WrongGPU Model L selected in the host's upscaler list (the launcher's model choice") == 1); + CHECK(CountLog("model choice conflict") == 0 && g_asiShown.size() == 1 && g_asiShown[0] == 'L'); + // ... also with no time on the launcher's model=L (a hand-edited file): the plugin's default never decides over it + r = RunAsi("[fsr]\nruntime_options = model=L\n", 'M', -1, 0); + CHECK(r.provider == "WrongGPU Model L" && EndsWith(r.options, "model=L")); + // (c) an explicit plugin choice older than the launcher's Model L -> Model L, with the conflict line once + r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", kChoiceAmd, 1, 1000); + CHECK(r.provider == "WrongGPU Model L" && EndsWith(r.options, "model=L") && !r.amd); + CHECK(CountLog("model choice conflict: OptiScaler menu plugin chose AMD FSR (wronggpu-asi.ini, chosen=1000), the launcher " + "chose Model L (wronggpu.ini runtime_options, model_chosen 2000); the launcher's choice wins") == 1); + // (d) an explicit plugin choice newer than the launcher's -> the plugin's, with the conflict line + r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", 'M', 1, 3000); + CHECK(r.provider == "WrongGPU Model M" && EndsWith(r.options, "model=M")); + CHECK(CountLog("model choice conflict") == 1 && CountLog("the plugin's choice wins (the more recent explicit choice): Model M runs") == 1); + r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", kChoiceAmd, 1, 3000); // ... AMD, newer + CHECK(r.amd && r.provider.empty() && r.runtimeCreates == 0 && + CountLog("OptiScaler plugin: AMD FSR selected in the host's upscaler list") == 1); + CHECK(g_asiShown.size() == 1 && g_asiShown[0] == kChoiceAmd); + // the plugin's own Model L entry (explicit) with the launcher at its default + r = RunAsi("[fsr]\nruntime_options = model=M\n", 'L', 1, 500); + CHECK(r.provider == "WrongGPU Model L" && EndsWith(r.options, "model=L") && CountLog("model choice conflict") == 0); + // (e) Model L chosen (by the launcher, over the plugin's default) and Model L's file missing: the existing refusal -- + // the create is refused with its reason, the runtime is not asked, AMD's FSR upscales (fallback_to_amd); no silent + // switch to Model M or its file. + r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", 'M', 0, 0, + {"G:\\game\\WrongGPU\\model\\model.wgcm", "G:\\game\\WrongGPU\\model\\K\\model.wgcm"}, true); + CHECK(r.runtimeCreates == 0 && r.amd); + CHECK(CountLog("Model L is chosen but no converted Model L was found") >= 1 && CountLog("model: no converted Model L found") == 1); + r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", 'M', 0, 0, {"G:\\game\\WrongGPU\\model\\L\\model.wgcm"}, true); + CHECK(r.runtimeCreates == 1 && !r.amd && r.provider == "WrongGPU Model L" && + r.options.find(";model_dir=G:\\game\\WrongGPU\\model") != std::string::npos); +#else + // A front end without Model L: the launcher's model=L is refused at start-up (IgnoreModelL, its own note), so no + // launcher choice is left: Model M. A plugin built with Model L whose saved entry is Model L, with this front end: + // Model M, said once. + r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", 'M', 0, 0); + CHECK(r.provider == "WrongGPU Model M" && EndsWith(r.options, "model=M")); + CHECK(CountLog("is refused: Model L is not part of this build of the front end") == 1); + r = RunAsi("[fsr]\nruntime_options = model=M\n", 'L', 1, 500); + CHECK(r.provider == "WrongGPU Model M" && EndsWith(r.options, "model=M")); + CHECK(CountLog("note: OptiScaler plugin: Model L is not part of this build of the front end; Model M is used") == 1); +#endif +#if WRONGGPU_MODEL_K + // (b) the plugin unset (no file: its default entry) + the launcher's Model K -> Model K + r = RunAsi("[fsr]\nruntime_options = model=K\nmodel_chosen = 2000\n", 'M', 0, 0); + CHECK(r.provider == "WrongGPU Model K" && EndsWith(r.options, "model=K") && CountLog("model choice conflict") == 0); +#if WRONGGPU_MODEL_L + // explicit K older than the launcher's L -> L; explicit K newer -> K (both with the conflict line) + r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", 'K', 1, 1000); + CHECK(r.provider == "WrongGPU Model L" && EndsWith(r.options, "model=L") && CountLog("model choice conflict") == 1); + r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", 'K', 1, 3000); + CHECK(r.provider == "WrongGPU Model K" && EndsWith(r.options, "model=K") && CountLog("model choice conflict") == 1); + // the launcher's K newer than the plugin's L + r = RunAsi("[fsr]\nruntime_options = model=K\nmodel_chosen = 4000\n", 'L', 1, 3000); + CHECK(r.provider == "WrongGPU Model K" && CountLog("the launcher's choice wins (the more recent explicit choice): Model K runs") == 1); +#endif +#else + // A front end without Model K: the launcher's model=K is dropped at start-up (IgnoreModelK, its own note): Model M. + // A saved Model K of the plugin: Model M, said once. + r = RunAsi("[fsr]\nruntime_options = model=K\nmodel_chosen = 2000\n", 'M', 0, 0); + CHECK(r.provider == "WrongGPU Model M" && EndsWith(r.options, "model=M")); + CHECK(CountLog("is ignored: Model K is not part of this build") == 1); + r = RunAsi("[fsr]\nruntime_options = model=M\n", 'K', 1, 500); + CHECK(r.provider == "WrongGPU Model M" && EndsWith(r.options, "model=M")); + CHECK(CountLog("note: OptiScaler plugin: Model K is not part of this build of the front end; Model M is used") == 1); +#endif + // No model item at all and the plugin's default: Model M as before, no conflict, nothing extra in the log. + r = RunAsi("[fsr]\nruntime_options = timing_log=1\n", 'M', -1, 0); + CHECK(r.provider == "WrongGPU Model M" && EndsWith(r.options, "model=M") && CountLog("model choice conflict") == 0); + CHECK(CountLog("OptiScaler plugin: WrongGPU Model M selected in the host's upscaler list") == 1 && CountLog("launcher's model choice") == 0); + g_asiPresent = present; + g_asiHooked = hooked; + g_asiModel = saved; +} + // i15: WrongGPU's version-list entries come from the registry (clean/wgshared). i20 (owner 2026-10-31): only the SR // models; the RR modes are a box of their own in the RR plugin's menu tab. An entry sets the context's model and // writes sr_model; one folder per choice lists its one entry and applies it without an override; a module that is not @@ -3443,6 +3645,7 @@ int main() { TestAsiPluginHooked(); TestAsiPluginNotHooked(); TestAsiPluginPresetK(); + TestAsiLauncherPrecedence(); { Config profile; const auto original = profile.BackendOptions(); diff --git a/clean/installer/src/wg_core/profile.cpp b/clean/installer/src/wg_core/profile.cpp index 2a05199a..57fe6c12 100644 --- a/clean/installer/src/wg_core/profile.cpp +++ b/clean/installer/src/wg_core/profile.cpp @@ -4,6 +4,7 @@ #include #include +#include #include "record.h" #include "settings.h" @@ -273,7 +274,7 @@ std::map EffectiveSettings(const string& wronggpuIni, const stri return eff; } -bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* why) { +bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* why, uint64_t now) { for (auto& d : kSettings) { if (!ValidateSetting(d, p.get(d.key), nullptr, why)) return false; } @@ -319,6 +320,15 @@ bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* const string joined = JoinOptions(items); // the line is rewritten only when its items change (a player's spacing and comment stay otherwise) if (hadOptions ? joined != JoinOptions(SplitOptions(options)) : !joined.empty()) text = IniSet(text, hadOptions ? section : "fsr", "runtime_options", joined); + // the model choice's time (profile.h): written when the model the front end runs changes, for any model letter + auto lastModel = [](const string& opts) { + string m; + for (auto& kv : SplitOptions(opts)) if (LowerA(kv.first) == "model") m = LowerA(TrimA(kv.second)); + return m; + }; + const string modelBefore = hadOptions ? lastModel(options) : string(), modelAfter = lastModel(joined); + if (modelAfter != modelBefore && !modelAfter.empty()) + text = IniSet(text, hadOptions ? section : "fsr", "model_chosen", std::to_string(now ? now : uint64_t(std::time(nullptr)))); out = text; return true; } diff --git a/clean/installer/src/wg_core/profile.h b/clean/installer/src/wg_core/profile.h index 61a1bf82..01e8d46e 100644 --- a/clean/installer/src/wg_core/profile.h +++ b/clean/installer/src/wg_core/profile.h @@ -71,7 +71,11 @@ std::map EffectiveSettings(const string& wronggpuIni, const stri // runtime items removed from runtime_options (and their own lines) and the non-default ones appended in a fixed // order; unmanaged items and every other line stay as they are. OptiScaler keys only where the key already exists. // false with *why when a profile value does not validate (nothing is rendered then). -bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* why); +// When the rendering changes the last model item of runtime_options (the model the front end runs), it also writes +// model_chosen = `now` (seconds since 1970 UTC; 0: the current time) in that section: the time of the launcher's model +// choice, which the front end weighs against the OptiScaler menu plugin's saved choice (clean/fsr/src/model_precedence.h: +// the more recent explicit choice wins). An unchanged model item leaves model_chosen as it is. +bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* why, uint64_t now = 0); bool RenderOptiIni(const Profile& p, const string& in, string& out, std::vector* notes = nullptr); // The profile a 0.5.x install implies: the effective values of its wronggpu.ini and OptiScaler.ini (defaults and the // stale defaults of earlier versions dropped; upscaler=standin counts as on). Only keys of the settings schema diff --git a/clean/installer/tests/model_choice_tests.cpp b/clean/installer/tests/model_choice_tests.cpp index 612a32cd..bc6a72d7 100644 --- a/clean/installer/tests/model_choice_tests.cpp +++ b/clean/installer/tests/model_choice_tests.cpp @@ -22,10 +22,10 @@ Profile With(const char* model) { if (!SetSetting(p, "model", model, &why)) throw std::runtime_error("test setup: model"); return p; } -string Wini(const Profile& p, const string& in) { +string Wini(const Profile& p, const string& in, uint64_t now = 0) { string out; wstring why; - if (!RenderWronggpuIni(p, in, out, &why)) throw std::runtime_error("test setup: render"); + if (!RenderWronggpuIni(p, in, out, &why, now)) throw std::runtime_error("test setup: render"); return out; } string Oini(const Profile& p, const string& in, std::vector* notes = nullptr) { @@ -71,6 +71,26 @@ int main() { "the file's model: L from its last model item, M otherwise"); require(EffectiveSettings("[fsr]\r\nruntime_options = model=L;model=M\r\n", "")["model"] == "m", "the file's model: the last model item counts"); + // ---- wronggpu.ini model_chosen: the time of the launcher's model choice (0.6.5; the front end weighs it against + // the OptiScaler menu plugin's saved choice, clean/fsr/src/model_precedence.h) -------------------------------------- + require(Wini(DefaultProfile(), fresh, 1000) == fresh, "Model M on the installer's file: no model_chosen (nothing changed, byte for byte)"); + const string toLt = Wini(With("l"), fresh, 1000); + require(toLt.find("model_chosen=1000\r\n") != string::npos && toLt.find("runtime_options=model=L") != string::npos, + "Model L chosen: model_chosen = the time of the change, next to runtime_options"); + require(Wini(With("l"), toLt, 2000) == toLt, "Model L again: model_chosen stays (the model did not change)"); + const string otherSetting = Wini([] { Profile q = With("l"); wstring w; SetSetting(q, "sparkle_guard", "on", &w); return q; }(), toLt, 3000); + require(otherSetting.find("model_chosen=1000\r\n") != string::npos && otherSetting.find("model_chosen=3000") == string::npos, + "another setting changed: model_chosen stays (only a model change is a model choice)"); + const string backMt = Wini(DefaultProfile(), toLt, 4000); + require(backMt.find("model=M") != string::npos && backMt.find("model_chosen=4000\r\n") != string::npos && backMt.find("model_chosen=1000") == string::npos, + "back to Model M: model_chosen = the time of that change (replaced, one line)"); + require(Wini(With("l"), "[fsr]\r\nruntime_options = model=K\r\n", 5000).find("model_chosen=5000") != string::npos, + "from another model's item (Model K) to Model L: stamped"); + require(Wini(DefaultProfile(), withK, 6000) == withK, "Model K's item left as it is by Model M: no model_chosen"); + require(Wini(With("l"), "[fsr]\r\nupscaler = network\r\n", 7000).find("model_chosen=7000") != string::npos, + "a file without runtime_options gets model=L and model_chosen"); + require(Wini(With("l"), fresh).find("model_chosen=") != string::npos, "now = 0: the current time is written"); + // ---- OptiScaler.ini: the entry OptiScaler starts with ----------------------------------------------------------- const string L = kModelLEntryIndex; const string slot = "[WrongGPU]\r\nUpscalerIndex=0\r\n[FSR]\r\nUpscalerIndex=0\r\n[Menu]\r\nShowFps=auto\r\n"; From acde5c1c158127daf9f7970f92faf74e8e588d2b Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:22:14 -0500 Subject: [PATCH 02/15] Model K launcher test: K then M also writes model_chosen The launcher now stamps every model change (model_chosen, profile.h), so the K-then-M rendering compares the file without that line and checks the line is there. Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/installer/tests/model_choice_k_tests.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/clean/installer/tests/model_choice_k_tests.cpp b/clean/installer/tests/model_choice_k_tests.cpp index f27a9c32..eeae276f 100644 --- a/clean/installer/tests/model_choice_k_tests.cpp +++ b/clean/installer/tests/model_choice_k_tests.cpp @@ -76,8 +76,17 @@ int main() { "Model K: every model item out (an L item too), model=K last (the last one wins); timing_log kept"); const string backM = Wini(DefaultProfile(), "[fsr]\r\nruntime_options = timing_log=1;model=K\r\n"); require(backM.find("runtime_options=timing_log=1;model=M\r\n") != string::npos, "back to Model M: Model K's item becomes model=M"); - require(Wini(DefaultProfile(), toK) == fresh.substr(0, fresh.find("runtime_options")) + "runtime_options=model=M\r\n", - "K then M: only the runtime_options line is rewritten (the installer's comment on it is gone as it is for L)"); + // (model_chosen: the time of the launcher's model choice, written on every model change, profile.h) + auto noTime = [](string s) { + const size_t a = s.find("model_chosen="); + if (a != string::npos) s.erase(a, s.find("\r\n", a) + 2 - a); + return s; + }; + require(toK.find("model_chosen=") != string::npos, "Model K chosen: model_chosen written"); + const string kThenM = Wini(DefaultProfile(), toK); + require(noTime(kThenM) == fresh.substr(0, fresh.find("runtime_options")) + "runtime_options=model=M\r\n" && kThenM.find("model_chosen=") != string::npos, + "K then M: only the runtime_options line is rewritten (the installer's comment on it is gone as it is for L), " + "and model_chosen is the time of that change"); const string withLItem = "[fsr]\r\nruntime_options = model=L\r\n"; if (withL) { require(Wini(DefaultProfile(), withLItem).find("model=M") != string::npos, "Model M control: Model L's item still goes back to model=M"); From 4b1c4b206c4dc4d02967155b15bec53b5d6ac9b9 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:06:18 -0500 Subject: [PATCH 03/15] Model choice precedence: review fixes (re-apply, ties, OptiScaler's FFX box) Review of #213 (three items): 1. An explicit launcher apply of a model restamps it as the newest choice, also the same model again and Model M: `set model=` passes modelChosen to ApplyProfile and RenderWronggpuIni, which writes model_chosen even when the model item is unchanged (Model M then becomes the last model item). Another setting applied is still not a model choice. 2. Stamps are Windows FILETIME units (100 ns since 1601 UTC) on all sides (launcher, plugin, front end). An exact tie goes to the launcher (then OptiScaler's FFX box, then the plugin menu); an untimed explicit choice ranks as the oldest and the log says so. Clock rollback is documented as a known limit. 3. With the plugin hooked, the WrongGPU entry picked in OptiScaler's FFX upscaler box is a third choice: the front end saves the entry it saw (wronggpu-ffx-choice.ini next to wronggpu.ini), stamps the time when it changes, and DecideModel weighs launcher, FFX box and plugin menu by the same most-recent rule, with one conflict line naming each. An AMD version in the box is still not a model choice. No OptiScaler change. Tests: the three-source table in every order, ties, untimed sources, the re-apply sequence for L, K and M (front end and launcher), the FFX box through hosted creates across two sessions; the Model K / Model L launcher end-to-end tests expect the new model_chosen line. Negative controls: each fix reverted makes its tests fail. Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/fsr/asi/README.md | 28 ++- clean/fsr/asi/asi_abi.h | 2 +- clean/fsr/asi/asi_thunk.h | 10 +- clean/fsr/asi/wronggpu_asi.cpp | 10 +- clean/fsr/src/asi_bridge.cpp | 28 +++ clean/fsr/src/asi_bridge.h | 7 + clean/fsr/src/config.cpp | 4 +- clean/fsr/src/config.h | 2 +- clean/fsr/src/dllmain.cpp | 2 + clean/fsr/src/frontend.cpp | 49 ++++- clean/fsr/src/frontend.h | 10 + clean/fsr/src/model_precedence.h | 169 ++++++++++----- clean/fsr/tests/test_frontend.cpp | 203 ++++++++++++++++-- clean/installer/src/app/cli.cpp | 3 + clean/installer/src/wg_core/launcher.cpp | 10 +- clean/installer/src/wg_core/launcher.h | 6 +- clean/installer/src/wg_core/profile.cpp | 21 +- clean/installer/src/wg_core/profile.h | 15 +- .../installer/tests/model_choice_k_tests.cpp | 11 +- clean/installer/tests/model_choice_tests.cpp | 17 +- clean/installer/tests/run_model_k_tests.py | 12 +- clean/installer/tests/run_model_l_tests.py | 29 ++- 22 files changed, 526 insertions(+), 122 deletions(-) diff --git a/clean/fsr/asi/README.md b/clean/fsr/asi/README.md index 1f909e2e..dba8152b 100644 --- a/clean/fsr/asi/README.md +++ b/clean/fsr/asi/README.md @@ -21,16 +21,24 @@ What the front end does with the plugin's entry (`src/frontend.cpp`, `TestAsiPlu whatever the FFX box names; "FSR 3.X(/4)" runs AMD: the AMD version the FFX box names, else AMD's newest listed version. The FFX box's list is the same with and without the plugin (WrongGPU first). -Which model runs (0.6.5, `src/model_precedence.h`, `TestAsiLauncherPrecedence`): the plugin's saved entry is weighed -against the launcher's model choice, the last `model=` item of wronggpu.ini's `runtime_options`. Each side records when -it was chosen: the plugin writes `chosen=` into `wronggpu-asi.ini` on every click in the menu, -and the launcher writes `model_chosen=` into wronggpu.ini whenever it changes the model item. A choice is a -*default* when nobody made it (no file, or Model M with no time on either side). The launcher's choice wins over the -plugin's default; the plugin's explicit choice wins over the launcher's default; when both are explicit and differ, the -more recent one wins (equal or missing times: the plugin's, the choice made in the game), and the front end logs one -`model choice conflict:` line naming both and the winner. The front end tells the plugin which model runs -(`WrongGpuAsiShowModelV1`), so the menu marks that entry. Model L's own entry ("WrongGPU Model L") is in the menu of a -build with `WG_MODEL_L`; a model the front end was built without runs as Model M, with a note in the log. +Which model runs (0.6.5, `src/model_precedence.h`, `TestAsiLauncherPrecedence`, `TestAsiFfxIndexChoice`): three places +can choose, each with the time it was chosen in Windows FILETIME units (100 ns since 1601 UTC): +- the launcher: the last `model=` item of wronggpu.ini's `runtime_options` and `model_chosen=`, written whenever the + launcher changes that item and whenever the player explicitly applies a model, also the same one again + (`WrongGPU.exe set model=`); +- OptiScaler's FFX upscaler box: the WrongGPU entry picked there (the version id OptiScaler passes with each create). The + front end saves the entry it saw in `wronggpu-ffx-choice.ini` next to wronggpu.ini and stamps the time when it sees a + different one; the first entry it ever sees is saved untimed; +- the plugin's menu: `selection=` and `chosen=` in `wronggpu-asi.ini`, written on every click. + +A choice is a *default* when nobody made it (no file, or Model M with no time; an untimed FFX entry). The most recent +explicit choice wins; an untimed explicit choice (a file of an earlier version) counts as the oldest; on an exact tie the +launcher wins, then the FFX box, then the plugin's menu. Explicit choices naming different models are a conflict: the +front end logs one `model choice conflict:` line naming each with its time and the winner with the reason. The front end +tells the plugin which model runs (`WrongGpuAsiShowModelV1`), so the menu marks that entry. Model L's own entry +("WrongGPU Model L") is in the menu of a build with `WG_MODEL_L`; a model the front end was built without runs as Model M, +with a note in the log. Known limit: the order follows the PC's clock; a clock set back between two choices can order +them wrongly. ## How it works diff --git a/clean/fsr/asi/asi_abi.h b/clean/fsr/asi/asi_abi.h index 37b6993c..6b60ed15 100644 --- a/clean/fsr/asi/asi_abi.h +++ b/clean/fsr/asi/asi_abi.h @@ -79,7 +79,7 @@ typedef int (*PfnWrongGpuAsiQueryStatusV1)(WrongGpuAsiStatusV1* status, uint32_t // The player's saved choice with what the front end needs to weigh it against the launcher's model choice (0.6.5; // src/model_precedence.h). model: 0 (AMD), 'M', 'K' or 'L'. explicit_choice: 1 when the player chose it in the menu (or // a file of an earlier version names a non-default entry), 0 for the default entry (no file, or Model M with no time). -// chosen_at: when the player clicked it, seconds since 1970-01-01 UTC; 0 = not recorded. Same size/version rules and +// chosen_at: when the player clicked it, Windows FILETIME (100 ns since 1601-01-01 UTC); 0 = not recorded. Same size/version rules and // return codes as WrongGpuAsiQueryStatusV1. A front end that finds no such export uses WrongGpuAsiQuery and treats // Model M as the default entry and K / AMD as explicit choices with no recorded time. #define WRONGGPU_ASI_CHOICE_QUERY "WrongGpuAsiQueryChoiceV1" diff --git a/clean/fsr/asi/asi_thunk.h b/clean/fsr/asi/asi_thunk.h index 0032029e..3d9e2a8b 100644 --- a/clean/fsr/asi/asi_thunk.h +++ b/clean/fsr/asi/asi_thunk.h @@ -57,8 +57,8 @@ inline const char* LabelOf(char model) { // Shared plugin state. `hooked` is read by the front end through the exported query. `model` is the player's saved // choice within OptiScaler's FSR 3.X entry; `explicitChoice` says whether the player (or an earlier version's file) -// actually chose it, as opposed to the default entry; `chosenAt` is when the player clicked it (seconds since -// 1970-01-01 UTC, 0 = not recorded: a file written before 0.6.5, or by an installer). `shown` is the model the front +// actually chose it, as opposed to the default entry; `chosenAt` is when the player clicked it (Windows FILETIME: +// 100 ns since 1601-01-01 UTC, 0 = not recorded: a file written before 0.6.5, or by an installer). `shown` is the model the front // end reported as running (kShowSaved until it reports one): the menu marks that one, so a launcher choice that won // over the plugin's default is what the player sees checked. struct PluginState { @@ -80,7 +80,7 @@ inline bool IsFsr3xLabel(const char* label) { // The Selectable thunk. `sel` is the real ImGui::Selectable(label, selected, flags, size). For OptiScaler's FSR 3.X // entry it draws the WrongGPU items first, then the original entry, records any click as the player's explicit choice -// (made at `now`, seconds since 1970 UTC), and returns true (click) to OptiScaler when any of them was clicked so +// (made at `now`, FILETIME units), and returns true (click) to OptiScaler when any of them was clicked so // OptiScaler switches to its FSR 3.X backend. `selected` (OptiScaler's backend is FSR 3.X) marks the WrongGPU item or // the FSR 3.X item of the model shown (ShownModel). Every other entry passes through unchanged. *clickedOut (when // given) is set to true on a click on one of these items, so the caller saves the choice. @@ -113,7 +113,7 @@ bool BeginComboThunkLogic(BcFn&& bc, const char* label, const char* preview, int } // The remembered choice (wronggpu-asi.ini next to the plugin): "selection=wronggpu" (Model M), "wronggpu-k", -// "wronggpu-l" or "amd", and since 0.6.5 "chosen=", the time of the player's click. +// "wronggpu-l" or "amd", and since 0.6.5 "chosen=" (100 ns since 1601 UTC), the time of the player's click. struct Selection { char model = kDefaultModel; bool explicitChoice = false; // false: the default entry (no file, no selection line, an unknown value, or @@ -166,7 +166,7 @@ inline const char* SelectionValue(char model) { // `chosenAt` 0 writes no time (the default entry's file, as installers write it). inline std::string FormatSelection(char model, uint64_t chosenAt = 0) { std::string text = std::string("; WrongGPU OptiScaler plugin: the entry last selected in OptiScaler's upscaler list\r\n") + - "; (wronggpu, wronggpu-k, wronggpu-l or amd) and when (chosen: seconds since 1970 UTC).\r\n" + "; (wronggpu, wronggpu-k, wronggpu-l or amd) and when (chosen: Windows FILETIME, 100 ns since 1601 UTC).\r\n" "; Deleting this file selects WrongGPU's default; the launcher's model choice then decides.\r\n" "selection=" + SelectionValue(model) + "\r\n"; if (chosenAt) text += "chosen=" + std::to_string(chosenAt) + "\r\n"; diff --git a/clean/fsr/asi/wronggpu_asi.cpp b/clean/fsr/asi/wronggpu_asi.cpp index d9a79241..0b1487de 100644 --- a/clean/fsr/asi/wronggpu_asi.cpp +++ b/clean/fsr/asi/wronggpu_asi.cpp @@ -82,13 +82,11 @@ wgasi::Selection LoadSelection() { return wgasi::ParseSelectionFile(text); } -// Seconds since 1970-01-01 UTC (the launcher stamps its model choice on the same clock). -uint64_t NowUnixSeconds() { +// Windows FILETIME units, 100 ns since 1601-01-01 UTC (the launcher and the front end stamp on the same clock and unit). +uint64_t NowFileTime() { FILETIME ft; GetSystemTimeAsFileTime(&ft); - const uint64_t t = (uint64_t(ft.dwHighDateTime) << 32) | ft.dwLowDateTime; // 100 ns since 1601 - const uint64_t epoch = 116444736000000000ull; // 1970-01-01 in that unit - return t > epoch ? (t - epoch) / 10000000ull : 0; + return (uint64_t(ft.dwHighDateTime) << 32) | ft.dwLowDateTime; } void SaveSelection(char model, uint64_t chosenAt) { @@ -105,7 +103,7 @@ extern "C" bool WgSelectableThunk(const char* label, bool selected, int flags, c bool ours = false; const bool clicked = wgasi::SelectableThunkLogic( [](const char* l, bool s, int f, const void* z) { return g_realSelectable(l, s, f, z); }, - label, selected, flags, size, g_state, NowUnixSeconds(), &ours); + label, selected, flags, size, g_state, NowFileTime(), &ours); if (ours) { // a click on an entry of the FSR 3.X group: the player's explicit choice, with its time (rare; menu thread) const char after = g_state.model.load(); const uint64_t at = g_state.chosenAt.load(); diff --git a/clean/fsr/src/asi_bridge.cpp b/clean/fsr/src/asi_bridge.cpp index ce4443ed..275247da 100644 --- a/clean/fsr/src/asi_bridge.cpp +++ b/clean/fsr/src/asi_bridge.cpp @@ -47,4 +47,32 @@ void ShowAsiModel(char model) { show(model); } +static std::wstring FfxChoicePath(const std::wstring& ini) { + const size_t slash = ini.find_last_of(L"\\/"); + return (slash == std::wstring::npos ? std::wstring(L".") : ini.substr(0, slash)) + L"\\wronggpu-ffx-choice.ini"; +} + +bool LoadFfxChoice(const std::wstring& ini, wgfsr::FfxModelChoice* choice) { + HANDLE h = CreateFileW(FfxChoicePath(ini).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) return false; + char buf[1024]; + DWORD got = 0; + const bool ok = ReadFile(h, buf, sizeof buf, &got, nullptr) != 0; + CloseHandle(h); + if (!ok) return false; + if (choice) *choice = wgfsr::ParseFfxChoiceFile(std::string(buf, got)); + return true; +} + +void SaveFfxChoice(const std::wstring& ini, const wgfsr::FfxModelChoice& choice) { + const std::string text = wgfsr::FormatFfxChoiceFile(choice); + HANDLE h = CreateFileW(FfxChoicePath(ini).c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, + nullptr); + if (h == INVALID_HANDLE_VALUE) return; + DWORD written = 0; + WriteFile(h, text.data(), DWORD(text.size()), &written, nullptr); + CloseHandle(h); +} + } // namespace wgwin diff --git a/clean/fsr/src/asi_bridge.h b/clean/fsr/src/asi_bridge.h index 40d5e125..70cab5d5 100644 --- a/clean/fsr/src/asi_bridge.h +++ b/clean/fsr/src/asi_bridge.h @@ -2,6 +2,8 @@ #pragma once // Front-end side of the WrongGPU ASI plugin interface (clean/fsr/asi/asi_abi.h): find WrongGPU.asi if it is loaded // in the process and ask it which upscaler entry the player selected in OptiScaler's menu. No link to the plugin. +#include + #include "model_precedence.h" namespace wgwin { @@ -15,4 +17,9 @@ bool QueryAsiPlugin(wgfsr::PluginModelChoice* choice); // Tells the plugin which model runs (its menu marks that entry). Nothing happens without the plugin or the export. void ShowAsiModel(char model); +// wronggpu-ffx-choice.ini next to `ini` (the front end's wronggpu.ini): the WrongGPU entry last seen in OptiScaler's FFX +// upscaler box (model_precedence.h). Load: false when there is no such file. +bool LoadFfxChoice(const std::wstring& ini, wgfsr::FfxModelChoice* choice); +void SaveFfxChoice(const std::wstring& ini, const wgfsr::FfxModelChoice& choice); + } // namespace wgwin diff --git a/clean/fsr/src/config.cpp b/clean/fsr/src/config.cpp index b39c276d..dc7daeee 100644 --- a/clean/fsr/src/config.cpp +++ b/clean/fsr/src/config.cpp @@ -346,8 +346,8 @@ Config ParseConfig(const std::string& text, std::string* warnings) { } else if (key == "runtime_options") { c.runtimeOptions = NormalizeOptions(value); } else if (key == "model_chosen") { - // Written by the launcher with the model item (model_precedence.h): seconds since 1970 UTC. - ok = !value.empty() && value.size() <= 19 && value.find_first_not_of("0123456789") == std::string::npos; + // Written by the launcher with the model item (model_precedence.h): FILETIME, 100 ns since 1601 UTC. + ok = !value.empty() && value.size() <= 20 && value.find_first_not_of("0123456789") == std::string::npos; if (ok) c.modelChosenAt = std::strtoull(value.c_str(), nullptr, 10); } else if (key == "overlay") { ok = lv == "on" || lv == "badge" || lv == "off"; diff --git a/clean/fsr/src/config.h b/clean/fsr/src/config.h index 5645d130..61ddd866 100644 --- a/clean/fsr/src/config.h +++ b/clean/fsr/src/config.h @@ -79,7 +79,7 @@ struct Config { // Extra "key=value;key=value" text for the upscaler (the network runtime's own keys, e.g. timing_log=1;sync=pipelined), // appended to BackendOptions() after the front end's keys. Normalized: items trimmed, empty items dropped. std::string runtimeOptions; - // [fsr] model_chosen: when the launcher last changed the model item of runtime_options (seconds since 1970 UTC; + // [fsr] model_chosen: when the launcher last changed the model item of runtime_options (Windows FILETIME, 100 ns since 1601 UTC; // 0 = not recorded). Weighed against the OptiScaler menu plugin's saved choice (model_precedence.h). uint64_t modelChosenAt = 0; diff --git a/clean/fsr/src/dllmain.cpp b/clean/fsr/src/dllmain.cpp index a1b8151d..56659309 100644 --- a/clean/fsr/src/dllmain.cpp +++ b/clean/fsr/src/dllmain.cpp @@ -239,6 +239,8 @@ FrontEnd& Get() { // before. p.asiPlugin = [](wgfsr::PluginModelChoice* choice) { return QueryAsiPlugin(choice); }; p.asiShowModel = [](char model) { ShowAsiModel(model); }; + p.loadFfxChoice = [](wgfsr::FfxModelChoice* c) { return LoadFfxChoice(Place().ini, c); }; + p.saveFfxChoice = [](const wgfsr::FfxModelChoice& c) { SaveFfxChoice(Place().ini, c); }; } p.menu = Menu(); g_frontEnd = new FrontEnd(p, config); diff --git a/clean/fsr/src/frontend.cpp b/clean/fsr/src/frontend.cpp index bfd3ebad..7373fa3f 100644 --- a/clean/fsr/src/frontend.cpp +++ b/clean/fsr/src/frontend.cpp @@ -566,17 +566,23 @@ ffxReturnCode_t FrontEnd::CreateUpscale(ffxContext* context, ffxCreateContextDes } } - // OptiScaler ASI plugin (clean/fsr/asi): when it has hooked the host's MAIN upscaler list, the FFX sub-box no - // longer chooses: the plugin's saved entry and the launcher's model choice (wronggpu.ini runtime_options' model item - // with model_chosen) do, by model_precedence.h (the launcher's choice wins over the plugin's default entry; on a - // conflict the more recent explicit choice wins, with one log line). A WrongGPU model -> WrongGPU, whatever the FFX - // sub-box names. AMD ("FSR 3.X(/4)") -> AMD: the version the FFX sub-box names when that is one of AMD's, else AMD's - // newest listed version (FSR 4 when the AMD provider has it). + // OptiScaler ASI plugin (clean/fsr/asi): when it has hooked the host's MAIN upscaler list, three choices are weighed + // by model_precedence.h: the launcher's (wronggpu.ini runtime_options' model item with model_chosen), the WrongGPU + // entry picked in OptiScaler's FFX sub-box (the override id, stamped when it changes: FfxChoiceSeen) and the plugin's + // saved entry. The most recent explicit choice wins (a tie: the launcher's), with one log line on a conflict. A + // WrongGPU model -> WrongGPU; an AMD version in the FFX sub-box is not a model choice and never routes it to AMD. + // AMD ("FSR 3.X(/4)" chosen in the plugin's list) -> AMD: the version the FFX sub-box names when that is one of AMD's, + // else AMD's newest listed version (FSR 4 when the AMD provider has it). PluginModelChoice asiChoice; const bool asiHooked = config_.hosted && platform_.asiPlugin && platform_.asiPlugin(&asiChoice); bool forceAmd = false; if (asiHooked) { - const ModelDecision decision = DecideModel(asiChoice, LauncherChoice()); + char seen = kChoiceNone; // the WrongGPU model entry the FFX sub-box names, if any + if (u->hasOverride) + if (const WgEntryDef* e = OwnEntryOfId(u->overrideId)) + if (e->slot == WG_OPT_SR_MODEL && e->value >= 0 && e->value < WG_SR_MODEL_COUNT) seen = kWgModelRows[e->value].name[0]; + const FfxModelChoice ffx = SeeFfxChoice(seen, tag); + const ModelDecision decision = DecideModel(asiChoice, LauncherChoice(), ffx); if (decision.conflict) { bool first = false; { @@ -590,6 +596,8 @@ ffxReturnCode_t FrontEnd::CreateUpscale(ffxContext* context, ffxCreateContextDes // model that runs (asiShowModel), also when the launcher's choice decided. const std::string by = decision.winner == ModelWinner::Launcher ? std::string(" (the launcher's model choice: wronggpu.ini runtime_options model=") + decision.model + ")" + : decision.winner == ModelWinner::Ffx + ? std::string(" (the WrongGPU entry picked in OptiScaler's upscaler box: Model ") + decision.model + ")" : std::string(); char model = decision.model; if (model != kChoiceAmd) { @@ -1412,6 +1420,33 @@ LauncherModelChoice FrontEnd::LauncherChoice() const { return c; } +FfxModelChoice FrontEnd::SeeFfxChoice(char seen, const std::string& tag) { + FfxModelChoice before, after; + { + std::lock_guard lock(mutex_); + if (!ffxLoaded_) { + ffxLoaded_ = true; + if (platform_.loadFfxChoice) platform_.loadFfxChoice(&ffxSaved_); + } + before = ffxSaved_; + uint64_t now = 0; + if (seen != kChoiceNone && before.model != kChoiceNone && before.model != seen) + now = platform_.clock ? platform_.clock() + : uint64_t(std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count() / 100) + + 116444736000000000ull; // 1970 in FILETIME units + after = FfxChoiceSeen(before, seen, now); + ffxSaved_ = after; + } + if (after.model != before.model || after.chosenAt != before.chosenAt) { + if (platform_.saveFfxChoice) platform_.saveFfxChoice(after); + Log(tag + " OptiScaler's upscaler box names " + ChoiceName(after.model) + + (after.chosenAt ? " (changed there: an explicit choice, chosen=" + std::to_string(after.chosenAt) + ")" + : std::string(" (the first entry seen: not counted as a choice)"))); + } + return after; +} + void FrontEnd::ApplyEntry(const WgEntryDef& e, UpscaleContext& u, const std::string& tag, const char* source) { int32_t model = e.slot == WG_OPT_SR_MODEL ? e.value : -1; std::string described; diff --git a/clean/fsr/src/frontend.h b/clean/fsr/src/frontend.h index bfecb324..573ec929 100644 --- a/clean/fsr/src/frontend.h +++ b/clean/fsr/src/frontend.h @@ -96,6 +96,12 @@ struct Platform { std::function asiPlugin; // Tells the plugin which model the context runs (0 AMD, 'M', 'K', 'L'), so its menu marks that entry. May be empty. std::function asiShowModel; + // With the plugin hooked: the WrongGPU entry last seen in OptiScaler's FFX upscaler box and when it changed + // (model_precedence.h FfxChoiceSeen; wronggpu-ffx-choice.ini in the DLL). Empty: nothing is kept between sessions. + std::function loadFfxChoice; + std::function saveFfxChoice; + // The time a choice is stamped with: Windows FILETIME units (100 ns since 1601 UTC). Empty: the system clock. + std::function clock; // Registry options and the menu's choices (shared settings block). Empty members: defaults, nothing written. MenuSettings menu; }; @@ -209,6 +215,8 @@ class FrontEnd { bool ConfiguredModel(int32_t* model, std::string* described); // The launcher's model choice in wronggpu.ini (model_precedence.h), weighed against the OptiScaler plugin's. LauncherModelChoice LauncherChoice() const; + // The FFX sub-box's WrongGPU entry seen by a create (`seen`, or kChoiceNone), saved and stamped when it changes. + FfxModelChoice SeeFfxChoice(char seen, const std::string& tag); // AMD's DLL behind a forwarded context (the one that created it), else AMD's original. const OriginalApi* ApiOf(void* context); // `u` runs on AMD while its upscaler's create runs (u.pending): takes the upscaler over when the create has finished. @@ -269,6 +277,8 @@ class FrontEnd { uint32_t inputRefusedRun_ = 0; // refusals in a row with that key (mutex_) std::atomic inputRefusedAny_{false}; // inputRefusedRun_ > 0 (the taken-frame path's cheap check) std::map modelLogged_; // ApplyModelDir: each distinct choice logged once (mutex_) + bool ffxLoaded_ = false; // SeeFfxChoice: the saved FFX entry read (mutex_) + FfxModelChoice ffxSaved_; std::atomic reentered_{0}; // calls refused because they re-entered this front end on one thread std::mutex parkMutex_; // guards the three below; held while a parked context is destroyed UpscaleContext* parked_ = nullptr; diff --git a/clean/fsr/src/model_precedence.h b/clean/fsr/src/model_precedence.h index d46d3d72..e1daefe2 100644 --- a/clean/fsr/src/model_precedence.h +++ b/clean/fsr/src/model_precedence.h @@ -1,37 +1,43 @@ // SPDX-License-Identifier: MIT #pragma once -// Which model runs when WrongGPU's OptiScaler menu plugin (clean/fsr/asi) has hooked the host's upscaler list: the -// plugin's saved choice or the launcher's (0.6.5). Plain C++, no Windows headers, so the unit tests can check it on -// any host (tests/test_model_precedence.cpp; the front end's own tests check it through CreateUpscale). +// Which model runs when WrongGPU's OptiScaler menu plugin (clean/fsr/asi) has hooked the host's upscaler list (0.6.5). +// Plain C++, no Windows headers, so the unit tests can check it on any host (tests/test_frontend.cpp, +// TestAsiLauncherPrecedence; the front end applies it in CreateUpscale). // -// The two choices: -// - the plugin's: the entry the player last clicked in OptiScaler's upscaler list (wronggpu-asi.ini: selection= and, -// since 0.6.5, chosen= with the click's time); -// - the launcher's: the last model item of wronggpu.ini's runtime_options (model=M / K / L), which the launcher -// writes, with model_chosen= (the time the launcher last changed that item; since 0.6.5). -// Times are seconds since 1970-01-01 UTC on this PC's clock; 0 means "not recorded" (files of earlier versions, -// installers, a hand-edited file). +// Three places can choose the model, each with the time it was chosen: +// - the LAUNCHER: the last model item of wronggpu.ini's runtime_options (model=M / K / L) and model_chosen=, which the +// launcher writes whenever it changes that item and whenever the player explicitly applies a model (also the same +// one again: `WrongGPU.exe set model=`); +// - the OPTISCALER INDEX: the WrongGPU entry the player picked in OptiScaler's FFX upscaler box (the version id +// OptiScaler passes with each create; [FSR] UpscalerIndex). The front end saves the entry it saw (wronggpu-ffx-choice.ini) +// and stamps the time when it sees a different one (FfxChoiceSeen below); +// - the PLUGIN MENU: the entry the player last clicked in the plugin's items of OptiScaler's main list +// (wronggpu-asi.ini selection= and chosen=). +// Times are Windows FILETIME units: 100 ns since 1601-01-01 UTC, on this PC's clock, so two choices practically never +// share a time. 0 means "not recorded" (files of earlier versions, installers, a hand edit, the first entry the front +// end ever saw): such a choice ranks as the OLDEST. // -// A choice is a DEFAULT when nobody chose it: on the plugin's side no file, no selection line, or Model M with no -// time (what installers seed and what earlier versions saved); on the launcher's side no model item, or model=M with -// no time (the installer's model=M). Anything else is EXPLICIT. +// A choice is a DEFAULT when nobody made it: plugin menu with no file / no selection line / Model M with no time; launcher +// with no model item or model=M with no time (the installer's item); OptiScaler index with no time (the first entry seen, +// or none). Anything else is EXPLICIT. // // The rule: -// 1. both default: Model M (as before); -// 2. only one explicit: that one (the launcher's choice wins over the plugin's default, and the reverse); -// 3. both explicit and the same model: that model; -// 4. both explicit and different (a CONFLICT): the more recent one, by its time; with equal times (also both not -// recorded) the plugin's, the choice the player made in the game. The front end logs one line naming both choices -// and which one won. +// 1. no explicit choice: the launcher's model item if it has one, else Model M (as before); +// 2. otherwise the explicit choice with the latest time wins; untimed explicit choices are the oldest; +// 3. on an exact tie (also: all untimed) the launcher wins, then the OptiScaler index, then the plugin menu (the launcher is +// the deliberate settings tool); +// 4. explicit choices that name different models are a CONFLICT: the front end logs one line naming each, its time, and +// the winner with the reason. // AMD (the plugin's "FSR 3.X(/4)" entry, model 0) is a choice like the models. The launcher's "WrongGPU off" // (upscaler = amd) is not a model choice: it is a master switch and still turns WrongGPU off whatever is chosen here. +// Known limit: the order follows the PC's clock; a clock set back between two choices can order them wrongly. #include #include namespace wgfsr { constexpr char kChoiceAmd = 0; // AMD's FSR (the plugin's FSR 3.X entry) -constexpr char kChoiceNone = '-'; // the launcher stated no model +constexpr char kChoiceNone = '-'; // no model stated struct PluginModelChoice { char model = 'M'; // 0 (AMD), 'M', 'K', 'L' @@ -45,7 +51,59 @@ struct LauncherModelChoice { bool Explicit() const { return model != kChoiceNone && (model != 'M' || chosenAt != 0); } }; -enum class ModelWinner { Default, Plugin, Launcher }; +// The WrongGPU entry picked in OptiScaler's FFX upscaler box, as the front end last saw it. +struct FfxModelChoice { + char model = kChoiceNone; // 'M', 'K', 'L', or kChoiceNone (no WrongGPU entry seen) + uint64_t chosenAt = 0; // when the front end saw it change; 0: the first entry seen (not counted as a choice) + bool Explicit() const { return model != kChoiceNone && chosenAt != 0; } +}; + +// The saved FFX entry after a create that names `seen` (a WrongGPU model's entry, or kChoiceNone) at time `now`: the +// first entry ever seen is saved untimed (it is what the launcher or the install set); a different entry than the saved +// one is the player's choice in OptiScaler's box, made now; the same entry keeps its time. No entry seen: unchanged. +inline FfxModelChoice FfxChoiceSeen(const FfxModelChoice& saved, char seen, uint64_t now) { + if (seen == kChoiceNone) return saved; + if (saved.model == kChoiceNone) return FfxModelChoice{seen, 0}; + if (saved.model != seen) return FfxModelChoice{seen, now}; + return saved; +} + +// wronggpu-ffx-choice.ini (next to wronggpu.ini): "model=" and "chosen=" (0 or none: untimed). +inline FfxModelChoice ParseFfxChoiceFile(const std::string& text) { + FfxModelChoice c; + size_t at = 0; + while (at < text.size()) { + size_t end = text.find('\n', at); + if (end == std::string::npos) end = text.size(); + std::string line; + for (size_t i = at; i < end; ++i) + if (text[i] != ' ' && text[i] != '\t' && text[i] != '\r') line += text[i]; + at = end + 1; + if (line.size() == 7 && line.compare(0, 6, "model=") == 0) { + const char m = char(line[6] >= 'a' && line[6] <= 'z' ? line[6] - 32 : line[6]); + if (m == 'M' || m == 'K' || m == 'L') c.model = m; + } else if (line.compare(0, 7, "chosen=") == 0 && line.size() > 7 && line.size() <= 27) { + uint64_t t = 0; + bool ok = true; + for (size_t i = 7; i < line.size(); ++i) { + if (line[i] < '0' || line[i] > '9') { ok = false; break; } + t = t * 10 + uint64_t(line[i] - '0'); + } + if (ok) c.chosenAt = t; + } + } + if (c.model == kChoiceNone) c.chosenAt = 0; + return c; +} + +inline std::string FormatFfxChoiceFile(const FfxModelChoice& c) { + return std::string("; WrongGPU front end: the WrongGPU entry last seen in OptiScaler's FFX upscaler box, and when it changed\r\n" + "; (chosen: Windows FILETIME, 100 ns since 1601 UTC; 0 = the first entry seen, not counted as a choice).\r\n" + "model=") + (c.model == kChoiceNone ? std::string() : std::string(1, c.model)) + "\r\nchosen=" + + std::to_string(c.chosenAt) + "\r\n"; +} + +enum class ModelWinner { Default, Plugin, Launcher, Ffx }; struct ModelDecision { char model = 'M'; @@ -60,41 +118,54 @@ inline std::string ChoiceName(char model) { return std::string("Model ") + model; } -inline std::string ChoiceTime(uint64_t t) { return t ? "chosen=" + std::to_string(t) : "no time recorded"; } +inline std::string ChoiceTime(uint64_t t) { return t ? "chosen=" + std::to_string(t) : "no time recorded, counted as the oldest"; } -inline ModelDecision DecideModel(const PluginModelChoice& plugin, const LauncherModelChoice& launcher) { +inline ModelDecision DecideModel(const PluginModelChoice& plugin, const LauncherModelChoice& launcher, + const FfxModelChoice& ffx = FfxModelChoice{}) { + struct Source { + bool on; + char model; + uint64_t at; + ModelWinner who; + const char* name; + }; + // tie order: launcher, OptiScaler index, plugin menu + const Source s[3] = { + {launcher.Explicit(), launcher.model, launcher.chosenAt, ModelWinner::Launcher, "the launcher"}, + {ffx.Explicit(), ffx.model, ffx.chosenAt, ModelWinner::Ffx, "OptiScaler's upscaler box"}, + {plugin.explicitChoice, plugin.model, plugin.chosenAt, ModelWinner::Plugin, "the OptiScaler menu plugin"}, + }; ModelDecision d; - const bool p = plugin.explicitChoice, l = launcher.Explicit(); - if (!p && !l) { + const Source* best = nullptr; + for (const Source& c : s) + if (c.on && (!best || c.at > best->at)) best = &c; // strictly later wins: an equal time keeps the earlier in tie order + if (!best) { d.model = launcher.model == kChoiceNone ? 'M' : launcher.model; // (an unstamped model=M: Model M) return d; } - if (p && !l) { - d.model = plugin.model; - d.winner = ModelWinner::Plugin; - return d; - } - if (!p && l) { - d.model = launcher.model; - d.winner = ModelWinner::Launcher; - return d; + d.model = best->model; + d.winner = best->who; + int tied = 0; + for (const Source& c : s) { + if (!c.on) continue; + if (c.model != best->model) d.conflict = true; + if (c.at == best->at) ++tied; } - if (plugin.model == launcher.model) { - d.model = plugin.model; - d.winner = ModelWinner::Plugin; - return d; + if (!d.conflict) return d; + static const char* const where[3] = {" (wronggpu.ini runtime_options, model_chosen)", " (wronggpu-ffx-choice.ini)", + " (wronggpu-asi.ini)"}; + d.line = "model choice conflict:"; + bool first = true; + for (int i = 0; i < 3; ++i) { + if (!s[i].on) continue; + d.line += std::string(first ? " " : ", ") + s[i].name + " chose " + ChoiceName(s[i].model) + where[i] + " " + + ChoiceTime(s[i].at); + first = false; } - const bool launcherNewer = launcher.chosenAt > plugin.chosenAt; - d.conflict = true; - d.winner = launcherNewer ? ModelWinner::Launcher : ModelWinner::Plugin; - d.model = launcherNewer ? launcher.model : plugin.model; - d.line = "model choice conflict: OptiScaler menu plugin chose " + ChoiceName(plugin.model) + " (wronggpu-asi.ini, " + - ChoiceTime(plugin.chosenAt) + "), the launcher chose " + ChoiceName(launcher.model) + - " (wronggpu.ini runtime_options, model_chosen " + (launcher.chosenAt ? std::to_string(launcher.chosenAt) : "not recorded") + - "); " + (launcherNewer ? "the launcher's" : "the plugin's") + " choice wins (" + - (launcher.chosenAt == plugin.chosenAt ? "same time or none recorded: the in-game choice is kept" - : "the more recent explicit choice") + - "): " + ChoiceName(d.model) + " runs"; + const char* why = best->at == 0 ? "no choice recorded a time; the launcher, then OptiScaler's box, then the plugin is taken" + : tied > 1 ? "the same time; the launcher, then OptiScaler's box, then the plugin is taken" + : "the most recent explicit choice"; + d.line += std::string("; ") + best->name + "'s choice wins (" + why + "): " + ChoiceName(d.model) + " runs"; return d; } diff --git a/clean/fsr/tests/test_frontend.cpp b/clean/fsr/tests/test_frontend.cpp index 0b2c4367..ccacc845 100644 --- a/clean/fsr/tests/test_frontend.cpp +++ b/clean/fsr/tests/test_frontend.cpp @@ -240,6 +240,10 @@ static char g_asiModel = 0; // 0 (AMD), 'M', 'K', 'L' static int g_asiExplicit = -1; // -1: as an earlier plugin reports it (Model M = default entry, others explicit); 0/1 static uint64_t g_asiChosenAt = 0; // when the player clicked it (0 = not recorded) static std::vector g_asiShown; // Platform::asiShowModel calls +static bool g_ffxHas = false; // Platform::loadFfxChoice / saveFfxChoice: the saved FFX entry (wronggpu-ffx-choice.ini) +static FfxModelChoice g_ffxFile; +static int g_ffxSaves = 0; +static uint64_t g_clockNow = 0; // Platform::clock // Fake shared settings (Platform::menu, settings_bridge.h in the DLL): values set "somewhere" (block / env / ini), // the writes of the menu's choices, whether this module is the writer, the folder sidecar's entry. @@ -290,6 +294,17 @@ static std::unique_ptr MakeFrontEnd(const Config& config) { return g_asiHooked; }; p.asiShowModel = [](char model) { g_asiShown.push_back(model); }; + p.loadFfxChoice = [](FfxModelChoice* c) { + if (!g_ffxHas) return false; + *c = g_ffxFile; + return true; + }; + p.saveFfxChoice = [](const FfxModelChoice& c) { + g_ffxFile = c; + g_ffxHas = true; + ++g_ffxSaves; + }; + p.clock = [] { return g_clockNow; }; } p.compareApi = []() -> const OriginalApi* { return g_compareApi; }; p.backend = [](const Config&, std::string&) -> const WgUpscalerBackend* { return g_useBackend; }; @@ -386,6 +401,10 @@ static void Reset() { g_asiExplicit = -1; g_asiChosenAt = 0; g_asiShown.clear(); + g_ffxHas = false; + g_ffxFile = FfxModelChoice{}; + g_ffxSaves = 0; + g_clockNow = 0; g_createInfo = WgCreateInfo{}; g_compare = false; g_statuses.clear(); @@ -2679,6 +2698,116 @@ static bool EndsWith(const std::string& s, const std::string& tail) { return s.size() >= tail.size() && s.compare(s.size() - tail.size(), tail.size(), tail) == 0; } +// #213 review P3: with the plugin hooked, the WrongGPU entry picked in OptiScaler's FFX upscaler box is a third, stamped +// choice (model_precedence.h FfxChoiceSeen): saved between sessions, stamped when it changes, weighed with the launcher's +// and the plugin menu's by the same most-recent rule. And P1 through a hosted create: the launcher's re-applied model wins. +static std::string CreateHosted(FrontEnd& fe, uint64_t overrideId, bool* amd = nullptr) { + const size_t amdBefore = g_amd.size(); + UpscaleCreate create(FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE, true); + create.version.versionId = overrideId; + ffxContext ctx = nullptr; + CHECK(fe.CreateContext(&ctx, &create.upscale.header, kMemCb) == FFX_API_RETURN_OK && ctx); + std::string provider; + const bool wentAmd = g_amd.size() > amdBefore; + if (amd) *amd = wentAmd; + if (!wentAmd) { + ffxQueryGetProviderVersion q{}; + q.header.type = FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION; + if (fe.Query(&ctx, &q.header) == FFX_API_RETURN_OK && q.versionName) provider = q.versionName; + } + CHECK(fe.DestroyContext(&ctx, kMemCb) == FFX_API_RETURN_OK); + return provider; +} + +static void TestAsiFfxIndexChoice() { + const bool present = g_asiPresent, hooked = g_asiHooked; + const char saved = g_asiModel; + // P1 through a hosted create: launcher X@1000 -> plugin Y@2000 runs Y; launcher re-applies X@3000 -> X, for each model + // this build has (L, K, M). + for (char x : {'L', 'K', 'M'}) { + const int32_t mx = ModelOfName(std::string(1, x)); + if (mx < 0) continue; + const char y = x == 'M' ? (ModelOfName("K") >= 0 ? 'K' : ModelOfName("L") >= 0 ? 'L' : kChoiceAmd) : 'M'; + const std::string before = std::string("[fsr]\nruntime_options = model=") + x + "\nmodel_chosen = 1000\n"; + const std::string after = std::string("[fsr]\nruntime_options = model=") + x + "\nmodel_chosen = 3000\n"; + AsiRun r = RunAsi(before.c_str(), y, 1, 2000); + CHECK(y == kChoiceAmd ? r.amd : r.provider == std::string("WrongGPU Model ") + y); + r = RunAsi(after.c_str(), y, 1, 2000); + CHECK(r.provider == std::string("WrongGPU Model ") + x && EndsWith(r.options, std::string("model=") + x)); + CHECK(CountLog("the launcher's choice wins (the most recent explicit choice)") == 1); + } + // P3: a model to switch to in the FFX box (L, else K); without either only the pure rule above checks it. + const char b = ModelOfName("L") >= 0 ? 'L' : ModelOfName("K") >= 0 ? 'K' : 0; + if (b) { + const uint64_t idM = SrEntryOfModel(ModelOfName("M"))->id, idB = SrEntryOfModel(ModelOfName(std::string(1, b)))->id; + const std::string providerB = std::string("WrongGPU Model ") + b; + Reset(); + g_resources[kOutput] = {dxgi::R16G16B16A16_FLOAT, 2560, 1440}; + std::string warnings; + Config c = ParseConfig("[fsr]\nruntime_options = model=M\nmodel_chosen = 1000\n", &warnings); // the launcher: M@1000 + CHECK(warnings.empty()); + c.hosted = true; + c.contextParkMs = 0; + g_asiPresent = true; + g_asiHooked = true; + g_asiModel = 'M'; + g_asiExplicit = 0; // the plugin's default entry + { + auto fe = MakeFrontEnd(c); + g_clockNow = 2000; + CHECK(CreateHosted(*fe, idM) == "WrongGPU Model M"); // first entry seen: saved untimed, not a choice + CHECK(g_ffxHas && g_ffxFile.model == 'M' && g_ffxFile.chosenAt == 0 && g_ffxSaves == 1); + CHECK(CountLog("OptiScaler's upscaler box names Model M (the first entry seen: not counted as a choice)") == 1); + g_clockNow = 3000; + CHECK(CreateHosted(*fe, idB) == providerB); // the player picks B in OptiScaler's box: newer than the launcher's M + CHECK(g_ffxFile.model == b && g_ffxFile.chosenAt == 3000 && g_ffxSaves == 2); + CHECK(CountLog("model choice conflict: the launcher chose Model M") == 1 && + CountLog("OptiScaler's upscaler box's choice wins (the most recent explicit choice)") == 1); + CHECK(CountLog((std::string("OptiScaler plugin: ") + providerB + + " selected in the host's upscaler list (the WrongGPU entry picked in OptiScaler's upscaler box").c_str()) == 1); + g_clockNow = 4000; + CHECK(CreateHosted(*fe, idB) == providerB && g_ffxFile.chosenAt == 3000 && g_ffxSaves == 2); // same entry: same time + CHECK(CreateHosted(*fe, g_versionIds[0]) == providerB && g_ffxSaves == 2); // an AMD version is not a model choice + } + // next session: the saved entry (B@3000) is read back; the launcher re-applied M at 5000 -> M + g_log.clear(); + c = ParseConfig("[fsr]\nruntime_options = model=M\nmodel_chosen = 5000\n", &warnings); + c.hosted = true; + c.contextParkMs = 0; + { + auto fe = MakeFrontEnd(c); + CHECK(CreateHosted(*fe, idB) == "WrongGPU Model M" && g_ffxSaves == 2); + CHECK(CountLog("the launcher's choice wins (the most recent explicit choice): Model M runs") == 1); + } + // all three: launcher M@5000, index B@3000, plugin AMD@6000 -> AMD; plugin AMD@4000 -> the launcher's M + g_log.clear(); + g_asiModel = kChoiceAmd; + g_asiExplicit = 1; + g_asiChosenAt = 6000; + { + auto fe = MakeFrontEnd(c); + uint64_t count = 8, ids[8] = {}; + const char* names[8] = {}; + ffxQueryDescGetVersions versions{}; + versions.header.type = FFX_API_QUERY_DESC_TYPE_GET_VERSIONS; + versions.createDescType = FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE; + versions.device = kDevice; + versions.outputCount = &count; + versions.versionIds = ids; + versions.versionNames = names; + CHECK(fe->Query(nullptr, &versions.header) == FFX_API_RETURN_OK); // AMD's versions known (the AMD route) + bool amd = false; + CreateHosted(*fe, idB, &amd); + CHECK(amd && CountLog("the OptiScaler menu plugin's choice wins (the most recent explicit choice): AMD FSR runs") == 1); + g_asiChosenAt = 4000; + CHECK(CreateHosted(*fe, idB) == "WrongGPU Model M"); + } + } + g_asiPresent = present; + g_asiHooked = hooked; + g_asiModel = saved; +} + static void TestAsiLauncherPrecedence() { const bool present = g_asiPresent, hooked = g_asiHooked; const char saved = g_asiModel; @@ -2693,16 +2822,23 @@ static void TestAsiLauncherPrecedence() { PluginModelChoice pk{'K', true, 1000}, pkNew{'K', true, 5000}, pkOld{'K', true, 0}, pa{kChoiceAmd, true, 1000}; ModelDecision d = DecideModel(pk, l); // explicit K older than the launcher's L CHECK(d.model == 'L' && d.winner == ModelWinner::Launcher && d.conflict); - CHECK(d.line.find("OptiScaler menu plugin chose Model K") != std::string::npos && - d.line.find("the launcher chose Model L") != std::string::npos && - d.line.find("the launcher's choice wins (the more recent explicit choice): Model L runs") != std::string::npos); + CHECK(d.line.find("the OptiScaler menu plugin chose Model K (wronggpu-asi.ini) chosen=1000") != std::string::npos && + d.line.find("the launcher chose Model L (wronggpu.ini runtime_options, model_chosen) chosen=2000") != std::string::npos && + d.line.find("the launcher's choice wins (the most recent explicit choice): Model L runs") != std::string::npos); d = DecideModel(pkNew, l); // explicit K newer than the launcher's L CHECK(d.model == 'K' && d.winner == ModelWinner::Plugin && d.conflict && - d.line.find("the plugin's choice wins (the more recent explicit choice): Model K runs") != std::string::npos); - d = DecideModel(pkOld, LauncherModelChoice{'L', 0}); // neither recorded a time: the in-game choice is kept - CHECK(d.model == 'K' && d.conflict && d.line.find("same time or none recorded") != std::string::npos); - d = DecideModel(pkOld, l); // an earlier version's K (no time) against a timed launcher L: the launcher's - CHECK(d.model == 'L' && d.conflict); + d.line.find("the OptiScaler menu plugin's choice wins (the most recent explicit choice): Model K runs") != std::string::npos); + // P2: untimed explicit choices rank as the OLDEST; a tie (also: none timed) goes to the launcher + d = DecideModel(pkOld, LauncherModelChoice{'L', 0}); // neither recorded a time + CHECK(d.model == 'L' && d.winner == ModelWinner::Launcher && d.conflict && + d.line.find("no choice recorded a time") != std::string::npos && d.line.find("most recent") == std::string::npos); + d = DecideModel(pkOld, l); // an earlier version's K (no time) against a timed launcher L + CHECK(d.model == 'L' && d.conflict && d.line.find("Model K (wronggpu-asi.ini) no time recorded, counted as the oldest") != std::string::npos); + d = DecideModel(pk, LauncherModelChoice{'L', 0}); // a timed plugin K against an untimed launcher L: the plugin's + CHECK(d.model == 'K' && d.winner == ModelWinner::Plugin && + d.line.find("Model L (wronggpu.ini runtime_options, model_chosen) no time recorded, counted as the oldest") != std::string::npos); + d = DecideModel(PluginModelChoice{'K', true, 2000}, l); // an exact tie: the launcher, the deliberate settings tool + CHECK(d.model == 'L' && d.winner == ModelWinner::Launcher && d.line.find("the same time") != std::string::npos); d = DecideModel(pa, l); CHECK(d.model == 'L' && d.conflict && d.line.find("chose AMD FSR") != std::string::npos); d = DecideModel(pa, m); // the launcher went back to Model M after the player chose AMD in the game @@ -2710,11 +2846,51 @@ static void TestAsiLauncherPrecedence() { d = DecideModel(pk, LauncherModelChoice{'K', 9000}); // the same model: no conflict CHECK(d.model == 'K' && !d.conflict && d.line.empty()); CHECK(DecideModel(pa, none).model == kChoiceAmd && DecideModel(pa, m0).model == kChoiceAmd); + // P1: the launcher RE-APPLIES the same model after a newer in-game choice: its new stamp makes it the newest. + // (L@1000, plugin K@2000, launcher re-applies L@3000 -> L; the same for K and M.) + struct Seq { char launcherModel; PluginModelChoice plugin; }; + for (const Seq& q : {Seq{'L', PluginModelChoice{'K', true, 2000}}, Seq{'K', PluginModelChoice{'L', true, 2000}}, + Seq{'M', PluginModelChoice{'K', true, 2000}}}) { + CHECK(DecideModel(q.plugin, LauncherModelChoice{q.launcherModel, 1000}).model == q.plugin.model); // before the re-apply + d = DecideModel(q.plugin, LauncherModelChoice{q.launcherModel, 3000}); // after it + CHECK(d.model == q.launcherModel && d.winner == ModelWinner::Launcher && d.conflict); + } + // P3: the OptiScaler FFX index as a third source. FfxChoiceSeen: the first entry seen is untimed (not a choice); a + // different one later is stamped; the same one keeps its time; no WrongGPU entry seen changes nothing. + FfxModelChoice f0; + FfxModelChoice f1 = FfxChoiceSeen(f0, 'M', 100); + CHECK(f1.model == 'M' && f1.chosenAt == 0 && !f1.Explicit()); + FfxModelChoice f2 = FfxChoiceSeen(f1, 'L', 200); + CHECK(f2.model == 'L' && f2.chosenAt == 200 && f2.Explicit()); + CHECK(FfxChoiceSeen(f2, 'L', 300).chosenAt == 200 && FfxChoiceSeen(f2, kChoiceNone, 300).model == 'L'); + FfxModelChoice f3 = ParseFfxChoiceFile(FormatFfxChoiceFile(f2)); + CHECK(f3.model == 'L' && f3.chosenAt == 200); + CHECK(ParseFfxChoiceFile("model=k\r\nchosen=133000000000000000\r\n").chosenAt == 133000000000000000ull && + ParseFfxChoiceFile("model=k\r\n").model == 'K' && ParseFfxChoiceFile("model=Q\r\nchosen=5\r\n").model == kChoiceNone && + ParseFfxChoiceFile("model=Q\r\nchosen=5\r\n").chosenAt == 0 && ParseFfxChoiceFile("model=M\r\nchosen=x\r\n").chosenAt == 0); + // all three sources, in every order of their times: the latest explicit choice wins; launcher L, index K, plugin M + const uint64_t orders[6][3] = {{1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}}; + for (const auto& o : orders) { + const LauncherModelChoice lc{'L', 1000 * o[0]}; + const FfxModelChoice fc{'K', 1000 * o[1]}; + const PluginModelChoice pc{'M', true, 1000 * o[2]}; + const char expected = o[0] == 3 ? 'L' : o[1] == 3 ? 'K' : 'M'; + d = DecideModel(pc, lc, fc); + CHECK(d.model == expected && d.conflict); + CHECK(d.line.find("the launcher chose Model L") != std::string::npos && + d.line.find("OptiScaler's upscaler box chose Model K") != std::string::npos && + d.line.find("the OptiScaler menu plugin chose Model M") != std::string::npos); + } + // ties among three: launcher, then the index, then the plugin; an untimed index entry is not a choice + CHECK(DecideModel(PluginModelChoice{'M', true, 5}, LauncherModelChoice{'L', 5}, FfxModelChoice{'K', 5}).model == 'L'); + CHECK(DecideModel(PluginModelChoice{'M', true, 5}, LauncherModelChoice{}, FfxModelChoice{'K', 5}).model == 'K'); + CHECK(DecideModel(PluginModelChoice{'M', true, 5}, LauncherModelChoice{}, FfxModelChoice{'K', 0}).model == 'M'); + CHECK(DecideModel(PluginModelChoice{}, LauncherModelChoice{}, FfxModelChoice{'L', 7}).winner == ModelWinner::Ffx); } // Config: model_chosen is read; a bad value is said and ignored. { std::string w; - CHECK(ParseConfig("[fsr]\nruntime_options = model=L\nmodel_chosen = 1763150000\n", &w).modelChosenAt == 1763150000ull && w.empty()); + CHECK(ParseConfig("[fsr]\nruntime_options = model=L\nmodel_chosen = 134077000000000000\n", &w).modelChosenAt == 134077000000000000ull && w.empty()); CHECK(ParseConfig("[fsr]\nmodel_chosen = soon\n", &w).modelChosenAt == 0 && w.find("bad value") != std::string::npos); } AsiRun r; @@ -2731,12 +2907,12 @@ static void TestAsiLauncherPrecedence() { // (c) an explicit plugin choice older than the launcher's Model L -> Model L, with the conflict line once r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", kChoiceAmd, 1, 1000); CHECK(r.provider == "WrongGPU Model L" && EndsWith(r.options, "model=L") && !r.amd); - CHECK(CountLog("model choice conflict: OptiScaler menu plugin chose AMD FSR (wronggpu-asi.ini, chosen=1000), the launcher " - "chose Model L (wronggpu.ini runtime_options, model_chosen 2000); the launcher's choice wins") == 1); + CHECK(CountLog("model choice conflict: the launcher chose Model L (wronggpu.ini runtime_options, model_chosen) chosen=2000, " + "the OptiScaler menu plugin chose AMD FSR (wronggpu-asi.ini) chosen=1000; the launcher's choice wins") == 1); // (d) an explicit plugin choice newer than the launcher's -> the plugin's, with the conflict line r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", 'M', 1, 3000); CHECK(r.provider == "WrongGPU Model M" && EndsWith(r.options, "model=M")); - CHECK(CountLog("model choice conflict") == 1 && CountLog("the plugin's choice wins (the more recent explicit choice): Model M runs") == 1); + CHECK(CountLog("model choice conflict") == 1 && CountLog("the OptiScaler menu plugin's choice wins (the most recent explicit choice): Model M runs") == 1); r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", kChoiceAmd, 1, 3000); // ... AMD, newer CHECK(r.amd && r.provider.empty() && r.runtimeCreates == 0 && CountLog("OptiScaler plugin: AMD FSR selected in the host's upscaler list") == 1); @@ -2777,7 +2953,7 @@ static void TestAsiLauncherPrecedence() { CHECK(r.provider == "WrongGPU Model K" && EndsWith(r.options, "model=K") && CountLog("model choice conflict") == 1); // the launcher's K newer than the plugin's L r = RunAsi("[fsr]\nruntime_options = model=K\nmodel_chosen = 4000\n", 'L', 1, 3000); - CHECK(r.provider == "WrongGPU Model K" && CountLog("the launcher's choice wins (the more recent explicit choice): Model K runs") == 1); + CHECK(r.provider == "WrongGPU Model K" && CountLog("the launcher's choice wins (the most recent explicit choice): Model K runs") == 1); #endif #else // A front end without Model K: the launcher's model=K is dropped at start-up (IgnoreModelK, its own note): Model M. @@ -3646,6 +3822,7 @@ int main() { TestAsiPluginNotHooked(); TestAsiPluginPresetK(); TestAsiLauncherPrecedence(); + TestAsiFfxIndexChoice(); { Config profile; const auto original = profile.BackendOptions(); diff --git a/clean/installer/src/app/cli.cpp b/clean/installer/src/app/cli.cpp index c7857fb0..72d81bd6 100644 --- a/clean/installer/src/app/cli.cpp +++ b/clean/installer/src/app/cli.cpp @@ -814,10 +814,12 @@ int Verb(const wstring& verb, const Args& a, Output& o) { if (!LoadRecord(RecordPath(dir), m) || m.legacy) { o.j.S("error", L"WrongGPU is not installed in " + dir); Print(L"WrongGPU is not installed in " + dir); return EXIT_NOT_INSTALLED; } Profile p = GameProfile(dir); std::vector> optiEdits; + bool modelGiven = false; // a model= item: the player's explicit model choice if (verb == L"set") { for (size_t i = 1; i < a.pos.size(); ++i) { const wstring& kv = a.pos[i]; const size_t eq = kv.find(L'='); + if (eq != wstring::npos && IEq(kv.substr(0, eq), L"model")) modelGiven = true; wstring why; if (eq == wstring::npos) why = L"use key=value: " + kv; else if (StartsWithI(kv, L"opti.")) { // an OptiScaler.ini key (the OptiScaler tab): checked when applied @@ -838,6 +840,7 @@ int Verb(const wstring& verb, const Args& a, Output& o) { if (NeedsElevation(dir)) { o.j.S("error", L"administrator permission is needed for " + dir); Print(L"administrator permission is needed for " + dir); return EXIT_REFUSED; } OpLogBegin(); OpRequest r; r.op = Op::Apply; r.dir = dir; r.hasProfile = true; r.profile = p; r.optiEdits = optiEdits; + r.modelChosen = modelGiven; // set model=: the player's explicit model choice, stamped (also the same model) Ui ui; ui.step = [](int, int, const wstring&) {}; ui.log = [](const wstring& s) { LogLine(g.ctx, s); }; const OpResult res = RunOp(g.ctx, r, ui); OpLogEnd(); diff --git a/clean/installer/src/wg_core/launcher.cpp b/clean/installer/src/wg_core/launcher.cpp index 61a1a01d..f2f2fab9 100644 --- a/clean/installer/src/wg_core/launcher.cpp +++ b/clean/installer/src/wg_core/launcher.cpp @@ -750,7 +750,8 @@ Profile GameProfile(const wstring& dir) { return p; } -void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vector& notes, std::vector* warnings) { +void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vector& notes, std::vector* warnings, + bool modelChosen) { Record m; if (!LoadRecord(RecordPath(dir), m) || m.legacy) Fail(L"WrongGPU is not installed in " + dir + L".", EXIT_NOT_INSTALLED); InferOwners(ctx, m); @@ -783,7 +784,9 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto JournalChanges(m.inikeys, name, in, out); recordChanged = recordChanged || out != in; } - else if (!RenderWronggpuIni(q, in, out, &why)) Fail(L"Settings not applied: " + why, EXIT_USAGE); + // (a model the files cannot run yet, written as Model M above, is not stamped as the player's choice) + else if (!RenderWronggpuIni(q, in, out, &why, 0, modelChosen && q.get("model") == p.get("model"))) + Fail(L"Settings not applied: " + why, EXIT_USAGE); if (out == in && (had || out.empty())) return; // unchanged, or nothing to write into a missing file WriteFileAtomic(path, out.data(), out.size()); const wstring h = Sha256Bytes(out.data(), out.size()); @@ -1151,7 +1154,8 @@ OpResult RunOp(Context& ctx, const OpRequest& r, Ui& ui) { Fail(wstring(L"Model ") + chosen + L" can't be chosen. " + ModelNotReady(chosen, why) + L" Nothing was changed.", EXIT_NO_MODEL); } } - if (!r.optiOnly) ApplyProfile(ctx, r.dir, r.hasProfile ? r.profile : GameProfile(r.dir), res.notes, &res.warnings); + if (!r.optiOnly) + ApplyProfile(ctx, r.dir, r.hasProfile ? r.profile : GameProfile(r.dir), res.notes, &res.warnings, r.hasProfile && r.modelChosen); ApplyOptiTab(ctx, r.dir, r, res.notes); res.message = L"Settings applied; they take effect the next time the game starts"; break; diff --git a/clean/installer/src/wg_core/launcher.h b/clean/installer/src/wg_core/launcher.h index 4b9d91a3..94edce5d 100644 --- a/clean/installer/src/wg_core/launcher.h +++ b/clean/installer/src/wg_core/launcher.h @@ -180,6 +180,7 @@ struct OpRequest { std::vector> movePluginsList, moveModsList; bool otherSetupOk = false; // 0.6.1: Clean up / Adopt of WrongGPU files another mod's setup uses, confirmed (--confirm-other-setup) bool hasProfile = false; // apply: this profile (else the game's profile.ini); install: the profile a new install starts with + bool modelChosen = false; // apply: the player explicitly applied the profile's model (set model=...): stamped Profile profile; // apply, the OptiScaler tab: edits of editable keys ("Section.Key", value); reset: the editable keys back to what the // install wrote (inikey journal, byte for byte); keep: values OptiScaler's menu saved over the launcher's are kept. @@ -210,7 +211,10 @@ bool NeedsElevation(const wstring& dir); // Writes the profile into the game's files (wronggpu.ini, OptiScaler.ini), the record's hashes of those files and // owned-files.json; saves profile.ini. // warnings: what could not be done that the player should hear (rr_config_fix: the game's Engine.ini, rrconfig.h). -void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vector& notes, std::vector* warnings = nullptr); +// modelChosen: the player explicitly applied the profile's model (`set model=`): wronggpu.ini's model_chosen is +// stamped now even when the model is the same (profile.h RenderWronggpuIni). +void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vector& notes, std::vector* warnings = nullptr, + bool modelChosen = false); Profile GameProfile(const wstring& dir); // profile.ini, else the profile its wronggpu.ini implies // The OptiScaler tab: reset / keep / edits of OpRequest written into the installed OptiScaler.ini with the inikey // journal in the record. Nothing to do: no change. diff --git a/clean/installer/src/wg_core/profile.cpp b/clean/installer/src/wg_core/profile.cpp index 670e0c3d..918e88ef 100644 --- a/clean/installer/src/wg_core/profile.cpp +++ b/clean/installer/src/wg_core/profile.cpp @@ -4,7 +4,7 @@ #include #include -#include +#include #include "record.h" #include "settings.h" @@ -284,7 +284,12 @@ std::map EffectiveSettings(const string& wronggpuIni, const stri return eff; } -bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* why, uint64_t now) { +uint64_t NowFileTime() { + using namespace std::chrono; + return uint64_t(duration_cast(system_clock::now().time_since_epoch()).count() / 100) + 116444736000000000ull; +} + +bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* why, uint64_t now, bool modelChosen) { for (auto& d : kSettings) { if (!ValidateSetting(d, p.get(d.key), nullptr, why)) return false; } @@ -322,10 +327,10 @@ bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* if (FindSetting("model")) { auto isModel = [](const std::pair& kv) { return LowerA(kv.first) == "model"; }; const string want = p.get("model"); - if (want == "l" || want == "k") { + if (want == "l" || want == "k" || (modelChosen && want == "m")) { // (Model M explicitly applied: model=M last) std::vector> kept; for (auto& kv : items) if (!isModel(kv)) kept.push_back(kv); - kept.push_back({"model", want == "k" ? "K" : "L"}); + kept.push_back({"model", want == "k" ? "K" : want == "l" ? "L" : "M"}); items = kept; } else { for (auto& kv : items) { @@ -338,15 +343,17 @@ bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* const string joined = JoinOptions(items); // the line is rewritten only when its items change (a player's spacing and comment stay otherwise) if (hadOptions ? joined != JoinOptions(SplitOptions(options)) : !joined.empty()) text = IniSet(text, hadOptions ? section : "fsr", "runtime_options", joined); - // the model choice's time (profile.h): written when the model the front end runs changes, for any model letter + // the model choice's time (profile.h): written when the model the front end runs changes, for any model letter, and + // when the player explicitly applied a model (also the same one again) auto lastModel = [](const string& opts) { string m; for (auto& kv : SplitOptions(opts)) if (LowerA(kv.first) == "model") m = LowerA(TrimA(kv.second)); return m; }; const string modelBefore = hadOptions ? lastModel(options) : string(), modelAfter = lastModel(joined); - if (modelAfter != modelBefore && !modelAfter.empty()) - text = IniSet(text, hadOptions ? section : "fsr", "model_chosen", std::to_string(now ? now : uint64_t(std::time(nullptr)))); + if (!modelAfter.empty() && (modelAfter != modelBefore || modelChosen)) + text = IniSet(text, hadOptions ? section : "fsr", "model_chosen", + std::to_string(now ? now : NowFileTime())); out = text; return true; } diff --git a/clean/installer/src/wg_core/profile.h b/clean/installer/src/wg_core/profile.h index f2129a78..fb2eb8c3 100644 --- a/clean/installer/src/wg_core/profile.h +++ b/clean/installer/src/wg_core/profile.h @@ -75,11 +75,16 @@ std::map EffectiveSettings(const string& wronggpuIni, const stri // runtime items removed from runtime_options (and their own lines) and the non-default ones appended in a fixed // order; unmanaged items and every other line stay as they are. OptiScaler keys only where the key already exists. // false with *why when a profile value does not validate (nothing is rendered then). -// When the rendering changes the last model item of runtime_options (the model the front end runs), it also writes -// model_chosen = `now` (seconds since 1970 UTC; 0: the current time) in that section: the time of the launcher's model -// choice, which the front end weighs against the OptiScaler menu plugin's saved choice (clean/fsr/src/model_precedence.h: -// the more recent explicit choice wins). An unchanged model item leaves model_chosen as it is. -bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* why, uint64_t now = 0); +// When the rendering changes the last model item of runtime_options (the model the front end runs), or `modelChosen` +// says the player explicitly applied a model (also the same one again; Model M then becomes the last model item), it +// also writes model_chosen = `now` (Windows FILETIME, 100 ns since 1601 UTC; 0: the current time) in that section: the +// time of the launcher's model choice, which the front end weighs against the OptiScaler side's choices (the plugin's +// menu, the entry picked in OptiScaler's FFX box; clean/fsr/src/model_precedence.h: the most recent explicit choice +// wins; a tie goes to the launcher). Otherwise an unchanged model item leaves +// model_chosen as it is (another setting applied is not a model choice). +bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* why, uint64_t now = 0, bool modelChosen = false); +// The current time in Windows FILETIME units (100 ns since 1601-01-01 UTC), the unit every model choice is stamped in. +uint64_t NowFileTime(); bool RenderOptiIni(const Profile& p, const string& in, string& out, std::vector* notes = nullptr); // The profile a 0.5.x install implies: the effective values of its wronggpu.ini and OptiScaler.ini (defaults and the // stale defaults of earlier versions dropped; upscaler=standin counts as on). Only keys of the settings schema diff --git a/clean/installer/tests/model_choice_k_tests.cpp b/clean/installer/tests/model_choice_k_tests.cpp index eeae276f..b9a284f8 100644 --- a/clean/installer/tests/model_choice_k_tests.cpp +++ b/clean/installer/tests/model_choice_k_tests.cpp @@ -23,10 +23,10 @@ Profile With(const char* model) { if (!SetSetting(p, "model", model, &why)) throw std::runtime_error("test setup: model"); return p; } -string Wini(const Profile& p, const string& in) { +string Wini(const Profile& p, const string& in, uint64_t now = 0, bool chosen = false) { string out; wstring why; - if (!RenderWronggpuIni(p, in, out, &why)) throw std::runtime_error("test setup: render"); + if (!RenderWronggpuIni(p, in, out, &why, now, chosen)) throw std::runtime_error("test setup: render"); return out; } string Oini(const Profile& p, const string& in, std::vector* notes = nullptr) { @@ -71,6 +71,13 @@ int main() { toK.find("upscaler = network") != string::npos && toK.find("# WrongGPU settings") != string::npos, "Model K: the model item is model=K; the other lines stay"); require(Wini(With("k"), toK) == toK, "Model K again: unchanged (the line is rewritten only when its items change)"); + // #213 review P1: Model K applied again by the player (set model=K): model_chosen = the new time + const string kAt1000 = Wini(With("k"), fresh, 1000); + const string kAt3000 = Wini(With("k"), kAt1000, 3000, true); + require(kAt1000.find("model_chosen=1000\r\n") != string::npos && kAt3000.find("model_chosen=3000\r\n") != string::npos && + kAt3000.find("model_chosen=1000") == string::npos && kAt3000.find("runtime_options=model=K\r\n") != string::npos, + "Model K applied again: stamped again (the newest choice), the model item unchanged"); + require(Wini(With("k"), kAt1000, 3000) == kAt1000, "Model K kept by an apply that is not a model choice: not stamped"); const string mixed = "[fsr]\r\nruntime_options = model=M;timing_log=1;model=L\r\n"; require(Wini(With("k"), mixed).find("runtime_options=timing_log=1;model=K\r\n") != string::npos, "Model K: every model item out (an L item too), model=K last (the last one wins); timing_log kept"); diff --git a/clean/installer/tests/model_choice_tests.cpp b/clean/installer/tests/model_choice_tests.cpp index bc6a72d7..332d0d2e 100644 --- a/clean/installer/tests/model_choice_tests.cpp +++ b/clean/installer/tests/model_choice_tests.cpp @@ -22,10 +22,10 @@ Profile With(const char* model) { if (!SetSetting(p, "model", model, &why)) throw std::runtime_error("test setup: model"); return p; } -string Wini(const Profile& p, const string& in, uint64_t now = 0) { +string Wini(const Profile& p, const string& in, uint64_t now = 0, bool chosen = false) { string out; wstring why; - if (!RenderWronggpuIni(p, in, out, &why, now)) throw std::runtime_error("test setup: render"); + if (!RenderWronggpuIni(p, in, out, &why, now, chosen)) throw std::runtime_error("test setup: render"); return out; } string Oini(const Profile& p, const string& in, std::vector* notes = nullptr) { @@ -90,6 +90,19 @@ int main() { require(Wini(With("l"), "[fsr]\r\nupscaler = network\r\n", 7000).find("model_chosen=7000") != string::npos, "a file without runtime_options gets model=L and model_chosen"); require(Wini(With("l"), fresh).find("model_chosen=") != string::npos, "now = 0: the current time is written"); + // #213 review P1: the player explicitly applies the SAME model again (set model=...): stamped again, newest + const string againL = Wini(With("l"), toLt, 3000, true); + require(againL.find("model_chosen=3000\r\n") != string::npos && againL.find("model_chosen=1000") == string::npos && + againL.find("runtime_options=model=L\r\n") != string::npos, + "Model L applied again by the player: model_chosen = the new time (the model item unchanged)"); + const string chosenM = Wini(DefaultProfile(), fresh, 3000, true); + require(chosenM.find("model_chosen=3000\r\n") != string::npos && chosenM.find("runtime_options = model=M ; the model\r\n") != string::npos, + "Model M explicitly applied on the installer's file: its model=M line kept as it is, stamped (an explicit M, not the default)"); + const string againM = Wini(DefaultProfile(), chosenM, 4000, true); + require(againM.find("model_chosen=4000\r\n") != string::npos && againM.find("model_chosen=3000") == string::npos, + "Model M applied again: stamped again"); + require(Wini(DefaultProfile(), chosenM, 5000) == chosenM, "another apply that is not a model choice: model_chosen stays"); + require(NowFileTime() > 133000000000000000ull, "NowFileTime: FILETIME units (100 ns since 1601), after 2022"); // ---- OptiScaler.ini: the entry OptiScaler starts with ----------------------------------------------------------- const string L = kModelLEntryIndex; diff --git a/clean/installer/tests/run_model_k_tests.py b/clean/installer/tests/run_model_k_tests.py index 105f23ca..3a9dd447 100644 --- a/clean/installer/tests/run_model_k_tests.py +++ b/clean/installer/tests/run_model_k_tests.py @@ -25,7 +25,7 @@ sys.path.insert(0, HERE) import run_model_l_tests as ml # noqa: E402 (T, the Model L case and the install helpers; it sets WRONGGPU_TESTING) from run_installer_tests import read, write # noqa: E402 -from run_model_l_tests import m_case, l_case, recorded_hash, suite, suite_options_model, upscaler_index # noqa: E402 +from run_model_l_tests import m_case, l_case, recorded_hash, suite, suite_options_model, upscaler_index, no_stamp, stamp # noqa: E402 def k_case(): @@ -76,12 +76,13 @@ def test_choice(t): t.check("...profile.ini says model=k", b"model=k\r\n" in profile_text(b)) k_w, k_o = read(wini), read(oini) rc = t.run("set", exe, "model=K") - t.check("set model=K again: nothing changes", rc == 0 and read(wini) == k_w and read(oini) == k_o, rc) + t.check("set model=K again: only model_chosen changes (stamped again: the newest choice)", + rc == 0 and no_stamp(read(wini)) == no_stamp(k_w) and read(oini) == k_o and stamp(read(wini)) > stamp(k_w) > 0, rc) rc = t.run("get", exe, "model") t.check("get model: k", rc == 0 and t.j.get("settings", {}).get("model", {}).get("profile") == "k", t.j.get("settings")) rc = t.run("set", exe, "model=M") - t.check("set model=M: wronggpu.ini and OptiScaler.ini back byte for byte as the install wrote them", - rc == 0 and read(wini) == m_w and read(oini) == m_o, (rc, read(wini)[-200:], read(oini)[-200:])) + t.check("set model=M: wronggpu.ini (but its model_chosen line) and OptiScaler.ini back byte for byte as the install wrote them", + rc == 0 and no_stamp(read(wini)) == no_stamp(m_w) and read(oini) == m_o and stamp(read(wini)) > 0, (rc, read(wini)[-200:], read(oini)[-200:])) t.check("...profile.ini has no model line again", b"model=" not in profile_text(b)) # the Model L control: unchanged by the K choice (its entry follows Model K's, so it is 2) lsrc = os.path.join(t.work, "l-source", "nvngx_dlss.dll") @@ -97,7 +98,8 @@ def test_choice(t): upscaler_index(read(oini).decode("utf-8", "replace")) == "1", (rc, t.j.get("message"))) rc = t.run("set", exe, "model=L") rc2 = t.run("set", exe, "model=M") - t.check("K to L to M: back byte for byte as the install wrote them", rc == 0 and rc2 == 0 and read(wini) == m_w and read(oini) == m_o, (rc, rc2)) + t.check("K to L to M: back byte for byte as the install wrote them (but model_chosen)", + rc == 0 and rc2 == 0 and no_stamp(read(wini)) == no_stamp(m_w) and read(oini) == m_o, (rc, rc2)) # a game saved on K whose data goes away: a repair keeps the player's choice, the files say Model M with a warning rc = t.run("set", exe, "model=K") os.remove(os.path.join(t.lad, "WrongGPU", "model", "K", "model.wgcm")) diff --git a/clean/installer/tests/run_model_l_tests.py b/clean/installer/tests/run_model_l_tests.py index 5871717e..3a35555f 100644 --- a/clean/installer/tests/run_model_l_tests.py +++ b/clean/installer/tests/run_model_l_tests.py @@ -224,10 +224,27 @@ def recorded_hash(b, name): return None +def no_stamp(data): + """wronggpu.ini without its model_chosen line: the launcher stamps every explicit model choice (also the same model + again, and Model M), so `set model=...` changes that line and nothing else of a file that already says the model.""" + kept = b"".join(l for l in data.splitlines(True) if not l.replace(b" ", b"").lower().startswith(b"model_chosen=")) + return kept.rstrip(b"\r\n") # (appending the line may give a file that had no final line end one) + + +def stamp(data): + """wronggpu.ini's model_chosen value (FILETIME units), 0 without one.""" + for l in data.splitlines(): + k, _, v = l.replace(b" ", b"").partition(b"=") + if k.lower() == b"model_chosen" and v.isdigit(): + return int(v) + return 0 + + def test_choice(t): """The launcher's Model L choice (a build with WRONGGPU_MODEL_L on and the test map): set model=L/M on an installed game. L only with Model L's data on this PC; it writes wronggpu.ini's model item and OptiScaler's UpscalerIndex, the - record's hashes follow (the file-ownership rule); M puts both files back byte for byte; uninstall restores the game.""" + record's hashes follow (the file-ownership rule); M puts both files back as the install wrote them (wronggpu.ini then + also has model_chosen, the time of the player's explicit model choice); uninstall restores the game.""" print("\n[3] the model choice: set model=L / model=M (a build with the choice on)") import run_launcher_tests as rl # (its game and OptiScaler fixtures: names and synthetic bytes only) t.model = m_case() # rl.game() writes t.model.file as the game's DLSS file (this hides T.model, the path helper) @@ -260,9 +277,15 @@ def test_choice(t): recorded_hash(b, "wronggpu.ini") == hashlib.sha256(read(wini)).hexdigest() and recorded_hash(b, "OptiScaler.ini") == hashlib.sha256(read(oini)).hexdigest(), (recorded_hash(b, "wronggpu.ini"), recorded_hash(b, "OptiScaler.ini"))) t.check("...profile.ini says model=l", b"model=l\r\n" in read(os.path.join(b, "wronggpu-setup", "profile.ini"))) + l_stamp = stamp(read(wini)) + t.check("...wronggpu.ini has model_chosen (the time of the choice, FILETIME units)", l_stamp > 133000000000000000, read(wini)) + rc = t.run("set", exe, "model=L") + t.check("set model=L again: model_chosen stamped again (the newest choice), nothing else changes", + rc == 0 and stamp(read(wini)) > l_stamp and suite_options_model(read(wini).decode("utf-8", "replace")) == "L", (rc, read(wini))) rc = t.run("set", exe, "model=M") - t.check("set model=M: wronggpu.ini and OptiScaler.ini back byte for byte as the install wrote them", - rc == 0 and read(wini) == m_w and read(oini) == m_o, (rc, read(wini)[-200:], read(oini)[-200:])) + t.check("set model=M: wronggpu.ini (but its model_chosen line) and OptiScaler.ini back byte for byte as the install wrote them", + rc == 0 and no_stamp(read(wini)) == no_stamp(m_w) and read(oini) == m_o and stamp(read(wini)) > l_stamp, + (rc, read(wini)[-200:], read(oini)[-200:])) t.check("...profile.ini has no model line again", b"model=" not in read(os.path.join(b, "wronggpu-setup", "profile.ini"))) # a game saved on L whose data goes away: a repair keeps the player's choice, the files say Model M with a warning rc = t.run("set", exe, "model=L") From b398cb59d238a102c0a06b7195632e0ceee171b7 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:51:02 -0500 Subject: [PATCH 04/15] Model choice: one seq record per game instead of three clocks Review of #213 (second round): the three-clock design lost or fabricated choices in OptiScaler's FFX box, could be locked out by a clock set back, wrote its files in place and parsed timestamps without overflow checks. Replaced as the architect decided: - One record per game, wronggpu-setup\model-choice.ini next to wronggpu.ini (the launcher's state folder; an uninstall removes it by name, a reinstall keeps it with the game's settings): model, seq, source (launcher|ffx|plugin) and ffx (the WrongGPU entry the writer knew OptiScaler's list to name). The highest seq is the most recent choice; no clock anywhere. - Writers: the launcher when it applies a model (explicit `set ... model=`, or a changed model item; it sets OptiScaler's entry with it and writes ffx = that entry), the front end when OptiScaler's FFX box names an entry the record does not know (also at the first create without a record), the menu plugin on a click on one of its model entries (keeping the record's ffx). The launcher's own index rewrite is never taken for a choice in the game. - Atomic writes: a temporary file in the same folder, flushed, renamed over the record through its handle with POSIX semantics (MoveFileExW REPLACE_EXISTING | WRITE_THROUGH as the fallback), checked, retried; a reader never sees part of a record, a stale temporary file is never read. - Strict parsing: exactly the four keys once, seq a checked uint64 (overflow refused), model in M/K/L; anything else is corrupt, logged and treated as no record. An unreadable record is never written over. - Without a record: the launcher's K/L item, else the plugin's saved entry, else Model M. The plugin's AMD entry still means AMD; a launcher model choice selects WrongGPU there again. - Removed: model_chosen, chosen= stamps, wronggpu-ffx-choice.ini, WrongGpuAsiQueryChoiceV1; the plugin gets WrongGpuAsiSetChoiceRecordV1. Tests on real files: strict format and overflow, seq order, the FFX rule, each source winning in turn, the launcher's index rewrite, the first create, a stale temporary file, corrupt and locked records, a reader racing 400 replacements; Model K / L launcher end-to-end tests check the record. Negative controls for the FFX rule, the overflow check, the unreadable rule and the atomic write. Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/fsr/CMakeLists.txt | 6 +- clean/fsr/asi/README.md | 34 +- clean/fsr/asi/asi_abi.h | 27 +- clean/fsr/asi/asi_thunk.h | 97 +--- clean/fsr/asi/exports_asi.def | 2 +- clean/fsr/asi/wronggpu_asi.cpp | 112 ++-- clean/fsr/src/asi_bridge.cpp | 53 +- clean/fsr/src/asi_bridge.h | 16 +- clean/fsr/src/config.cpp | 4 - clean/fsr/src/config.h | 3 - clean/fsr/src/dllmain.cpp | 23 +- clean/fsr/src/frontend.cpp | 152 +++--- clean/fsr/src/frontend.h | 34 +- clean/fsr/src/model_choice_record.h | 294 +++++++++++ clean/fsr/src/model_precedence.h | 172 ------ clean/fsr/tests/test_asi_status.cpp | 26 +- clean/fsr/tests/test_asi_thunk.cpp | 67 +-- clean/fsr/tests/test_frontend.cpp | 492 +++++------------- clean/fsr/tests/test_model_choice_record.cpp | 197 +++++++ clean/installer/src/wg_core/launcher.cpp | 53 +- clean/installer/src/wg_core/launcher.h | 10 +- clean/installer/src/wg_core/profile.cpp | 46 +- clean/installer/src/wg_core/profile.h | 16 +- clean/installer/src/wg_core/record.cpp | 9 +- .../installer/tests/model_choice_k_tests.cpp | 29 +- clean/installer/tests/model_choice_tests.cpp | 45 +- clean/installer/tests/run_model_k_tests.py | 17 +- clean/installer/tests/run_model_l_tests.py | 46 +- 28 files changed, 1047 insertions(+), 1035 deletions(-) create mode 100644 clean/fsr/src/model_choice_record.h delete mode 100644 clean/fsr/src/model_precedence.h create mode 100644 clean/fsr/tests/test_model_choice_record.cpp diff --git a/clean/fsr/CMakeLists.txt b/clean/fsr/CMakeLists.txt index df25e8a8..5af83945 100644 --- a/clean/fsr/CMakeLists.txt +++ b/clean/fsr/CMakeLists.txt @@ -138,6 +138,9 @@ add_test(NAME fsr_asi_thunk_unit COMMAND test_asi_thunk) add_executable(test_asi_thunk_kl tests/test_asi_thunk.cpp) target_compile_definitions(test_asi_thunk_kl PRIVATE WRONGGPU_MODEL_K_OVERRIDE=1 WRONGGPU_MODEL_L=1) add_test(NAME fsr_asi_thunk_kl_unit COMMAND test_asi_thunk_kl) +# The game's model choice record (src/model_choice_record.h) on real files in the temporary folder. +add_executable(test_model_choice_record tests/test_model_choice_record.cpp) +add_test(NAME fsr_model_choice_record_unit COMMAND test_model_choice_record) add_executable(test_asi_patch tests/test_asi_patch.cpp) add_test(NAME fsr_asi_patch_unit COMMAND test_asi_patch) add_executable(test_asi_lifetime tests/test_asi_lifetime.cpp) @@ -146,7 +149,7 @@ add_executable(test_asi_scan tests/test_asi_scan.cpp) add_test(NAME fsr_asi_scan_unit COMMAND test_asi_scan) set_tests_properties(fsr_asi_scan_unit PROPERTIES SKIP_RETURN_CODE 77) if(MSVC) - set_property(TARGET test_asi_thunk test_asi_thunk_kl test_asi_scan test_asi_patch test_asi_lifetime PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + set_property(TARGET test_asi_thunk test_asi_thunk_kl test_model_choice_record test_asi_scan test_asi_patch test_asi_lifetime PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") endif() if(WIN32) @@ -172,6 +175,7 @@ if(WIN32) target_link_options(test_fsr30 PRIVATE ${WG_STATIC_RUNTIME}) target_link_options(test_asi_thunk PRIVATE ${WG_STATIC_RUNTIME}) target_link_options(test_asi_thunk_kl PRIVATE ${WG_STATIC_RUNTIME}) + target_link_options(test_model_choice_record PRIVATE ${WG_STATIC_RUNTIME}) target_link_options(test_asi_scan PRIVATE ${WG_STATIC_RUNTIME}) target_link_options(test_asi_patch PRIVATE ${WG_STATIC_RUNTIME}) target_link_options(test_asi_lifetime PRIVATE ${WG_STATIC_RUNTIME}) diff --git a/clean/fsr/asi/README.md b/clean/fsr/asi/README.md index dba8152b..b6ee3136 100644 --- a/clean/fsr/asi/README.md +++ b/clean/fsr/asi/README.md @@ -21,24 +21,20 @@ What the front end does with the plugin's entry (`src/frontend.cpp`, `TestAsiPlu whatever the FFX box names; "FSR 3.X(/4)" runs AMD: the AMD version the FFX box names, else AMD's newest listed version. The FFX box's list is the same with and without the plugin (WrongGPU first). -Which model runs (0.6.5, `src/model_precedence.h`, `TestAsiLauncherPrecedence`, `TestAsiFfxIndexChoice`): three places -can choose, each with the time it was chosen in Windows FILETIME units (100 ns since 1601 UTC): -- the launcher: the last `model=` item of wronggpu.ini's `runtime_options` and `model_chosen=`, written whenever the - launcher changes that item and whenever the player explicitly applies a model, also the same one again - (`WrongGPU.exe set model=`); -- OptiScaler's FFX upscaler box: the WrongGPU entry picked there (the version id OptiScaler passes with each create). The - front end saves the entry it saw in `wronggpu-ffx-choice.ini` next to wronggpu.ini and stamps the time when it sees a - different one; the first entry it ever sees is saved untimed; -- the plugin's menu: `selection=` and `chosen=` in `wronggpu-asi.ini`, written on every click. - -A choice is a *default* when nobody made it (no file, or Model M with no time; an untimed FFX entry). The most recent -explicit choice wins; an untimed explicit choice (a file of an earlier version) counts as the oldest; on an exact tie the -launcher wins, then the FFX box, then the plugin's menu. Explicit choices naming different models are a conflict: the -front end logs one `model choice conflict:` line naming each with its time and the winner with the reason. The front end -tells the plugin which model runs (`WrongGpuAsiShowModelV1`), so the menu marks that entry. Model L's own entry -("WrongGPU Model L") is in the menu of a build with `WG_MODEL_L`; a model the front end was built without runs as Model M, -with a note in the log. Known limit: the order follows the PC's clock; a clock set back between two choices can order -them wrongly. +Which model runs (0.6.5, `src/model_choice_record.h`, `TestAsiChoiceRecord`, `tests/test_model_choice_record.cpp`): the +plugin's entry says WrongGPU or AMD; which WrongGPU model is the game's **model choice record**, +`wronggpu-setup\model-choice.ini` next to wronggpu.ini (the launcher's state folder). It holds one record: `model=`, +`seq=`, `source=` (launcher, ffx or plugin) and `ffx=` (the WrongGPU entry the writer knew OptiScaler's list to name). +Three places write it, each with the record's seq + 1, so the highest seq is the most recent choice and no clock is +involved: the launcher when it applies a model (it sets OptiScaler's entry with it and writes `ffx` = that entry), the +front end when OptiScaler's FFX box names a WrongGPU entry the record does not know (the player picked it there; also at +the first create when there is no record yet), and this plugin when the player clicks one of its model entries (it keeps +the record's `ffx`, so the unchanged FFX box is never taken for a new choice). Writes are atomic (a temporary file in +the same folder, flushed, renamed over the record); parsing is strict, and a corrupt record counts as no record. Without +a record the launcher's Model K / L item decides, else the plugin's saved entry, else Model M. The front end logs the +model and which choice decided, one line when the record and wronggpu.ini's model item disagree, and tells the plugin +which model runs (`WrongGpuAsiShowModelV1`), so the menu marks that entry. Model L's own entry ("WrongGPU Model L") is in +the menu of a build with `WG_MODEL_L`; a model the front end was built without runs as Model M, with a note in the log. ## How it works @@ -61,7 +57,7 @@ them wrongly. 4. WrongGPU's front end (`amd_fidelityfx_dx12.dll`) finds the plugin by module and asks it (`WrongGpuAsiQuery`, `asi_abi.h`) which model is selected. The FFX list always starts with WrongGPU entries followed by AMD entries; when hooked, the front end creates Model M / K / L or AMD from the plugin's selection weighed against the launcher's - model choice (`WrongGpuAsiQueryChoiceV1`; see "Which model runs" above). + model choice (the model choice record; see "Which model runs" above). If a required anchor is missing or ambiguous, or a stub cannot be placed, nothing is patched and the plugin reports "not hooked". Call sites are prepared and revalidated before publication. A failed write rolls back sites whose diff --git a/clean/fsr/asi/asi_abi.h b/clean/fsr/asi/asi_abi.h index 6b60ed15..443b7cef 100644 --- a/clean/fsr/asi/asi_abi.h +++ b/clean/fsr/asi/asi_abi.h @@ -4,6 +4,7 @@ // entry the player selected in OptiScaler's menu. The front end finds the plugin by module (GetModuleHandle of the // plugin file name) and resolves this one export by name, so load order does not matter and neither DLL links the // other. Defined once, shared by the plugin (which exports it) and the front-end bridge (which calls it). +#include #include #define WRONGGPU_ASI_MODULE L"WrongGPU.asi" @@ -13,7 +14,8 @@ // Query result. `hooked` is 1 after the prepared menu call-patch transaction commits; it does not promise // complete menu adaptation. The FFX list still contains WrongGPU and AMD entries. Zero means inactive: the // front end then behaves as if no plugin were present. `model` is 0 (OptiScaler's own FSR 3.X / AMD), 'M' or 'K' -// (a saved Model L reads as 'M' here, for an older front end; WrongGpuAsiQueryChoiceV1 below reports it). Returns the ABI version (>= 1), or 0 on error. Signature: int WrongGpuAsiQuery(int* hooked, char* model). +// (a saved Model L reads as 'M' here, for an older front end; which WrongGPU model runs is the model choice +// record's, src/model_choice_record.h). Returns the ABI version (>= 1), or 0 on error. Signature: int WrongGpuAsiQuery(int* hooked, char* model). typedef int (*PfnWrongGpuAsiQuery)(int* hooked, char* model); // Additive WrongGPU-owned diagnostic API; this is NOT a host plugin or RR frame ABI. @@ -76,24 +78,11 @@ typedef struct WrongGpuAsiStatusV1 { typedef int (*PfnWrongGpuAsiQueryStatusV1)(WrongGpuAsiStatusV1* status, uint32_t caller_size); -// The player's saved choice with what the front end needs to weigh it against the launcher's model choice (0.6.5; -// src/model_precedence.h). model: 0 (AMD), 'M', 'K' or 'L'. explicit_choice: 1 when the player chose it in the menu (or -// a file of an earlier version names a non-default entry), 0 for the default entry (no file, or Model M with no time). -// chosen_at: when the player clicked it, Windows FILETIME (100 ns since 1601-01-01 UTC); 0 = not recorded. Same size/version rules and -// return codes as WrongGpuAsiQueryStatusV1. A front end that finds no such export uses WrongGpuAsiQuery and treats -// Model M as the default entry and K / AMD as explicit choices with no recorded time. -#define WRONGGPU_ASI_CHOICE_QUERY "WrongGpuAsiQueryChoiceV1" -#define WRONGGPU_ASI_CHOICE_VERSION 1u -typedef struct WrongGpuAsiChoiceV1 { - uint32_t size; - uint32_t version; - uint32_t hooked; - uint32_t model; - uint32_t explicit_choice; - uint32_t reserved; - uint64_t chosen_at; -} WrongGpuAsiChoiceV1; -typedef int (*PfnWrongGpuAsiQueryChoiceV1)(WrongGpuAsiChoiceV1* choice, uint32_t caller_size); +// The front end tells the plugin where the game's model choice record is (wronggpu-setup\model-choice.ini next to +// its wronggpu.ini; src/model_choice_record.h). A click on one of the plugin's model entries is written there (seq + 1, +// source=plugin). Without this call the plugin uses wronggpu-setup\model-choice.ini in its own data folder. +#define WRONGGPU_ASI_SET_CHOICE_RECORD "WrongGpuAsiSetChoiceRecordV1" +typedef void (*PfnWrongGpuAsiSetChoiceRecordV1)(const wchar_t* path); // The front end reports which model it runs (0 AMD, 'M', 'K', 'L'), so the plugin's menu marks that entry; 1 returns // to marking the saved choice. Display only: nothing is saved. diff --git a/clean/fsr/asi/asi_thunk.h b/clean/fsr/asi/asi_thunk.h index 3d9e2a8b..4131865b 100644 --- a/clean/fsr/asi/asi_thunk.h +++ b/clean/fsr/asi/asi_thunk.h @@ -6,14 +6,12 @@ // // It writes none of OptiScaler's data. When the player clicks a WrongGPU item, the Selectable thunk returns "clicked" // for OptiScaler's own "FSR 3.X" entry, so OptiScaler's unchanged code sets its backend to FSR 3.X (which loads -// WrongGPU's FidelityFX DLL); the plugin only remembers which entry the player chose (and when), and the front end -// reads that back. The front end decides which model runs (the plugin's choice or the launcher's: frontend -// model_precedence.h) and tells the plugin, so the menu marks the model that actually runs. The WrongGPU labels are -// plain UI text. +// WrongGPU's FidelityFX DLL). The plugin remembers whether WrongGPU or AMD was chosen (wronggpu-asi.ini); a click on a +// WrongGPU model is also written to the game's model choice record (clean/fsr/src/model_choice_record.h), which decides +// the model with the launcher's and OptiScaler's list's choices. The front end reports the model it runs, so the menu +// marks that one. The WrongGPU labels are plain UI text. #include #include -#include -#include #include #include @@ -55,17 +53,12 @@ inline const char* LabelOf(char model) { return nullptr; } -// Shared plugin state. `hooked` is read by the front end through the exported query. `model` is the player's saved -// choice within OptiScaler's FSR 3.X entry; `explicitChoice` says whether the player (or an earlier version's file) -// actually chose it, as opposed to the default entry; `chosenAt` is when the player clicked it (Windows FILETIME: -// 100 ns since 1601-01-01 UTC, 0 = not recorded: a file written before 0.6.5, or by an installer). `shown` is the model the front -// end reported as running (kShowSaved until it reports one): the menu marks that one, so a launcher choice that won -// over the plugin's default is what the player sees checked. +// Shared plugin state. `hooked` is read by the front end through the exported query; `model` is the player's choice +// within OptiScaler's FSR 3.X entry (0: AMD). `shown` is the model the front end reported as running (kShowSaved until +// it reports one): the menu marks that one, so the model the choice record decided is what the player sees checked. struct PluginState { std::atomic hooked{false}; std::atomic model{kDefaultModel}; - std::atomic explicitChoice{false}; - std::atomic chosenAt{0}; std::atomic shown{kShowSaved}; }; @@ -79,14 +72,13 @@ inline bool IsFsr3xLabel(const char* label) { } // The Selectable thunk. `sel` is the real ImGui::Selectable(label, selected, flags, size). For OptiScaler's FSR 3.X -// entry it draws the WrongGPU items first, then the original entry, records any click as the player's explicit choice -// (made at `now`, FILETIME units), and returns true (click) to OptiScaler when any of them was clicked so -// OptiScaler switches to its FSR 3.X backend. `selected` (OptiScaler's backend is FSR 3.X) marks the WrongGPU item or -// the FSR 3.X item of the model shown (ShownModel). Every other entry passes through unchanged. *clickedOut (when -// given) is set to true on a click on one of these items, so the caller saves the choice. +// entry it draws the WrongGPU items first, then the original entry, records any click as the selected model, and +// returns true (click) to OptiScaler when any of them was clicked so OptiScaler switches to its FSR 3.X backend. +// `selected` (OptiScaler's backend is FSR 3.X) marks the item of the model shown (ShownModel). Every other entry passes +// through unchanged. *clickedOut (when given) is set to true on a click on one of these items (the caller saves it). template bool SelectableThunkLogic(SelFn&& sel, const char* label, bool selected, int flags, const void* size, PluginState& st, - uint64_t now = 0, bool* clickedOut = nullptr) { + bool* clickedOut = nullptr) { if (clickedOut) *clickedOut = false; if (!IsFsr3xLabel(label)) return sel(label, selected, flags, size); const char model = ShownModel(st); @@ -96,8 +88,6 @@ bool SelectableThunkLogic(SelFn&& sel, const char* label, bool selected, int fla if (sel(label, selected && model == kModelAmd, flags, size) && clicked == 1) clicked = kModelAmd; if (clicked == 1) return false; st.model.store(clicked); - st.explicitChoice.store(true); - st.chosenAt.store(now); st.shown.store(kShowSaved); // the player's click is the newest choice: it runs and is marked if (clickedOut) *clickedOut = true; return true; @@ -112,20 +102,10 @@ bool BeginComboThunkLogic(BcFn&& bc, const char* label, const char* preview, int return bc(label, preview, flags); } -// The remembered choice (wronggpu-asi.ini next to the plugin): "selection=wronggpu" (Model M), "wronggpu-k", -// "wronggpu-l" or "amd", and since 0.6.5 "chosen=" (100 ns since 1601 UTC), the time of the player's click. -struct Selection { - char model = kDefaultModel; - bool explicitChoice = false; // false: the default entry (no file, no selection line, an unknown value, or - // Model M with no recorded time: what installers write and what 0.6.0 saved for M) - uint64_t chosenAt = 0; // 0: not recorded -}; - -// Anything else, or no file, is the default (WrongGPU Model M, not an explicit choice). A model this build lacks -// (Model K or L) reads as the default too, so the launcher's choice decides. -inline Selection ParseSelectionFile(const std::string& text) { - Selection s; - bool stated = false; +// The remembered entry (wronggpu-asi.ini next to the plugin): "selection=wronggpu" (Model M), "wronggpu-k", "wronggpu-l" +// or "amd". Anything else, or no file, is the default (WrongGPU). A model this build lacks reads as WrongGPU (Model M). +// Which WrongGPU model runs is the model choice record's (model_choice_record.h); this file says WrongGPU or AMD. +inline char ParseSelection(const std::string& text) { size_t at = 0; while (at < text.size()) { size_t end = text.find('\n', at); @@ -134,43 +114,20 @@ inline Selection ParseSelectionFile(const std::string& text) { for (size_t i = at; i < end; ++i) if (!std::isspace(static_cast(text[i]))) line += char(std::tolower(static_cast(text[i]))); at = end + 1; - if (!stated && line.rfind("selection=", 0) == 0) { - stated = true; - const std::string v = line.substr(10); - if (v == "amd") s.model = kModelAmd; - else if (v == "wronggpu-k" && LabelOf(kModelK)) s.model = kModelK; - else if (v == "wronggpu-l" && LabelOf(kModelL)) s.model = kModelL; - else if (v == "wronggpu") s.model = kModelM; - else stated = false; // an unknown entry, or one this build lacks: the default - } else if (line.rfind("chosen=", 0) == 0) { - const std::string v = line.substr(7); - uint64_t t = 0; - bool digits = !v.empty() && v.size() <= 19; - for (char c : v) digits = digits && c >= '0' && c <= '9'; - if (digits) t = std::strtoull(v.c_str(), nullptr, 10); - s.chosenAt = t; - } + if (line.rfind("selection=", 0) != 0) continue; + const std::string v = line.substr(10); + if (v == "amd") return kModelAmd; + if (v == "wronggpu-k") return LabelOf(kModelK) ? kModelK : kModelM; + if (v == "wronggpu-l") return LabelOf(kModelL) ? kModelL : kModelM; + return kDefaultModel; } - if (!stated) return Selection{}; - s.explicitChoice = s.model != kDefaultModel || s.chosenAt != 0; - return s; -} - -// The model alone (the earlier interface). -inline char ParseSelection(const std::string& text) { return ParseSelectionFile(text).model; } - -inline const char* SelectionValue(char model) { - return model == kModelAmd ? "amd" : model == kModelK ? "wronggpu-k" : model == kModelL ? "wronggpu-l" : "wronggpu"; + return kDefaultModel; } -// `chosenAt` 0 writes no time (the default entry's file, as installers write it). -inline std::string FormatSelection(char model, uint64_t chosenAt = 0) { - std::string text = std::string("; WrongGPU OptiScaler plugin: the entry last selected in OptiScaler's upscaler list\r\n") + - "; (wronggpu, wronggpu-k, wronggpu-l or amd) and when (chosen: Windows FILETIME, 100 ns since 1601 UTC).\r\n" - "; Deleting this file selects WrongGPU's default; the launcher's model choice then decides.\r\n" - "selection=" + SelectionValue(model) + "\r\n"; - if (chosenAt) text += "chosen=" + std::to_string(chosenAt) + "\r\n"; - return text; +inline std::string FormatSelection(char model) { + const char* v = model == kModelAmd ? "amd" : model == kModelK ? "wronggpu-k" : model == kModelL ? "wronggpu-l" : "wronggpu"; + return std::string("; WrongGPU OptiScaler plugin: the entry last selected in OptiScaler's upscaler list\r\n") + + "; (wronggpu, wronggpu-k, wronggpu-l or amd). Deleting this file selects WrongGPU.\r\nselection=" + v + "\r\n"; } } // namespace wgasi diff --git a/clean/fsr/asi/exports_asi.def b/clean/fsr/asi/exports_asi.def index 315f0654..fbd2a940 100644 --- a/clean/fsr/asi/exports_asi.def +++ b/clean/fsr/asi/exports_asi.def @@ -4,5 +4,5 @@ EXPORTS InitializeASI WrongGpuAsiQuery WrongGpuAsiQueryStatusV1 - WrongGpuAsiQueryChoiceV1 + WrongGpuAsiSetChoiceRecordV1 WrongGpuAsiShowModelV1 diff --git a/clean/fsr/asi/wronggpu_asi.cpp b/clean/fsr/asi/wronggpu_asi.cpp index 0b1487de..2e2bb89b 100644 --- a/clean/fsr/asi/wronggpu_asi.cpp +++ b/clean/fsr/asi/wronggpu_asi.cpp @@ -2,8 +2,9 @@ // WrongGPU.asi: an OptiScaler plugin (its own DLL, our own code only) that makes WrongGPU appear as its own entry // ("WrongGPU"; with Model K and/or L: "WrongGPU Model M", "WrongGPU Model K", "WrongGPU Model L") in OptiScaler's MAIN // DX12 upscaler dropdown, leaving OptiScaler's "FSR 3.X(/4)" entry to mean AMD's upscaler again. WrongGPU is the default -// entry; the player's choice (and when it was made) is remembered in wronggpu-asi.ini next to the plugin. The front end -// weighs it against the launcher's model choice (src/model_precedence.h) and reports back the model it runs. +// entry; WrongGPU or AMD is remembered in wronggpu-asi.ini next to the plugin, and a click on a model entry is written to +// the game's model choice record (src/model_choice_record.h), which decides the model. The front end reports back the +// model it runs. // // How: OptiScaler calls our exported InitializeASI() after loading us (see its LoadAsiPlugins). The module that // called us is OptiScaler itself (its image holds the menu code), so we identify it by InitializeASI's return @@ -30,6 +31,7 @@ #include "asi_patch.h" #include "asi_status.h" #include "asi_thunk.h" +#include "model_choice_record.h" #include "opti_module.h" #include "opti_resolver.h" @@ -69,47 +71,76 @@ bool PinOwnModule() noexcept { // The remembered choice: wronggpu-asi.ini in PluginDataDir() (asi_thunk.h, ParseSelection / FormatSelection). std::wstring SelectionPath() { return wgasi::PluginDataDir() + L"wronggpu-asi.ini"; } -wgasi::Selection LoadSelection() { +char LoadSelection() { std::string text; - HANDLE h = CreateFileW(SelectionPath().c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, nullptr); + HANDLE h = CreateFileW(SelectionPath().c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (h != INVALID_HANDLE_VALUE) { - char buf[1024]; + char buf[512]; DWORD got = 0; if (ReadFile(h, buf, sizeof buf, &got, nullptr)) text.assign(buf, got); CloseHandle(h); } - return wgasi::ParseSelectionFile(text); + return wgasi::ParseSelection(text); } -// Windows FILETIME units, 100 ns since 1601-01-01 UTC (the launcher and the front end stamp on the same clock and unit). -uint64_t NowFileTime() { - FILETIME ft; - GetSystemTimeAsFileTime(&ft); - return (uint64_t(ft.dwHighDateTime) << 32) | ft.dwLowDateTime; +// The plugin's own file, replaced atomically (a temporary file next to it, flushed, moved over it). +void SaveSelection(char model) { + const std::string text = wgasi::FormatSelection(model); + const std::wstring path = SelectionPath(), tmp = path + L"." + std::to_wstring(GetCurrentProcessId()) + L".tmp"; + HANDLE h = CreateFileW(tmp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + bool ok = false; + if (h != INVALID_HANDLE_VALUE) { + DWORD written = 0; + ok = WriteFile(h, text.data(), DWORD(text.size()), &written, nullptr) && written == text.size() && FlushFileBuffers(h); + CloseHandle(h); + ok = ok && MoveFileExW(tmp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH); + if (!ok) DeleteFileW(tmp.c_str()); + } + if (!ok) AsiLog::Get().Write("wronggpu-asi.ini could not be written (Windows error " + std::to_string(GetLastError()) + ")"); +} + +// The game's model choice record (model_choice_record.h): where the front end said it is (WrongGpuAsiSetChoiceRecordV1), +// else wronggpu-setup\model-choice.ini in PluginDataDir() (the game folder in the launcher's layouts). +std::mutex g_recordMutex; +std::wstring g_recordPath; +std::wstring RecordPath() { + std::lock_guard lock(g_recordMutex); + return g_recordPath.empty() ? wgchoice::RecordPathIn(wgasi::PluginDataDir()).wstring() : g_recordPath; } -void SaveSelection(char model, uint64_t chosenAt) { - const std::string text = wgasi::FormatSelection(model, chosenAt); - HANDLE h = CreateFileW(SelectionPath().c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, nullptr); - if (h == INVALID_HANDLE_VALUE) return; - DWORD written = 0; - WriteFile(h, text.data(), DWORD(text.size()), &written, nullptr); - CloseHandle(h); +// A click on one of the plugin's model entries: the record gets this model with the next seq (source=plugin); the +// entry OptiScaler's list names (ffx) stays what the record knew. +void RecordModelChoice(char model) { + const std::wstring path = RecordPath(); + wgchoice::Record cur, next; + std::string why; + const wgchoice::ReadResult rr = wgchoice::ReadRecordFile(path, &cur, &why); + if (rr == wgchoice::ReadResult::Unreadable) { + AsiLog::Get().Write("model choice record " + wgasi::Utf8(path) + " cannot be read (" + why + "); the click is not recorded"); + return; + } + if (rr == wgchoice::ReadResult::Corrupt) AsiLog::Get().Write("model choice record " + wgasi::Utf8(path) + " is corrupt (" + why + "); replaced"); + if (!wgchoice::NextRecord(rr == wgchoice::ReadResult::Ok ? &cur : nullptr, model, wgchoice::Source::Plugin, wgchoice::kUnknown, &next)) { + AsiLog::Get().Write("model choice record: seq cannot grow; the click is not recorded"); + return; + } + if (wgchoice::WriteRecordFile(path, next, &why)) + AsiLog::Get().Writef("model choice record: Model %c (seq %llu, source=plugin)", model, static_cast(next.seq)); + else + AsiLog::Get().Write("model choice record " + wgasi::Utf8(path) + " could not be written (" + why + ")"); } extern "C" bool WgSelectableThunk(const char* label, bool selected, int flags, const void* size) { bool ours = false; const bool clicked = wgasi::SelectableThunkLogic( [](const char* l, bool s, int f, const void* z) { return g_realSelectable(l, s, f, z); }, - label, selected, flags, size, g_state, NowFileTime(), &ours); - if (ours) { // a click on an entry of the FSR 3.X group: the player's explicit choice, with its time (rare; menu thread) + label, selected, flags, size, g_state, &ours); + if (ours) { // a click on an entry of the FSR 3.X group (rare; on the menu thread) const char after = g_state.model.load(); - const uint64_t at = g_state.chosenAt.load(); - SaveSelection(after, at); - AsiLog::Get().Writef("selected: %s (chosen=%llu)", after == wgasi::kModelAmd ? label : wgasi::LabelOf(after), - static_cast(at)); + SaveSelection(after); + if (after != wgasi::kModelAmd) RecordModelChoice(after); + AsiLog::Get().Writef("selected: %s", after == wgasi::kModelAmd ? label : wgasi::LabelOf(after)); } return clicked; } @@ -232,16 +263,7 @@ void Hook(const void* caller) { g_realBeginCombo = r.beginCombo ? reinterpret_cast(const_cast(optiBase) + r.beginCombo) : nullptr; // Selection I/O and all allocations happen before any call site can enter our thunks. - { - const wgasi::Selection saved = LoadSelection(); - g_state.model.store(saved.model); - g_state.explicitChoice.store(saved.explicitChoice); - g_state.chosenAt.store(saved.chosenAt); - log.Writef("saved choice: %s (%s, chosen=%llu)", - saved.model == wgasi::kModelAmd ? "AMD (FSR 3.X)" : wgasi::LabelOf(saved.model), - saved.explicitChoice ? "explicit" : "default entry: the launcher's model choice decides", - static_cast(saved.chosenAt)); - } + g_state.model.store(LoadSelection()); uint8_t* stubs = AllocNear(optiBase + r.addDx12Lo); if (!stubs) { g_diagnostics.Outcome(WG_ASI_MENU_UNAVAILABLE, WG_ASI_REASON_STUB_ALLOCATION_FAILED); @@ -319,20 +341,10 @@ extern "C" __declspec(dllexport) int WrongGpuAsiQuery(int* hooked, char* model) return int(WRONGGPU_ASI_ABI); } -extern "C" __declspec(dllexport) int WrongGpuAsiQueryChoiceV1(WrongGpuAsiChoiceV1* choice, uint32_t caller_size) { - if (!choice) return WG_ASI_STATUS_INVALID_ARGUMENT; - if (caller_size < sizeof(WrongGpuAsiChoiceV1) || choice->size < sizeof(WrongGpuAsiChoiceV1) || choice->size > caller_size) - return WG_ASI_STATUS_INVALID_SIZE; - if (choice->version != WRONGGPU_ASI_CHOICE_VERSION) return WG_ASI_STATUS_UNSUPPORTED_VERSION; - WrongGpuAsiChoiceV1 v{}; - v.size = sizeof(v); - v.version = WRONGGPU_ASI_CHOICE_VERSION; - v.hooked = g_state.hooked.load() ? 1u : 0u; - v.model = static_cast(g_state.model.load()); - v.explicit_choice = g_state.explicitChoice.load() ? 1u : 0u; - v.chosen_at = g_state.chosenAt.load(); - *choice = v; - return WG_ASI_STATUS_OK; +// The front end tells the plugin where the game's model choice record is (next to its wronggpu.ini). +extern "C" __declspec(dllexport) void WrongGpuAsiSetChoiceRecordV1(const wchar_t* path) { + std::lock_guard lock(g_recordMutex); + g_recordPath = path ? path : L""; } // The front end reports the model it runs (0 AMD, 'M', 'K', 'L'), so the menu marks that one; 1 = the saved choice. diff --git a/clean/fsr/src/asi_bridge.cpp b/clean/fsr/src/asi_bridge.cpp index 275247da..84c86eb2 100644 --- a/clean/fsr/src/asi_bridge.cpp +++ b/clean/fsr/src/asi_bridge.cpp @@ -11,32 +11,16 @@ namespace wgwin { -bool QueryAsiPlugin(wgfsr::PluginModelChoice* choice) { - if (choice) *choice = wgfsr::PluginModelChoice{}; +bool QueryAsiPlugin(char* model) { + if (model) *model = 0; HMODULE m = GetModuleHandleW(WRONGGPU_ASI_MODULE); // present only if OptiScaler loaded our plugin; no reference taken if (!m) return false; - if (auto query = reinterpret_cast(reinterpret_cast(GetProcAddress(m, WRONGGPU_ASI_CHOICE_QUERY)))) { - WrongGpuAsiChoiceV1 c{}; - c.size = sizeof(c); - c.version = WRONGGPU_ASI_CHOICE_VERSION; - if (query(&c, sizeof(c)) != WG_ASI_STATUS_OK) return false; - if (choice) { - choice->model = char(c.model); - choice->explicitChoice = c.explicit_choice != 0; - choice->chosenAt = c.chosen_at; - } - return c.hooked != 0; - } auto query = reinterpret_cast(reinterpret_cast(GetProcAddress(m, WRONGGPU_ASI_QUERY))); if (!query) return false; int hooked = 0; char mdl = 0; if (query(&hooked, &mdl) < int(WRONGGPU_ASI_ABI)) return false; // older/unknown ABI: ignore - if (choice) { // an earlier plugin: its default entry is Model M; any other entry was chosen, at an unknown time - choice->model = mdl; - choice->explicitChoice = mdl != 'M'; - choice->chosenAt = 0; - } + if (model) *model = mdl; return hooked != 0; } @@ -47,32 +31,11 @@ void ShowAsiModel(char model) { show(model); } -static std::wstring FfxChoicePath(const std::wstring& ini) { - const size_t slash = ini.find_last_of(L"\\/"); - return (slash == std::wstring::npos ? std::wstring(L".") : ini.substr(0, slash)) + L"\\wronggpu-ffx-choice.ini"; -} - -bool LoadFfxChoice(const std::wstring& ini, wgfsr::FfxModelChoice* choice) { - HANDLE h = CreateFileW(FfxChoicePath(ini).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, nullptr); - if (h == INVALID_HANDLE_VALUE) return false; - char buf[1024]; - DWORD got = 0; - const bool ok = ReadFile(h, buf, sizeof buf, &got, nullptr) != 0; - CloseHandle(h); - if (!ok) return false; - if (choice) *choice = wgfsr::ParseFfxChoiceFile(std::string(buf, got)); - return true; -} - -void SaveFfxChoice(const std::wstring& ini, const wgfsr::FfxModelChoice& choice) { - const std::string text = wgfsr::FormatFfxChoiceFile(choice); - HANDLE h = CreateFileW(FfxChoicePath(ini).c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, - nullptr); - if (h == INVALID_HANDLE_VALUE) return; - DWORD written = 0; - WriteFile(h, text.data(), DWORD(text.size()), &written, nullptr); - CloseHandle(h); +void SetAsiChoiceRecord(const std::wstring& path) { + HMODULE m = GetModuleHandleW(WRONGGPU_ASI_MODULE); + if (!m) return; + if (auto set = reinterpret_cast(reinterpret_cast(GetProcAddress(m, WRONGGPU_ASI_SET_CHOICE_RECORD)))) + set(path.c_str()); } } // namespace wgwin diff --git a/clean/fsr/src/asi_bridge.h b/clean/fsr/src/asi_bridge.h index 70cab5d5..739d3312 100644 --- a/clean/fsr/src/asi_bridge.h +++ b/clean/fsr/src/asi_bridge.h @@ -4,22 +4,16 @@ // in the process and ask it which upscaler entry the player selected in OptiScaler's menu. No link to the plugin. #include -#include "model_precedence.h" - namespace wgwin { -// Fills *choice: the plugin's saved entry (0 AMD FSR, 'M', 'K', 'L'), whether the player chose it, and when -// (WrongGpuAsiQueryChoiceV1; a plugin without it: WrongGpuAsiQuery, with Model M as its default entry and K / AMD as -// explicit choices with no recorded time). Returns true only when the plugin is present and has hooked the host's -// menu (so the plugin's choice, weighed against the launcher's, decides the model). False otherwise. -bool QueryAsiPlugin(wgfsr::PluginModelChoice* choice); +// Sets *model to 0 (AMD FSR) or a WrongGPU model ('M', 'K'; which WrongGPU model runs is the model choice record's). +// Returns true only when the plugin is present and has hooked the host's menu. False otherwise. +bool QueryAsiPlugin(char* model); // Tells the plugin which model runs (its menu marks that entry). Nothing happens without the plugin or the export. void ShowAsiModel(char model); -// wronggpu-ffx-choice.ini next to `ini` (the front end's wronggpu.ini): the WrongGPU entry last seen in OptiScaler's FFX -// upscaler box (model_precedence.h). Load: false when there is no such file. -bool LoadFfxChoice(const std::wstring& ini, wgfsr::FfxModelChoice* choice); -void SaveFfxChoice(const std::wstring& ini, const wgfsr::FfxModelChoice& choice); +// Tells the plugin where the game's model choice record is (src/model_choice_record.h). Nothing without the plugin. +void SetAsiChoiceRecord(const std::wstring& path); } // namespace wgwin diff --git a/clean/fsr/src/config.cpp b/clean/fsr/src/config.cpp index dc7daeee..7574bdbe 100644 --- a/clean/fsr/src/config.cpp +++ b/clean/fsr/src/config.cpp @@ -345,10 +345,6 @@ Config ParseConfig(const std::string& text, std::string* warnings) { if (ok) c.splitTimeoutMs = static_cast(f); } else if (key == "runtime_options") { c.runtimeOptions = NormalizeOptions(value); - } else if (key == "model_chosen") { - // Written by the launcher with the model item (model_precedence.h): FILETIME, 100 ns since 1601 UTC. - ok = !value.empty() && value.size() <= 20 && value.find_first_not_of("0123456789") == std::string::npos; - if (ok) c.modelChosenAt = std::strtoull(value.c_str(), nullptr, 10); } else if (key == "overlay") { ok = lv == "on" || lv == "badge" || lv == "off"; if (ok) c.overlay = lv; diff --git a/clean/fsr/src/config.h b/clean/fsr/src/config.h index 61ddd866..54b76ce2 100644 --- a/clean/fsr/src/config.h +++ b/clean/fsr/src/config.h @@ -79,9 +79,6 @@ struct Config { // Extra "key=value;key=value" text for the upscaler (the network runtime's own keys, e.g. timing_log=1;sync=pipelined), // appended to BackendOptions() after the front end's keys. Normalized: items trimmed, empty items dropped. std::string runtimeOptions; - // [fsr] model_chosen: when the launcher last changed the model item of runtime_options (Windows FILETIME, 100 ns since 1601 UTC; - // 0 = not recorded). Weighed against the OptiScaler menu plugin's saved choice (model_precedence.h). - uint64_t modelChosenAt = 0; // In-game overlay (overlay.h): "on" (the full panel for 10 s after WrongGPU starts upscaling, then a one-line badge), // "badge" (the badge only), "off". overlayKey toggles it: insert, home, end, delete, pageup, pagedown, pause, diff --git a/clean/fsr/src/dllmain.cpp b/clean/fsr/src/dllmain.cpp index 56659309..db5c017b 100644 --- a/clean/fsr/src/dllmain.cpp +++ b/clean/fsr/src/dllmain.cpp @@ -234,13 +234,24 @@ FrontEnd& Get() { return CompareApi(dll); }; } - // If WrongGPU.asi has hooked OptiScaler's menu, its saved entry weighed against the launcher's model choice - // (not an FFX version override) chooses the model (model_precedence.h). Absent or not hooked: hosted mode as - // before. - p.asiPlugin = [](wgfsr::PluginModelChoice* choice) { return QueryAsiPlugin(choice); }; + // If WrongGPU.asi has hooked OptiScaler's menu, its entry says WrongGPU or AMD, and the game's model choice + // record (model_choice_record.h, next to wronggpu.ini) says which WrongGPU model. Absent or not hooked: hosted + // mode as before. + p.asiPlugin = [](char* model) { return QueryAsiPlugin(model); }; p.asiShowModel = [](char model) { ShowAsiModel(model); }; - p.loadFfxChoice = [](wgfsr::FfxModelChoice* c) { return LoadFfxChoice(Place().ini, c); }; - p.saveFfxChoice = [](const wgfsr::FfxModelChoice& c) { SaveFfxChoice(Place().ini, c); }; + { + const std::wstring& ini = Place().ini; + const size_t slash = ini.find_last_of(L"\\/"); + const std::filesystem::path record = + wgchoice::RecordPathIn(slash == std::wstring::npos ? std::wstring(L".") : ini.substr(0, slash)); + std::error_code ec; + if (std::filesystem::is_directory(record.parent_path(), ec)) { // a launcher install: its state folder + p.choiceRecord = record; + SetAsiChoiceRecord(record.wstring()); // the plugin writes its menu's model clicks there too + } else { + L().Write("model choice: no launcher state folder next to wronggpu.ini: no model choice record (the model item decides)"); + } + } } p.menu = Menu(); g_frontEnd = new FrontEnd(p, config); diff --git a/clean/fsr/src/frontend.cpp b/clean/fsr/src/frontend.cpp index 7373fa3f..6a011d39 100644 --- a/clean/fsr/src/frontend.cpp +++ b/clean/fsr/src/frontend.cpp @@ -566,52 +566,27 @@ ffxReturnCode_t FrontEnd::CreateUpscale(ffxContext* context, ffxCreateContextDes } } - // OptiScaler ASI plugin (clean/fsr/asi): when it has hooked the host's MAIN upscaler list, three choices are weighed - // by model_precedence.h: the launcher's (wronggpu.ini runtime_options' model item with model_chosen), the WrongGPU - // entry picked in OptiScaler's FFX sub-box (the override id, stamped when it changes: FfxChoiceSeen) and the plugin's - // saved entry. The most recent explicit choice wins (a tie: the launcher's), with one log line on a conflict. A - // WrongGPU model -> WrongGPU; an AMD version in the FFX sub-box is not a model choice and never routes it to AMD. - // AMD ("FSR 3.X(/4)" chosen in the plugin's list) -> AMD: the version the FFX sub-box names when that is one of AMD's, + // OptiScaler ASI plugin (clean/fsr/asi): when it has hooked the host's MAIN upscaler list, its entry says WrongGPU or + // AMD ("FSR 3.X(/4)"), and the game's model choice record (model_choice_record.h) says which WrongGPU model: the + // launcher, OptiScaler's FFX box (a WrongGPU entry the record did not know: the player picked it there) and the + // plugin's own model entries all write it, the highest seq is the most recent choice. A WrongGPU model -> WrongGPU, + // whatever AMD version the FFX box names. AMD -> AMD: the version the FFX sub-box names when that is one of AMD's, // else AMD's newest listed version (FSR 4 when the AMD provider has it). - PluginModelChoice asiChoice; - const bool asiHooked = config_.hosted && platform_.asiPlugin && platform_.asiPlugin(&asiChoice); + char asiModel = 0; + const bool asiHooked = config_.hosted && platform_.asiPlugin && platform_.asiPlugin(&asiModel); bool forceAmd = false; if (asiHooked) { - char seen = kChoiceNone; // the WrongGPU model entry the FFX sub-box names, if any + char seen = wgchoice::kUnknown; // the WrongGPU model entry the FFX box names, if any if (u->hasOverride) if (const WgEntryDef* e = OwnEntryOfId(u->overrideId)) if (e->slot == WG_OPT_SR_MODEL && e->value >= 0 && e->value < WG_SR_MODEL_COUNT) seen = kWgModelRows[e->value].name[0]; - const FfxModelChoice ffx = SeeFfxChoice(seen, tag); - const ModelDecision decision = DecideModel(asiChoice, LauncherChoice(), ffx); - if (decision.conflict) { - bool first = false; - { - std::lock_guard lock(mutex_); - first = !modelLogged_.count(decision.line); - modelLogged_[decision.line] = true; - } - if (first) Log(tag + " " + decision.line); - } - // "selected in the host's upscaler list" (the launcher's log reader looks for it): the plugin's menu marks the - // model that runs (asiShowModel), also when the launcher's choice decided. - const std::string by = decision.winner == ModelWinner::Launcher - ? std::string(" (the launcher's model choice: wronggpu.ini runtime_options model=") + decision.model + ")" - : decision.winner == ModelWinner::Ffx - ? std::string(" (the WrongGPU entry picked in OptiScaler's upscaler box: Model ") + decision.model + ")" - : std::string(); - char model = decision.model; - if (model != kChoiceAmd) { + std::string why; + char model = ChooseModel(seen, asiModel, tag, &why); + if (asiModel != 0) { const int32_t m = ModelOfName(std::string(1, model)); const WgEntryDef* sr = m >= 0 ? SrEntryOfModel(m) : nullptr; if (!sr) { // a model this build of the front end lacks (CMake WG_MODEL_K / WG_MODEL_L): Model M, said once - const std::string line = "note: OptiScaler plugin: " + ChoiceName(model) + " is not part of this build of the front end; Model M is used"; - bool first = false; - { - std::lock_guard lock(mutex_); - first = !modelLogged_.count(line); - modelLogged_[line] = true; - } - if (first) Log(tag + " " + line); + LogOnce(tag, std::string("note: model choice: Model ") + model + " is not part of this build of the front end; Model M is used"); model = 'M'; sr = SrEntryOfModel(ModelOfName("M")); } @@ -619,10 +594,13 @@ ffxReturnCode_t FrontEnd::CreateUpscale(ffxContext* context, ffxCreateContextDes u->modelProviderId = sr ? sr->id : kWrongGpuProviderVersionId; u->modelProviderName = sr ? EntryProviderName(*sr) : kWrongGpuVersionName; u->hasOverride = false; // an AMD version in the FFX sub-box must not route this context to AMD - Log(tag + " OptiScaler plugin: " + u->modelProviderName + " selected in the host's upscaler list" + by); + // "selected in the host's upscaler list" (the launcher's log reader looks for it): the plugin's menu marks the + // model that runs (asiShowModel) + Log(tag + " OptiScaler plugin: " + u->modelProviderName + " selected in the host's upscaler list (" + why + ")"); } else { forceAmd = true; - Log(tag + " OptiScaler plugin: AMD FSR selected in the host's upscaler list" + by); + model = 0; + Log(tag + " OptiScaler plugin: AMD FSR selected in the host's upscaler list"); } if (platform_.asiShowModel) platform_.asiShowModel(model); } @@ -1404,47 +1382,75 @@ bool FrontEnd::ConfiguredModel(int32_t* model, std::string* described) { return true; } -LauncherModelChoice FrontEnd::LauncherChoice() const { - // The launcher's choice: the last model item of wronggpu.ini's runtime_options (the launcher writes model= - // there; a build without Model K / L has already dropped those items, IgnoreModelK / IgnoreModelL) and - // model_chosen, when the launcher last changed it. WG_RUNTIME_OPTIONS is a developer's override, not a choice: it - // is checked against the decided model further on (CreateUpscale). - LauncherModelChoice c; +char FrontEnd::LauncherModel() const { + // The last model item of wronggpu.ini's runtime_options (the launcher writes model= there; a build without + // Model K / L has already dropped those items, IgnoreModelK / IgnoreModelL). bool found = false; const std::string v = OptionValue(config_.runtimeOptions, "model", &found); - if (found && v.size() == 1) { - const char m = char(std::toupper(static_cast(v[0]))); - if (m == 'M' || m == 'K' || m == 'L') c.model = m; - } - c.chosenAt = config_.modelChosenAt; - return c; + if (!found || v.size() != 1) return 0; + const char m = char(std::toupper(static_cast(v[0]))); + return wgchoice::IsModel(m) ? m : 0; } -FfxModelChoice FrontEnd::SeeFfxChoice(char seen, const std::string& tag) { - FfxModelChoice before, after; +void FrontEnd::LogOnce(const std::string& tag, const std::string& line) { { std::lock_guard lock(mutex_); - if (!ffxLoaded_) { - ffxLoaded_ = true; - if (platform_.loadFfxChoice) platform_.loadFfxChoice(&ffxSaved_); + if (modelLogged_.count(line)) return; + modelLogged_[line] = true; + } + Log(tag + " " + line); +} + +char FrontEnd::ChooseModel(char seen, char plugin, const std::string& tag, std::string* why) { + const char launcher = LauncherModel(); + // no record: the launcher's K / L item, else the plugin's saved WrongGPU entry (0.6.0's rule), else Model M + auto noRecord = [&] { + if (launcher == 'K' || launcher == 'L') { + *why = std::string("no model choice record; the launcher's model item, wronggpu.ini model=") + launcher; + return launcher; + } + if (wgchoice::IsModel(plugin)) { + *why = std::string("no model choice record; the plugin's saved entry"); + return plugin; + } + *why = launcher ? std::string("no model choice record; wronggpu.ini model=") + launcher : std::string("no model choice record; the default"); + return 'M'; + }; + if (platform_.choiceRecord.empty()) return noRecord(); + std::lock_guard lock(choiceMutex_); // one read-modify-write of the record at a time in this process + wgchoice::Record cur; + std::string err; + const wgchoice::ReadResult rr = wgchoice::ReadRecordFile(platform_.choiceRecord, &cur, &err); + if (rr == wgchoice::ReadResult::Corrupt) + LogOnce(tag, "model choice: the record (wronggpu-setup\\model-choice.ini) is corrupt (" + err + "): treated as no choice"); + if (rr == wgchoice::ReadResult::Unreadable) { + // (never written over: a record held open for a moment must not be replaced by a guess) + LogOnce(tag, "model choice: the record (wronggpu-setup\\model-choice.ini) cannot be read (" + err + "): treated as no record"); + return noRecord(); + } + const wgchoice::Record* have = rr == wgchoice::ReadResult::Ok ? &cur : nullptr; + wgchoice::Record next; + const wgchoice::FfxStep step = wgchoice::FfxObservation(have, seen, &next); + if (step != wgchoice::FfxStep::None) { + if (wgchoice::WriteRecordFile(platform_.choiceRecord, next, &err)) { + if (step == wgchoice::FfxStep::Choice) + Log(tag + " model choice: Model " + next.model + " picked in OptiScaler's upscaler list (seq " + std::to_string(next.seq) + + (have ? std::string(", replacing Model ") + have->model + " from " + wgchoice::SourceWords(have->source) + + ", seq " + std::to_string(have->seq) + ")" + : std::string(", the first choice recorded for this game)"))); + } else { + LogOnce(tag, "ERROR: model choice: the record (wronggpu-setup\\model-choice.ini) could not be written (" + err + ")" + + (step == wgchoice::FfxStep::Choice ? "; this session uses the choice, the next one may not" : "")); } - before = ffxSaved_; - uint64_t now = 0; - if (seen != kChoiceNone && before.model != kChoiceNone && before.model != seen) - now = platform_.clock ? platform_.clock() - : uint64_t(std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()).count() / 100) + - 116444736000000000ull; // 1970 in FILETIME units - after = FfxChoiceSeen(before, seen, now); - ffxSaved_ = after; - } - if (after.model != before.model || after.chosenAt != before.chosenAt) { - if (platform_.saveFfxChoice) platform_.saveFfxChoice(after); - Log(tag + " OptiScaler's upscaler box names " + ChoiceName(after.model) + - (after.chosenAt ? " (changed there: an explicit choice, chosen=" + std::to_string(after.chosenAt) + ")" - : std::string(" (the first entry seen: not counted as a choice)"))); - } - return after; + cur = next; // the player's choice in the list is real even when it could not be saved + have = &cur; + } + if (!have) return noRecord(); + *why = std::string("the model choice record: ") + wgchoice::SourceWords(have->source) + ", seq " + std::to_string(have->seq); + if (launcher && launcher != have->model) + LogOnce(tag, std::string("model choice conflict: wronggpu.ini's model item says Model ") + launcher + "; the more recent choice, Model " + + have->model + " from " + wgchoice::SourceWords(have->source) + " (seq " + std::to_string(have->seq) + "), runs"); + return have->model; } void FrontEnd::ApplyEntry(const WgEntryDef& e, UpscaleContext& u, const std::string& tag, const char* source) { diff --git a/clean/fsr/src/frontend.h b/clean/fsr/src/frontend.h index 573ec929..99128354 100644 --- a/clean/fsr/src/frontend.h +++ b/clean/fsr/src/frontend.h @@ -16,7 +16,7 @@ #include "amd_compare.h" #include "async_create.h" #include "config.h" -#include "model_precedence.h" +#include "model_choice_record.h" #include "status.h" #include "ffx_headers.h" #include "param_map.h" @@ -90,18 +90,14 @@ struct Platform { std::function deviceLost; // OptiScaler ASI plugin bridge (clean/fsr/asi): when WrongGPU.asi is loaded and has hooked OptiScaler's menu, // WrongGPU is its own entry in the host's MAIN upscaler list, not a version in the FFX sub-box. Returns true when - // hooked (then the plugin's saved choice, weighed against the launcher's model choice by model_precedence.h, not an - // FFX override, chooses the model) and fills *choice: model 0 (AMD FSR), 'M', 'K' or 'L', whether the player chose - // it, and when. Null or returns false: no plugin / unknown host build; hosted mode as before. - std::function asiPlugin; + // hooked and sets *model to 0 (AMD FSR chosen there) or a WrongGPU model (then the model choice record decides which, + // choiceRecord below). Null or returns false: no plugin / unknown host build; hosted mode as before. + std::function asiPlugin; // Tells the plugin which model the context runs (0 AMD, 'M', 'K', 'L'), so its menu marks that entry. May be empty. std::function asiShowModel; - // With the plugin hooked: the WrongGPU entry last seen in OptiScaler's FFX upscaler box and when it changed - // (model_precedence.h FfxChoiceSeen; wronggpu-ffx-choice.ini in the DLL). Empty: nothing is kept between sessions. - std::function loadFfxChoice; - std::function saveFfxChoice; - // The time a choice is stamped with: Windows FILETIME units (100 ns since 1601 UTC). Empty: the system clock. - std::function clock; + // The game's model choice record (model_choice_record.h: wronggpu-setup\model-choice.ini next to wronggpu.ini), read + // and written with real files. Empty: no record (the launcher's model item decides, as before). + std::filesystem::path choiceRecord; // Registry options and the menu's choices (shared settings block). Empty members: defaults, nothing written. MenuSettings menu; }; @@ -213,10 +209,15 @@ class FrontEnd { // The configured SR model (sr_model: block > environment > ini) for a context no entry chose; false: not set // anywhere (the model then comes from runtime_options / the runtime's default, as before the registry). bool ConfiguredModel(int32_t* model, std::string* described); - // The launcher's model choice in wronggpu.ini (model_precedence.h), weighed against the OptiScaler plugin's. - LauncherModelChoice LauncherChoice() const; - // The FFX sub-box's WrongGPU entry seen by a create (`seen`, or kChoiceNone), saved and stamped when it changes. - FfxModelChoice SeeFfxChoice(char seen, const std::string& tag); + // The model the launcher's wronggpu.ini names (the last model item of runtime_options: 'M', 'K', 'L'), else 0. + char LauncherModel() const; + // With the plugin hooked: the model choice record after a create that sees OptiScaler's list name `seen` (a WrongGPU + // model's entry, or wgchoice::kUnknown); writes the record when the list names an entry it did not know. The model + // that runs: the record's; without a record, the launcher's model item when it names Model K or L, else the plugin's + // saved WrongGPU entry (`plugin`; what decided before 0.6.5), else Model M. *why: which choice decided, for the log. + char ChooseModel(char seen, char plugin, const std::string& tag, std::string* why); + // `line` logged once per session (after `tag`). + void LogOnce(const std::string& tag, const std::string& line); // AMD's DLL behind a forwarded context (the one that created it), else AMD's original. const OriginalApi* ApiOf(void* context); // `u` runs on AMD while its upscaler's create runs (u.pending): takes the upscaler over when the create has finished. @@ -277,8 +278,7 @@ class FrontEnd { uint32_t inputRefusedRun_ = 0; // refusals in a row with that key (mutex_) std::atomic inputRefusedAny_{false}; // inputRefusedRun_ > 0 (the taken-frame path's cheap check) std::map modelLogged_; // ApplyModelDir: each distinct choice logged once (mutex_) - bool ffxLoaded_ = false; // SeeFfxChoice: the saved FFX entry read (mutex_) - FfxModelChoice ffxSaved_; + std::mutex choiceMutex_; // ChooseModel: one read-modify-write of the choice record at a time std::atomic reentered_{0}; // calls refused because they re-entered this front end on one thread std::mutex parkMutex_; // guards the three below; held while a parked context is destroyed UpscaleContext* parked_ = nullptr; diff --git a/clean/fsr/src/model_choice_record.h b/clean/fsr/src/model_choice_record.h new file mode 100644 index 00000000..7f93b9d2 --- /dev/null +++ b/clean/fsr/src/model_choice_record.h @@ -0,0 +1,294 @@ +// SPDX-License-Identifier: MIT +#pragma once +// The model choice record (0.6.5): ONE small file per game, wronggpu-setup\model-choice.ini in the folder of the front +// end's wronggpu.ini (the launcher's state folder: an uninstall removes it by that name, a reinstall keeps it with the +// game's settings; without that folder there is no record), that every place which can choose WrongGPU's model writes, +// and which decides the model: +// - the launcher, when it applies a model (`WrongGPU.exe set model=`, or a change of the model item); +// - the front end, when the WrongGPU entry picked in OptiScaler's upscaler list (the FFX box, or OptiScaler 10's WrongGPU +// box) is not the one the record knows (`ffx`): the player picked it there; +// - the WrongGPU menu plugin (clean/fsr/asi), when the player clicks one of its model entries. +// "Most recent" is the highest sequence number: a writer reads the record and writes seq + 1. No clock is involved, so a +// clock set back or forward changes nothing. +// +// The file, strictly (anything else is CORRUPT: logged and treated as "no choice", never as a partial one): +// ; comment lines and blank lines +// model= +// seq=<1..18446744073709551615> (decimal digits only, overflow refused) +// source= +// ffx= (the WrongGPU entry the writer knew OptiScaler's list to name; - = not known) +// each key exactly once, no other key, no spaces around '='. Writes are atomic: a temporary file in the same folder, +// flushed, then renamed over the record (on Windows through its handle with POSIX semantics, else MoveFileExW +// REPLACE_EXISTING | WRITE_THROUGH); a reader sees the old +// record or the new one, never part of one. A temporary file a crash left behind is never read. +// +// Why `ffx`: OptiScaler's list keeps naming the entry it last selected. The launcher sets that entry with its model (and +// writes ffx = the entry it set), the plugin keeps the record's ffx (it cannot move OptiScaler's list), so an unchanged +// list never looks like a new choice; only a list entry the record does not know is the player's choice there. With no +// record at all, the entry seen at the first create counts as a choice (the launcher writes the record whenever it sets a +// model and the entry together, so a game without a record has had no model choice yet). +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif + +namespace wgchoice { + +constexpr const wchar_t* kStateFolder = L"wronggpu-setup"; // the launcher's state folder (installer kStateDirName) +constexpr const wchar_t* kRecordFile = L"model-choice.ini"; +// The record of the game whose wronggpu.ini is in `iniDir`. +inline std::filesystem::path RecordPathIn(const std::filesystem::path& iniDir) { return iniDir / kStateFolder / kRecordFile; } +constexpr char kUnknown = '-'; + +enum class Source { Launcher, Ffx, Plugin }; + +struct Record { + char model = 'M'; // 'M', 'K', 'L' + uint64_t seq = 0; // >= 1 in a valid record + Source source = Source::Launcher; + char ffx = kUnknown; // 'M', 'K', 'L' or kUnknown +}; + +inline const char* SourceName(Source s) { return s == Source::Launcher ? "launcher" : s == Source::Ffx ? "ffx" : "plugin"; } +inline const char* SourceWords(Source s) { + return s == Source::Launcher ? "the launcher" : s == Source::Ffx ? "OptiScaler's upscaler list" : "the WrongGPU menu plugin"; +} +inline bool IsModel(char c) { return c == 'M' || c == 'K' || c == 'L'; } + +// Decimal digits only, 1..20 of them, no overflow, not zero. +inline bool ParseSeq(const std::string& v, uint64_t* out) { + if (v.empty() || v.size() > 20) return false; + uint64_t n = 0; + for (char c : v) { + if (c < '0' || c > '9') return false; + const uint64_t d = uint64_t(c - '0'); + if (n > (UINT64_MAX - d) / 10) return false; // n * 10 + d would overflow + n = n * 10 + d; + } + if (n == 0) return false; + *out = n; + return true; +} + +// false (with *why) for anything but one valid record. +inline bool ParseRecord(const std::string& text, Record* out, std::string* why) { + Record r; + bool hasModel = false, hasSeq = false, hasSource = false, hasFfx = false; + auto fail = [&](const std::string& w) { + if (why) *why = w; + return false; + }; + size_t at = 0; + int lineNo = 0; + while (at < text.size()) { + size_t end = text.find('\n', at); + if (end == std::string::npos) end = text.size(); + std::string line = text.substr(at, end - at); + at = end + 1; + ++lineNo; + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line.empty() || line[0] == ';' || line[0] == '#') continue; + const size_t eq = line.find('='); + if (eq == std::string::npos) return fail("line " + std::to_string(lineNo) + " is not key=value"); + const std::string k = line.substr(0, eq), v = line.substr(eq + 1); + if (k == "model") { + if (hasModel) return fail("model given twice"); + if (v.size() != 1 || !IsModel(v[0])) return fail("model is not M, K or L"); + r.model = v[0]; + hasModel = true; + } else if (k == "seq") { + if (hasSeq) return fail("seq given twice"); + if (!ParseSeq(v, &r.seq)) return fail("seq is not a number from 1 to 18446744073709551615"); + hasSeq = true; + } else if (k == "source") { + if (hasSource) return fail("source given twice"); + if (v == "launcher") r.source = Source::Launcher; + else if (v == "ffx") r.source = Source::Ffx; + else if (v == "plugin") r.source = Source::Plugin; + else return fail("source is not launcher, ffx or plugin"); + hasSource = true; + } else if (k == "ffx") { + if (hasFfx) return fail("ffx given twice"); + if (v.size() != 1 || !(IsModel(v[0]) || v[0] == kUnknown)) return fail("ffx is not M, K, L or -"); + r.ffx = v[0]; + hasFfx = true; + } else { + return fail("unknown key \"" + k + "\""); + } + } + if (!hasModel || !hasSeq || !hasSource || !hasFfx) return fail("model, seq, source and ffx are all needed"); + *out = r; + return true; +} + +inline std::string FormatRecord(const Record& r) { + return std::string("; WrongGPU: the model chosen last for this game, by the launcher, OptiScaler's upscaler list (ffx) or the\r\n" + "; WrongGPU menu plugin. The highest seq is the most recent choice. Written by WrongGPU; do not edit.\r\n") + + "model=" + r.model + "\r\nseq=" + std::to_string(r.seq) + "\r\nsource=" + SourceName(r.source) + "\r\nffx=" + r.ffx + "\r\n"; +} + +// The record after a new choice of `model` by `source`, given the current one (`cur`, or none). `ffx`: what that writer +// knows OptiScaler's list names (kUnknown to keep the current record's). false when seq cannot grow (2^64 - 1 reached). +inline bool NextRecord(const Record* cur, char model, Source source, char ffx, Record* out) { + if (cur && cur->seq == UINT64_MAX) return false; + out->model = model; + out->seq = cur ? cur->seq + 1 : 1; + out->source = source; + out->ffx = ffx != kUnknown ? ffx : cur ? cur->ffx : kUnknown; + return true; +} + +enum class FfxStep { + None, // nothing to write: the list names the entry the record knows (or no WrongGPU entry) + Adopt, // the record did not know the list's entry (ffx = -): written with it, not a new choice + Choice, // the player picked another WrongGPU entry in OptiScaler's list (or the first create without a record) +}; + +// What a create that sees OptiScaler's list naming `seen` ('M', 'K', 'L', or kUnknown for none / an AMD version) does +// to the record `cur` (or none): *out is the record to write for Adopt and Choice. +inline FfxStep FfxObservation(const Record* cur, char seen, Record* out) { + if (!IsModel(seen)) return FfxStep::None; + if (!cur) { + NextRecord(nullptr, seen, Source::Ffx, seen, out); + return FfxStep::Choice; + } + if (cur->ffx == seen) return FfxStep::None; + if (cur->ffx == kUnknown) { + *out = *cur; + out->ffx = seen; + return FfxStep::Adopt; + } + if (!NextRecord(cur, seen, Source::Ffx, seen, out)) return FfxStep::None; + return FfxStep::Choice; +} + +// ---- files -------------------------------------------------------------------------------------------------------- + +enum class ReadResult { Missing, Ok, Corrupt, Unreadable }; + +inline ReadResult ReadRecordFile(const std::filesystem::path& path, Record* out, std::string* why) { + std::string text; +#ifdef _WIN32 + // FILE_SHARE_DELETE: a writer may replace the record while it is read (the reader keeps the old one) + HANDLE h = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) { + const DWORD e = GetLastError(); + if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) return ReadResult::Missing; + if (why) *why = "cannot open (Windows error " + std::to_string(e) + ")"; + return ReadResult::Unreadable; + } + char buf[2048]; + DWORD got = 0; + const BOOL ok = ReadFile(h, buf, sizeof buf, &got, nullptr); + CloseHandle(h); + if (!ok) { + if (why) *why = "cannot read"; + return ReadResult::Unreadable; + } + if (got == sizeof buf) { + if (why) *why = "larger than a record"; + return ReadResult::Corrupt; + } + text.assign(buf, got); +#else + std::error_code ec; + if (!std::filesystem::exists(path, ec)) return ReadResult::Missing; + std::ifstream f(path, std::ios::binary); + if (!f) { + if (why) *why = "cannot open"; + return ReadResult::Unreadable; + } + std::ostringstream s; + s << f.rdbuf(); + text = s.str(); + if (text.size() >= 2048) { + if (why) *why = "larger than a record"; + return ReadResult::Corrupt; + } +#endif + return ParseRecord(text, out, why) ? ReadResult::Ok : ReadResult::Corrupt; +} + +// Atomic replace: a temporary file next to the record (its name ends in .tmp; never read), written in full, flushed, then +// moved over the record. Up to `attempts` tries (a reader or scanner can hold the record for a moment). false with *why. +inline bool WriteRecordFile(const std::filesystem::path& path, const Record& r, std::string* why, int attempts = 3) { + const std::string text = FormatRecord(r); + std::string last; + for (int i = 0; i < attempts; ++i) { +#ifdef _WIN32 + const std::wstring tmp = path.wstring() + L"." + std::to_wstring(GetCurrentProcessId()) + L"." + + std::to_wstring(GetTickCount64()) + L"." + std::to_wstring(i) + L".tmp"; + HANDLE h = CreateFileW(tmp.c_str(), GENERIC_WRITE | DELETE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) { + last = "cannot create the temporary file (Windows error " + std::to_string(GetLastError()) + ")"; + } else { + DWORD written = 0; + const bool wrote = WriteFile(h, text.data(), DWORD(text.size()), &written, nullptr) && written == text.size(); + const bool flushed = wrote && FlushFileBuffers(h); + bool moved = false; + if (wrote && flushed) { + // Rename through the handle with POSIX semantics (Windows 10 1809+, NTFS): the record is replaced also while + // a reader holds it open (readers open it with FILE_SHARE_DELETE and keep the old one); then flushed. + const std::wstring target = path.wstring(); + std::vector buf(sizeof(FILE_RENAME_INFO) + target.size() * sizeof(wchar_t)); + auto* info = reinterpret_cast(buf.data()); + const DWORD flags = 0x1 /* FILE_RENAME_FLAG_REPLACE_IF_EXISTS */ | 0x2 /* FILE_RENAME_FLAG_POSIX_SEMANTICS */; + std::memcpy(buf.data(), &flags, sizeof flags); // the union { ReplaceIfExists; Flags } at offset 0 + info->RootDirectory = nullptr; + info->FileNameLength = DWORD(target.size() * sizeof(wchar_t)); + std::memcpy(info->FileName, target.c_str(), target.size() * sizeof(wchar_t)); + moved = SetFileInformationByHandle(h, static_cast(22) /* FileRenameInfoEx */, info, + DWORD(buf.size())) != 0; + if (moved) FlushFileBuffers(h); + } + CloseHandle(h); + if (!wrote || !flushed) { + last = wrote ? "cannot flush the temporary file" : "cannot write the temporary file"; + DeleteFileW(tmp.c_str()); + } else if (moved || MoveFileExW(tmp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { + return true; // (MoveFileExW: older Windows or file systems without the POSIX rename) + } else { + last = "cannot replace the record (Windows error " + std::to_string(GetLastError()) + ")"; + DeleteFileW(tmp.c_str()); + } + } + Sleep(20); +#else + const std::filesystem::path tmp = path.string() + "." + std::to_string(i) + ".tmp"; + { + std::ofstream f(tmp, std::ios::binary | std::ios::trunc); + f.write(text.data(), std::streamsize(text.size())); + f.flush(); + if (!f) { + last = "cannot write the temporary file"; + std::error_code ec; + std::filesystem::remove(tmp, ec); + continue; + } + } + std::error_code ec; + std::filesystem::rename(tmp, path, ec); + if (!ec) return true; + last = "cannot replace the record"; + std::filesystem::remove(tmp, ec); +#endif + } + if (why) *why = last; + return false; +} + +} // namespace wgchoice diff --git a/clean/fsr/src/model_precedence.h b/clean/fsr/src/model_precedence.h deleted file mode 100644 index e1daefe2..00000000 --- a/clean/fsr/src/model_precedence.h +++ /dev/null @@ -1,172 +0,0 @@ -// SPDX-License-Identifier: MIT -#pragma once -// Which model runs when WrongGPU's OptiScaler menu plugin (clean/fsr/asi) has hooked the host's upscaler list (0.6.5). -// Plain C++, no Windows headers, so the unit tests can check it on any host (tests/test_frontend.cpp, -// TestAsiLauncherPrecedence; the front end applies it in CreateUpscale). -// -// Three places can choose the model, each with the time it was chosen: -// - the LAUNCHER: the last model item of wronggpu.ini's runtime_options (model=M / K / L) and model_chosen=, which the -// launcher writes whenever it changes that item and whenever the player explicitly applies a model (also the same -// one again: `WrongGPU.exe set model=`); -// - the OPTISCALER INDEX: the WrongGPU entry the player picked in OptiScaler's FFX upscaler box (the version id -// OptiScaler passes with each create; [FSR] UpscalerIndex). The front end saves the entry it saw (wronggpu-ffx-choice.ini) -// and stamps the time when it sees a different one (FfxChoiceSeen below); -// - the PLUGIN MENU: the entry the player last clicked in the plugin's items of OptiScaler's main list -// (wronggpu-asi.ini selection= and chosen=). -// Times are Windows FILETIME units: 100 ns since 1601-01-01 UTC, on this PC's clock, so two choices practically never -// share a time. 0 means "not recorded" (files of earlier versions, installers, a hand edit, the first entry the front -// end ever saw): such a choice ranks as the OLDEST. -// -// A choice is a DEFAULT when nobody made it: plugin menu with no file / no selection line / Model M with no time; launcher -// with no model item or model=M with no time (the installer's item); OptiScaler index with no time (the first entry seen, -// or none). Anything else is EXPLICIT. -// -// The rule: -// 1. no explicit choice: the launcher's model item if it has one, else Model M (as before); -// 2. otherwise the explicit choice with the latest time wins; untimed explicit choices are the oldest; -// 3. on an exact tie (also: all untimed) the launcher wins, then the OptiScaler index, then the plugin menu (the launcher is -// the deliberate settings tool); -// 4. explicit choices that name different models are a CONFLICT: the front end logs one line naming each, its time, and -// the winner with the reason. -// AMD (the plugin's "FSR 3.X(/4)" entry, model 0) is a choice like the models. The launcher's "WrongGPU off" -// (upscaler = amd) is not a model choice: it is a master switch and still turns WrongGPU off whatever is chosen here. -// Known limit: the order follows the PC's clock; a clock set back between two choices can order them wrongly. -#include -#include - -namespace wgfsr { - -constexpr char kChoiceAmd = 0; // AMD's FSR (the plugin's FSR 3.X entry) -constexpr char kChoiceNone = '-'; // no model stated - -struct PluginModelChoice { - char model = 'M'; // 0 (AMD), 'M', 'K', 'L' - bool explicitChoice = false; // false: the plugin's default entry - uint64_t chosenAt = 0; -}; - -struct LauncherModelChoice { - char model = kChoiceNone; // 'M', 'K', 'L' (the last model item), or kChoiceNone - uint64_t chosenAt = 0; // wronggpu.ini model_chosen - bool Explicit() const { return model != kChoiceNone && (model != 'M' || chosenAt != 0); } -}; - -// The WrongGPU entry picked in OptiScaler's FFX upscaler box, as the front end last saw it. -struct FfxModelChoice { - char model = kChoiceNone; // 'M', 'K', 'L', or kChoiceNone (no WrongGPU entry seen) - uint64_t chosenAt = 0; // when the front end saw it change; 0: the first entry seen (not counted as a choice) - bool Explicit() const { return model != kChoiceNone && chosenAt != 0; } -}; - -// The saved FFX entry after a create that names `seen` (a WrongGPU model's entry, or kChoiceNone) at time `now`: the -// first entry ever seen is saved untimed (it is what the launcher or the install set); a different entry than the saved -// one is the player's choice in OptiScaler's box, made now; the same entry keeps its time. No entry seen: unchanged. -inline FfxModelChoice FfxChoiceSeen(const FfxModelChoice& saved, char seen, uint64_t now) { - if (seen == kChoiceNone) return saved; - if (saved.model == kChoiceNone) return FfxModelChoice{seen, 0}; - if (saved.model != seen) return FfxModelChoice{seen, now}; - return saved; -} - -// wronggpu-ffx-choice.ini (next to wronggpu.ini): "model=" and "chosen=" (0 or none: untimed). -inline FfxModelChoice ParseFfxChoiceFile(const std::string& text) { - FfxModelChoice c; - size_t at = 0; - while (at < text.size()) { - size_t end = text.find('\n', at); - if (end == std::string::npos) end = text.size(); - std::string line; - for (size_t i = at; i < end; ++i) - if (text[i] != ' ' && text[i] != '\t' && text[i] != '\r') line += text[i]; - at = end + 1; - if (line.size() == 7 && line.compare(0, 6, "model=") == 0) { - const char m = char(line[6] >= 'a' && line[6] <= 'z' ? line[6] - 32 : line[6]); - if (m == 'M' || m == 'K' || m == 'L') c.model = m; - } else if (line.compare(0, 7, "chosen=") == 0 && line.size() > 7 && line.size() <= 27) { - uint64_t t = 0; - bool ok = true; - for (size_t i = 7; i < line.size(); ++i) { - if (line[i] < '0' || line[i] > '9') { ok = false; break; } - t = t * 10 + uint64_t(line[i] - '0'); - } - if (ok) c.chosenAt = t; - } - } - if (c.model == kChoiceNone) c.chosenAt = 0; - return c; -} - -inline std::string FormatFfxChoiceFile(const FfxModelChoice& c) { - return std::string("; WrongGPU front end: the WrongGPU entry last seen in OptiScaler's FFX upscaler box, and when it changed\r\n" - "; (chosen: Windows FILETIME, 100 ns since 1601 UTC; 0 = the first entry seen, not counted as a choice).\r\n" - "model=") + (c.model == kChoiceNone ? std::string() : std::string(1, c.model)) + "\r\nchosen=" + - std::to_string(c.chosenAt) + "\r\n"; -} - -enum class ModelWinner { Default, Plugin, Launcher, Ffx }; - -struct ModelDecision { - char model = 'M'; - ModelWinner winner = ModelWinner::Default; - bool conflict = false; - std::string line; // the conflict line (empty without a conflict) -}; - -inline std::string ChoiceName(char model) { - if (model == kChoiceAmd) return "AMD FSR"; - if (model == kChoiceNone) return "no model"; - return std::string("Model ") + model; -} - -inline std::string ChoiceTime(uint64_t t) { return t ? "chosen=" + std::to_string(t) : "no time recorded, counted as the oldest"; } - -inline ModelDecision DecideModel(const PluginModelChoice& plugin, const LauncherModelChoice& launcher, - const FfxModelChoice& ffx = FfxModelChoice{}) { - struct Source { - bool on; - char model; - uint64_t at; - ModelWinner who; - const char* name; - }; - // tie order: launcher, OptiScaler index, plugin menu - const Source s[3] = { - {launcher.Explicit(), launcher.model, launcher.chosenAt, ModelWinner::Launcher, "the launcher"}, - {ffx.Explicit(), ffx.model, ffx.chosenAt, ModelWinner::Ffx, "OptiScaler's upscaler box"}, - {plugin.explicitChoice, plugin.model, plugin.chosenAt, ModelWinner::Plugin, "the OptiScaler menu plugin"}, - }; - ModelDecision d; - const Source* best = nullptr; - for (const Source& c : s) - if (c.on && (!best || c.at > best->at)) best = &c; // strictly later wins: an equal time keeps the earlier in tie order - if (!best) { - d.model = launcher.model == kChoiceNone ? 'M' : launcher.model; // (an unstamped model=M: Model M) - return d; - } - d.model = best->model; - d.winner = best->who; - int tied = 0; - for (const Source& c : s) { - if (!c.on) continue; - if (c.model != best->model) d.conflict = true; - if (c.at == best->at) ++tied; - } - if (!d.conflict) return d; - static const char* const where[3] = {" (wronggpu.ini runtime_options, model_chosen)", " (wronggpu-ffx-choice.ini)", - " (wronggpu-asi.ini)"}; - d.line = "model choice conflict:"; - bool first = true; - for (int i = 0; i < 3; ++i) { - if (!s[i].on) continue; - d.line += std::string(first ? " " : ", ") + s[i].name + " chose " + ChoiceName(s[i].model) + where[i] + " " + - ChoiceTime(s[i].at); - first = false; - } - const char* why = best->at == 0 ? "no choice recorded a time; the launcher, then OptiScaler's box, then the plugin is taken" - : tied > 1 ? "the same time; the launcher, then OptiScaler's box, then the plugin is taken" - : "the most recent explicit choice"; - d.line += std::string("; ") + best->name + "'s choice wins (" + why + "): " + ChoiceName(d.model) + " runs"; - return d; -} - -} // namespace wgfsr diff --git a/clean/fsr/tests/test_asi_status.cpp b/clean/fsr/tests/test_asi_status.cpp index ad787a58..761ade63 100644 --- a/clean/fsr/tests/test_asi_status.cpp +++ b/clean/fsr/tests/test_asi_status.cpp @@ -117,27 +117,19 @@ int main(int argc, char** argv) { CHECK(s.selected_model == 'M' && s.rr_ready == 0); } } - // 0.6.5: the saved choice for the precedence against the launcher (asi_abi.h WrongGpuAsiQueryChoiceV1), and the - // front end's report of the model that runs (display only; never saved, never hooks anything). - auto choice = reinterpret_cast(GetProcAddress(module, WRONGGPU_ASI_CHOICE_QUERY)); + // 0.6.5: the front end's report of the model that runs (display only) and of where the game's model choice record is + // (the plugin writes its menu's model clicks there). Neither is saved, neither hooks anything. auto show = reinterpret_cast(GetProcAddress(module, WRONGGPU_ASI_SHOW_MODEL)); - CHECK(choice != nullptr && show != nullptr); - if (choice && show) { - CHECK(choice(nullptr, sizeof(WrongGpuAsiChoiceV1)) == WG_ASI_STATUS_INVALID_ARGUMENT); - WrongGpuAsiChoiceV1 c{}; - c.size = sizeof(c); - c.version = WRONGGPU_ASI_CHOICE_VERSION; - CHECK(choice(&c, sizeof(c) - 1) == WG_ASI_STATUS_INVALID_SIZE); - c.version = 99; - CHECK(choice(&c, sizeof(c)) == WG_ASI_STATUS_UNSUPPORTED_VERSION); - c.version = WRONGGPU_ASI_CHOICE_VERSION; - CHECK(choice(&c, sizeof(c)) == WG_ASI_STATUS_OK); - // never initialised: the default entry, not chosen, no time, not hooked - CHECK(c.hooked == 0 && c.model == 'M' && c.explicit_choice == 0 && c.chosen_at == 0); + auto setRecord = reinterpret_cast(GetProcAddress(module, WRONGGPU_ASI_SET_CHOICE_RECORD)); + CHECK(show != nullptr && setRecord != nullptr); + if (show && setRecord && legacy) { show('L'); show('Z'); // not an entry: ignored show(1); - CHECK(choice(&c, sizeof(c)) == WG_ASI_STATUS_OK && c.model == 'M' && c.explicit_choice == 0); + setRecord(L"X:\\nowhere\\wronggpu-setup\\model-choice.ini"); + setRecord(nullptr); + int hooked = -1; char model = '?'; + CHECK(legacy(&hooked, &model) == 1 && hooked == 0 && model == 'M'); // the saved entry is unchanged } CHECK(FreeLibrary(module) != 0); // No initialization or patches ever occurred. CHECK(GetModuleHandleA(argv[1]) == nullptr); // Query-only loading did not permanently pin it. diff --git a/clean/fsr/tests/test_asi_thunk.cpp b/clean/fsr/tests/test_asi_thunk.cpp index 59887e1d..fb384cc1 100644 --- a/clean/fsr/tests/test_asi_thunk.cpp +++ b/clean/fsr/tests/test_asi_thunk.cpp @@ -162,48 +162,16 @@ void TestSelectionFile() { CHECK(ParseSelection("selection=wronggpu-l") == (WRONGGPU_MODEL_L ? kModelL : kModelM)); } -// 0.6.5: the saved choice says whether the player chose it and when (chosen=), so the front end can weigh it against -// the launcher's model choice (src/model_precedence.h). -void TestSelectionExplicitAndTime() { - Selection s = ParseSelectionFile(""); - CHECK(s.model == kModelM && !s.explicitChoice && s.chosenAt == 0); // no file: the default entry - s = ParseSelectionFile("; c\r\nselection=wronggpu\r\n"); // what installers seed / 0.6.0 saved for M - CHECK(s.model == kModelM && !s.explicitChoice && s.chosenAt == 0); - s = ParseSelectionFile("selection=wronggpu\r\nchosen=1763150000\r\n"); // a click on Model M, with its time - CHECK(s.model == kModelM && s.explicitChoice && s.chosenAt == 1763150000ull); - s = ParseSelectionFile("chosen=77\r\nselection=amd\r\n"); // order does not matter - CHECK(s.model == kModelAmd && s.explicitChoice && s.chosenAt == 77); - s = ParseSelectionFile("selection=amd\r\n"); // an earlier version's AMD: explicit, no time - CHECK(s.model == kModelAmd && s.explicitChoice && s.chosenAt == 0); - s = ParseSelectionFile("selection=wronggpu\r\nchosen=soon\r\n"); // a bad time: not recorded - CHECK(s.model == kModelM && !s.explicitChoice && s.chosenAt == 0); - s = ParseSelectionFile("selection=garbage\r\nchosen=5\r\n"); // an unknown entry: the default, whatever the time - CHECK(s.model == kModelM && !s.explicitChoice && s.chosenAt == 0); - s = ParseSelectionFile("selection=wronggpu-k\r\n"); - CHECK(WRONGGPU_MODEL_K ? (s.model == kModelK && s.explicitChoice) : (s.model == kModelM && !s.explicitChoice)); - s = ParseSelectionFile("selection=wronggpu-l\r\nchosen=9\r\n"); // Model L; in a build without it, the default - CHECK(WRONGGPU_MODEL_L ? (s.model == kModelL && s.explicitChoice && s.chosenAt == 9) : (s.model == kModelM && !s.explicitChoice)); - // round trip of every entry with and without a time - for (const Entry& e : kEntries) { - const Selection t = ParseSelectionFile(FormatSelection(e.model, 1234)); - CHECK(t.model == e.model && t.explicitChoice && t.chosenAt == 1234); - const Selection u = ParseSelectionFile(FormatSelection(e.model)); - CHECK(u.model == e.model && u.chosenAt == 0 && u.explicitChoice == (e.model != kModelM)); - } - CHECK(FormatSelection(kModelL, 5).find("selection=wronggpu-l\r\nchosen=5\r\n") != std::string::npos); - CHECK(FormatSelection(kModelM).find("chosen=") == std::string::npos); -} - -// A click records an explicit choice with its time and reports it; the menu marks the model the front end reported -// (ShownModel) until the next click. -void TestClickRecordsTimeAndShownModel() { +// A click records the model and reports it; the menu marks the model the front end reported (ShownModel) until the +// next click. (The click's entry in the game's model choice record is the live plugin's: wronggpu_asi.cpp.) +void TestClickAndShownModel() { PluginState st; FakeSelectable none; bool clicked = true; const int size = 0; - SelectableThunkLogic(none, "FSR 3.X", true, 0, &size, st, 100, &clicked); - CHECK(!clicked && !st.explicitChoice.load() && st.chosenAt.load() == 0); // drawing alone records nothing - // the front end reports that another model runs (the launcher's choice won over the plugin's default) + SelectableThunkLogic(none, "FSR 3.X", true, 0, &size, st, &clicked); + CHECK(!clicked && st.model.load() == kModelM); // drawing alone records nothing + // the front end reports that another model runs (the model choice record decided) st.shown.store(kEntries[kEntryCount - 1].model); FakeSelectable marks; SelectableThunkLogic(marks, "FSR 3.X", true, 0, &size, st); @@ -211,21 +179,21 @@ void TestClickRecordsTimeAndShownModel() { FakeBeginCombo bc; BeginComboThunkLogic(bc, "", "FSR 3.X", 0, st); CHECK(bc.preview == kEntries[kEntryCount - 1].label); - // the player clicks Model M: explicit, timed, and marked again + // the player clicks the first entry: recorded, marked again FakeSelectable click; click.clickLabel = kEntries[0].label; - CHECK(SelectableThunkLogic(click, "FSR 3.X", true, 0, &size, st, 1763150000ull, &clicked)); - CHECK(clicked && st.model.load() == kModelM && st.explicitChoice.load() && st.chosenAt.load() == 1763150000ull); - CHECK(st.shown.load() == kShowSaved && ShownModel(st) == kModelM); - // a click on the entry already saved is still an explicit choice with a new time - FakeSelectable again; - again.clickLabel = kEntries[0].label; - CHECK(SelectableThunkLogic(again, "FSR 3.X", true, 0, &size, st, 1763150500ull, &clicked) && clicked); - CHECK(st.chosenAt.load() == 1763150500ull); + CHECK(SelectableThunkLogic(click, "FSR 3.X", true, 0, &size, st, &clicked)); + CHECK(clicked && st.model.load() == kModelM && st.shown.load() == kShowSaved && ShownModel(st) == kModelM); #if WRONGGPU_MODEL_L FakeSelectable l; l.clickLabel = "WrongGPU Model L"; - CHECK(SelectableThunkLogic(l, "FSR 3.X", true, 0, &size, st, 1763151000ull, &clicked) && clicked && st.model.load() == kModelL); + CHECK(SelectableThunkLogic(l, "FSR 3.X", true, 0, &size, st, &clicked) && clicked && st.model.load() == kModelL); + CHECK(ParseSelection(FormatSelection(kModelL)) == kModelL); +#endif +#if WRONGGPU_MODEL_K + FakeSelectable k; + k.clickLabel = "WrongGPU Model K"; + CHECK(SelectableThunkLogic(k, "FSR 3.X", true, 0, &size, st, &clicked) && clicked && st.model.load() == kModelK); #endif } @@ -240,8 +208,7 @@ int main() { TestClickAmd(); TestPreviewRelabel(); TestSelectionFile(); - TestSelectionExplicitAndTime(); - TestClickRecordsTimeAndShownModel(); + TestClickAndShownModel(); std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } diff --git a/clean/fsr/tests/test_frontend.cpp b/clean/fsr/tests/test_frontend.cpp index ccacc845..f6a2b091 100644 --- a/clean/fsr/tests/test_frontend.cpp +++ b/clean/fsr/tests/test_frontend.cpp @@ -7,6 +7,8 @@ #include #include #include +#include +#include #include #include #include @@ -233,17 +235,12 @@ static bool g_compare = false; // Platform::compareAmd static std::vector g_statuses; // Platform::status static std::vector> g_timed; // Platform::gpuTimer -// Fake WrongGPU.asi bridge (clean/fsr/asi): g_asiHooked/g_asiModel/... stand in for the plugin's WrongGpuAsiQueryChoiceV1. +// Fake WrongGPU.asi bridge (clean/fsr/asi): g_asiHooked/g_asiModel stand in for the plugin's WrongGpuAsiQuery. static bool g_asiPresent = false; // the plugin bridge is wired at all static bool g_asiHooked = false; // and it reports a successful hook -static char g_asiModel = 0; // 0 (AMD), 'M', 'K', 'L' -static int g_asiExplicit = -1; // -1: as an earlier plugin reports it (Model M = default entry, others explicit); 0/1 -static uint64_t g_asiChosenAt = 0; // when the player clicked it (0 = not recorded) -static std::vector g_asiShown; // Platform::asiShowModel calls -static bool g_ffxHas = false; // Platform::loadFfxChoice / saveFfxChoice: the saved FFX entry (wronggpu-ffx-choice.ini) -static FfxModelChoice g_ffxFile; -static int g_ffxSaves = 0; -static uint64_t g_clockNow = 0; // Platform::clock +static char g_asiModel = 0; // 0 (AMD), 'M', 'K' +static std::vector g_asiShown; // Platform::asiShowModel calls +static std::filesystem::path g_choiceRecord; // Platform::choiceRecord (a real file; empty: none) // Fake shared settings (Platform::menu, settings_bridge.h in the DLL): values set "somewhere" (block / env / ini), // the writes of the menu's choices, whether this module is the writer, the folder sidecar's entry. @@ -284,28 +281,10 @@ static std::unique_ptr MakeFrontEnd(const Config& config) { p.menu.folderEntry = g_folderEntry; } p.original = []() -> const OriginalApi* { return g_originalAvailable ? g_originalApi : nullptr; }; - if (g_asiPresent) { - p.asiPlugin = [](PluginModelChoice* c) { - if (c) { - c->model = g_asiModel; - c->explicitChoice = g_asiExplicit < 0 ? g_asiModel != 'M' : g_asiExplicit != 0; - c->chosenAt = g_asiChosenAt; - } - return g_asiHooked; - }; - p.asiShowModel = [](char model) { g_asiShown.push_back(model); }; - p.loadFfxChoice = [](FfxModelChoice* c) { - if (!g_ffxHas) return false; - *c = g_ffxFile; - return true; - }; - p.saveFfxChoice = [](const FfxModelChoice& c) { - g_ffxFile = c; - g_ffxHas = true; - ++g_ffxSaves; - }; - p.clock = [] { return g_clockNow; }; - } + if (g_asiPresent) + p.asiPlugin = [](char* model) { if (model) *model = g_asiModel; return g_asiHooked; }; + if (g_asiPresent) p.asiShowModel = [](char model) { g_asiShown.push_back(model); }; + p.choiceRecord = g_choiceRecord; p.compareApi = []() -> const OriginalApi* { return g_compareApi; }; p.backend = [](const Config&, std::string&) -> const WgUpscalerBackend* { return g_useBackend; }; p.services = [](const WgUpscalerBackend* b, void* device) -> const WgFrontEndServices* { @@ -398,13 +377,7 @@ static void Reset() { g_asiPresent = false; g_asiHooked = false; g_asiModel = 0; - g_asiExplicit = -1; - g_asiChosenAt = 0; g_asiShown.clear(); - g_ffxHas = false; - g_ffxFile = FfxModelChoice{}; - g_ffxSaves = 0; - g_clockNow = 0; g_createInfo = WgCreateInfo{}; g_compare = false; g_statuses.clear(); @@ -2589,22 +2562,14 @@ static void TestAsiPluginNotHooked() { // The installer's Preset K with the plugin hooked (0.5.0): wronggpu.ini says runtime_options = model=K, OptiScaler.ini // UpscalerIndex=1, and the installer seeds the plugin's wronggpu-asi.ini with selection=wronggpu-k, so the plugin -// reports 'K' and the context runs Model K. Since 0.6.5 the plugin's default entry (Model M with no time) no longer -// decides over the launcher's model=K (the 0.6.5 audit: the plugin's default hid the launcher's choice); a later choice -// of Model M in OptiScaler's list (a click with its time) still runs Model M, with the conflict line. +// reports 'K' and the context runs Model K. Since 0.6.5 the game's model choice record decides (TestAsiChoiceRecord); +// without one, the launcher's K item decides over the plugin's saved entry (the 0.6.5 audit: the plugin's default hid the +// launcher's choice), so both cases run Model K here. static void TestAsiPluginPresetK() { #if WRONGGPU_MODEL_K const bool present = g_asiPresent, hooked = g_asiHooked; const char saved = g_asiModel; - struct Case { - char plugin; - int explicitChoice; - uint64_t at; - char runs; - bool conflict; - }; - for (const Case& k : {Case{'K', -1, 0, 'K', false}, Case{'M', 1, 1000, 'M', true}, Case{'M', 0, 0, 'K', false}}) { - const char plugin = k.runs; // the model expected to run + for (char plugin : {'K', 'M'}) { Reset(); g_resources[kOutput] = {dxgi::R16G16B16A16_FLOAT, 2560, 1440}; std::string warnings; @@ -2614,9 +2579,7 @@ static void TestAsiPluginPresetK() { c.upscaler = UpscalerChoice::Network; g_asiPresent = true; g_asiHooked = true; - g_asiModel = k.plugin; - g_asiExplicit = k.explicitChoice; - g_asiChosenAt = k.at; + g_asiModel = plugin; auto fe = MakeFrontEnd(c); UpscaleCreate create(FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE, true); create.version.versionId = kWrongGpuKProviderVersionId; // the FFX sub-box at UpscalerIndex=1 @@ -2627,14 +2590,13 @@ static void TestAsiPluginPresetK() { ffxQueryGetProviderVersion q{}; q.header.type = FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION; CHECK(fe->Query(&ctx, &q.header) == FFX_API_RETURN_OK); - const std::string expected = std::string("WrongGPU Model ") + plugin; + const char runs = 'K'; // (no record: the launcher's K item) + const std::string expected = std::string("WrongGPU Model ") + runs; CHECK(q.versionName && expected == q.versionName); - CHECK(q.versionId == (plugin == 'K' ? kWrongGpuKProviderVersionId : kWrongGpuProviderVersionId)); + CHECK(q.versionId == kWrongGpuKProviderVersionId); const std::string options = g_createInfo.options ? g_createInfo.options : ""; - CHECK(options.size() >= 7 && options.compare(options.size() - 7, 7, std::string("model=") + plugin) == 0); + CHECK(options.size() >= 7 && options.compare(options.size() - 7, 7, std::string("model=") + runs) == 0); CHECK(CountLog((std::string("OptiScaler plugin: ") + expected + " selected").c_str()) == 1); - CHECK(CountLog("model choice conflict") == (k.conflict ? 1u : 0u)); - CHECK(g_asiShown.size() == 1 && g_asiShown[0] == k.runs); CHECK(fe->DestroyContext(&ctx, kMemCb) == FFX_API_RETURN_OK); } g_asiPresent = present; @@ -2643,18 +2605,39 @@ static void TestAsiPluginPresetK() { #endif } -// 0.6.5 audit (the A8 blocker): with the plugin hooked, the launcher's model choice (wronggpu.ini runtime_options' -// model item, with model_chosen) decides over the plugin's default entry; on a conflict between two explicit choices -// the more recent one runs and one line names both (model_precedence.h). Every case goes through CreateUpscale with a -// hosted create, and checks the provider the context reports, the runtime option passed on, and the log. -struct AsiRun { - std::string provider; // QUERY_GET_PROVIDER_VERSION's name, "" when the context went to AMD - std::string options; // the runtime's create options ("" when nothing was created) - bool amd = false; // AMD's FSR was asked to create a context - int runtimeCreates = 0; // creates the runtime saw +// 0.6.5 (#213): with the plugin hooked, the game's model choice record (model_choice_record.h) decides the WrongGPU model, +// on REAL files in a fresh folder under the temporary folder: the launcher's, OptiScaler's list's (ffx) and the plugin's +// choices, the highest seq winning; the launcher's own index rewrite never a choice; the first create without a record; +// corrupt and unreadable records. Plus the audit's case without any record (the launcher's model item). +struct RecordFolder { + std::filesystem::path dir; + RecordFolder() { + dir = std::filesystem::temp_directory_path() / "wg-frontend-choice-test"; + std::error_code ec; + std::filesystem::create_directories(dir / wgchoice::kStateFolder, ec); + std::filesystem::remove(record(), ec); + } + std::filesystem::path record() const { return wgchoice::RecordPathIn(dir); } + ~RecordFolder() { + std::error_code ec; + for (auto& e : std::filesystem::directory_iterator(dir / wgchoice::kStateFolder, ec)) std::filesystem::remove(e.path(), ec); + std::filesystem::remove(dir / wgchoice::kStateFolder, ec); + std::filesystem::remove(dir, ec); + } }; -static AsiRun RunAsi(const char* ini, char plugin, int explicitChoice, uint64_t at, std::vector modelFiles = {}, - bool lookup = false) { + +static wgchoice::Record ReadRec(const std::filesystem::path& p, wgchoice::ReadResult* rr = nullptr) { + wgchoice::Record r; + std::string why; + const wgchoice::ReadResult res = wgchoice::ReadRecordFile(p, &r, &why); + if (rr) *rr = res; + if (res != wgchoice::ReadResult::Ok) r = wgchoice::Record{0, 0, wgchoice::Source::Launcher, wgchoice::kUnknown}; + return r; +} + +// One hosted create with the plugin hooked (its entry `plugin`: 0 AMD or a WrongGPU model), OptiScaler's FFX box naming +// `overrideId`; the provider the context runs ("" for AMD). +static std::string HookedCreate(const char* ini, char plugin, uint64_t overrideId) { Reset(); g_resources[kOutput] = {dxgi::R16G16B16A16_FLOAT, 2560, 1440}; std::string warnings; @@ -2666,309 +2649,113 @@ static AsiRun RunAsi(const char* ini, char plugin, int explicitChoice, uint64_t g_asiPresent = true; g_asiHooked = true; g_asiModel = plugin; - g_asiExplicit = explicitChoice; - g_asiChosenAt = at; - if (lookup) { - g_modelOn = true; - g_modelPlaces = {{"G:\\game\\WrongGPU\\model", "the game's data folder", false}}; - g_modelFiles = modelFiles; - } auto fe = MakeFrontEnd(c); - AsiRun r; const size_t amd = g_amd.size(); - const int creates = g_createCalls; - g_createOptions.clear(); - UpscaleCreate create(FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE, true); - create.version.versionId = kWrongGpuProviderVersionId; // the FFX sub-box names Model M: it does not decide here - ffxContext ctx = nullptr; - CHECK(fe->CreateContext(&ctx, &create.upscale.header, kMemCb) == FFX_API_RETURN_OK && ctx); - r.amd = g_amd.size() > amd; - r.runtimeCreates = g_createCalls - creates; - r.options = g_createOptions; - if (fe->OwnContextCount() == 1 && !r.amd) { - ffxQueryGetProviderVersion q{}; - q.header.type = FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION; - if (fe->Query(&ctx, &q.header) == FFX_API_RETURN_OK && q.versionName) r.provider = q.versionName; - } - CHECK(fe->DestroyContext(&ctx, kMemCb) == FFX_API_RETURN_OK); - return r; -} - -static bool EndsWith(const std::string& s, const std::string& tail) { - return s.size() >= tail.size() && s.compare(s.size() - tail.size(), tail.size(), tail) == 0; -} - -// #213 review P3: with the plugin hooked, the WrongGPU entry picked in OptiScaler's FFX upscaler box is a third, stamped -// choice (model_precedence.h FfxChoiceSeen): saved between sessions, stamped when it changes, weighed with the launcher's -// and the plugin menu's by the same most-recent rule. And P1 through a hosted create: the launcher's re-applied model wins. -static std::string CreateHosted(FrontEnd& fe, uint64_t overrideId, bool* amd = nullptr) { - const size_t amdBefore = g_amd.size(); UpscaleCreate create(FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE, true); create.version.versionId = overrideId; ffxContext ctx = nullptr; - CHECK(fe.CreateContext(&ctx, &create.upscale.header, kMemCb) == FFX_API_RETURN_OK && ctx); + CHECK(fe->CreateContext(&ctx, &create.upscale.header, kMemCb) == FFX_API_RETURN_OK && ctx); std::string provider; - const bool wentAmd = g_amd.size() > amdBefore; - if (amd) *amd = wentAmd; - if (!wentAmd) { + if (g_amd.size() == amd) { ffxQueryGetProviderVersion q{}; q.header.type = FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION; - if (fe.Query(&ctx, &q.header) == FFX_API_RETURN_OK && q.versionName) provider = q.versionName; + if (fe->Query(&ctx, &q.header) == FFX_API_RETURN_OK && q.versionName) provider = q.versionName; } - CHECK(fe.DestroyContext(&ctx, kMemCb) == FFX_API_RETURN_OK); + CHECK(fe->DestroyContext(&ctx, kMemCb) == FFX_API_RETURN_OK); return provider; } -static void TestAsiFfxIndexChoice() { +static void TestAsiChoiceRecord() { const bool present = g_asiPresent, hooked = g_asiHooked; const char saved = g_asiModel; - // P1 through a hosted create: launcher X@1000 -> plugin Y@2000 runs Y; launcher re-applies X@3000 -> X, for each model - // this build has (L, K, M). - for (char x : {'L', 'K', 'M'}) { - const int32_t mx = ModelOfName(std::string(1, x)); - if (mx < 0) continue; - const char y = x == 'M' ? (ModelOfName("K") >= 0 ? 'K' : ModelOfName("L") >= 0 ? 'L' : kChoiceAmd) : 'M'; - const std::string before = std::string("[fsr]\nruntime_options = model=") + x + "\nmodel_chosen = 1000\n"; - const std::string after = std::string("[fsr]\nruntime_options = model=") + x + "\nmodel_chosen = 3000\n"; - AsiRun r = RunAsi(before.c_str(), y, 1, 2000); - CHECK(y == kChoiceAmd ? r.amd : r.provider == std::string("WrongGPU Model ") + y); - r = RunAsi(after.c_str(), y, 1, 2000); - CHECK(r.provider == std::string("WrongGPU Model ") + x && EndsWith(r.options, std::string("model=") + x)); - CHECK(CountLog("the launcher's choice wins (the most recent explicit choice)") == 1); + const bool hasL = ModelOfName("L") >= 0, hasK = ModelOfName("K") >= 0; + auto idOf = [](char m) { return SrEntryOfModel(ModelOfName(std::string(1, m)))->id; }; + auto name = [](char m) { return std::string("WrongGPU Model ") + m; }; + // A second model to choose (L, else K); a build with neither checks the record rule with Model M only (below). + const char b = hasL ? 'L' : hasK ? 'K' : 0; + const char c3 = hasL && hasK ? 'K' : 0; // a third model, in a build with both + RecordFolder f; + std::string why; + // The audit's case without a record (a front end without the state folder): the launcher's K / L item decides over the + // plugin's saved default entry (Model M). + if (b) { + const std::string ini = std::string("runtime_options = model=") + b + "\n"; + CHECK(HookedCreate(ini.c_str(), 'M', kWrongGpuProviderVersionId) == name(b)); + CHECK(CountLog("no model choice record; the launcher's model item") == 1); } - // P3: a model to switch to in the FFX box (L, else K); without either only the pure rule above checks it. - const char b = ModelOfName("L") >= 0 ? 'L' : ModelOfName("K") >= 0 ? 'K' : 0; + g_choiceRecord = f.record(); if (b) { - const uint64_t idM = SrEntryOfModel(ModelOfName("M"))->id, idB = SrEntryOfModel(ModelOfName(std::string(1, b)))->id; - const std::string providerB = std::string("WrongGPU Model ") + b; - Reset(); - g_resources[kOutput] = {dxgi::R16G16B16A16_FLOAT, 2560, 1440}; - std::string warnings; - Config c = ParseConfig("[fsr]\nruntime_options = model=M\nmodel_chosen = 1000\n", &warnings); // the launcher: M@1000 - CHECK(warnings.empty()); - c.hosted = true; - c.contextParkMs = 0; - g_asiPresent = true; - g_asiHooked = true; - g_asiModel = 'M'; - g_asiExplicit = 0; // the plugin's default entry - { - auto fe = MakeFrontEnd(c); - g_clockNow = 2000; - CHECK(CreateHosted(*fe, idM) == "WrongGPU Model M"); // first entry seen: saved untimed, not a choice - CHECK(g_ffxHas && g_ffxFile.model == 'M' && g_ffxFile.chosenAt == 0 && g_ffxSaves == 1); - CHECK(CountLog("OptiScaler's upscaler box names Model M (the first entry seen: not counted as a choice)") == 1); - g_clockNow = 3000; - CHECK(CreateHosted(*fe, idB) == providerB); // the player picks B in OptiScaler's box: newer than the launcher's M - CHECK(g_ffxFile.model == b && g_ffxFile.chosenAt == 3000 && g_ffxSaves == 2); - CHECK(CountLog("model choice conflict: the launcher chose Model M") == 1 && - CountLog("OptiScaler's upscaler box's choice wins (the most recent explicit choice)") == 1); - CHECK(CountLog((std::string("OptiScaler plugin: ") + providerB + - " selected in the host's upscaler list (the WrongGPU entry picked in OptiScaler's upscaler box").c_str()) == 1); - g_clockNow = 4000; - CHECK(CreateHosted(*fe, idB) == providerB && g_ffxFile.chosenAt == 3000 && g_ffxSaves == 2); // same entry: same time - CHECK(CreateHosted(*fe, g_versionIds[0]) == providerB && g_ffxSaves == 2); // an AMD version is not a model choice + const std::string ini = std::string("runtime_options = model=") + b + "\n"; + // (1) the launcher applied b and set OptiScaler's entry with it (record: b, seq 1, ffx=b): b runs, nothing written + wgchoice::Record next; + CHECK(wgchoice::NextRecord(nullptr, b, wgchoice::Source::Launcher, b, &next) && wgchoice::WriteRecordFile(f.record(), next, &why)); + CHECK(HookedCreate(ini.c_str(), 'M', idOf(b)) == name(b)); + CHECK(ReadRec(f.record()).seq == 1 && g_asiShown.size() == 1 && g_asiShown[0] == b); + CHECK(CountLog("selected in the host's upscaler list (the model choice record: the launcher, seq 1)") == 1); + // (2) the player picks Model M in OptiScaler's FFX box: a choice there (seq 2, source=ffx); M runs, with its line + CHECK(HookedCreate(ini.c_str(), 'M', idOf('M')) == name('M')); + wgchoice::Record r = ReadRec(f.record()); + CHECK(r.model == 'M' && r.seq == 2 && r.source == wgchoice::Source::Ffx && r.ffx == 'M'); + CHECK(CountLog((std::string("model choice: Model M picked in OptiScaler's upscaler list (seq 2, replacing Model ") + b + + " from the launcher, seq 1)").c_str()) == 1); + CHECK(CountLog((std::string("model choice conflict: wronggpu.ini's model item says Model ") + b).c_str()) == 1); + // (3) the player clicks b in the plugin's menu (the plugin writes seq 3, source=plugin, keeping ffx=M); OptiScaler's + // box still names M: that is no new choice, b runs + CHECK(wgchoice::NextRecord(&r, b, wgchoice::Source::Plugin, wgchoice::kUnknown, &next) && wgchoice::WriteRecordFile(f.record(), next, &why)); + CHECK(HookedCreate(ini.c_str(), b, idOf('M')) == name(b)); + r = ReadRec(f.record()); + CHECK(r.model == b && r.seq == 3 && r.source == wgchoice::Source::Plugin && r.ffx == 'M'); + CHECK(CountLog("picked in OptiScaler's upscaler list") == 0); + // (4) the launcher re-applies Model M (seq 4) and sets the box to M: its own index rewrite is no choice; M runs + CHECK(wgchoice::NextRecord(&r, 'M', wgchoice::Source::Launcher, 'M', &next) && wgchoice::WriteRecordFile(f.record(), next, &why)); + CHECK(HookedCreate("runtime_options = model=M\n", b, idOf('M')) == name('M')); + CHECK(ReadRec(f.record()).seq == 4 && CountLog("picked in OptiScaler's upscaler list") == 0); + // (5) a third model in the box (a build with K and L): the player's choice again (seq 5) + if (c3) { + CHECK(HookedCreate("runtime_options = model=M\n", b, idOf(c3)) == name(c3)); + r = ReadRec(f.record()); + CHECK(r.model == c3 && r.seq == 5 && r.source == wgchoice::Source::Ffx); } - // next session: the saved entry (B@3000) is read back; the launcher re-applied M at 5000 -> M - g_log.clear(); - c = ParseConfig("[fsr]\nruntime_options = model=M\nmodel_chosen = 5000\n", &warnings); - c.hosted = true; - c.contextParkMs = 0; + // the plugin's AMD entry: AMD runs; the record is untouched + const wgchoice::Record before = ReadRec(f.record()); + CHECK(HookedCreate("runtime_options = model=M\n", 0, idOf(before.ffx)).empty()); + CHECK(ReadRec(f.record()).seq == before.seq); + CHECK(CountLog("OptiScaler plugin: AMD FSR selected in the host's upscaler list") == 1); + // an AMD version in the FFX box is no model choice + const uint64_t s2 = ReadRec(f.record()).seq; + HookedCreate("runtime_options = model=M\n", 'M', g_versionIds[0]); + CHECK(ReadRec(f.record()).seq == s2); + // (6) the first create without a record: the entry the box names counts as a choice (seq 1, source=ffx) + std::error_code ec; + std::filesystem::remove(f.record(), ec); + CHECK(HookedCreate(ini.c_str(), 'M', idOf(b)) == name(b)); + r = ReadRec(f.record()); + CHECK(r.model == b && r.seq == 1 && r.source == wgchoice::Source::Ffx && r.ffx == b); + CHECK(CountLog("the first choice recorded for this game") == 1); + // (7) a corrupt record (seq overflow): said once, treated as no choice, replaced by the box's entry { - auto fe = MakeFrontEnd(c); - CHECK(CreateHosted(*fe, idB) == "WrongGPU Model M" && g_ffxSaves == 2); - CHECK(CountLog("the launcher's choice wins (the most recent explicit choice): Model M runs") == 1); + std::ofstream o(f.record(), std::ios::binary | std::ios::trunc); + o << "model=L\nseq=18446744073709551616\nsource=launcher\nffx=L\n"; } - // all three: launcher M@5000, index B@3000, plugin AMD@6000 -> AMD; plugin AMD@4000 -> the launcher's M - g_log.clear(); - g_asiModel = kChoiceAmd; - g_asiExplicit = 1; - g_asiChosenAt = 6000; - { - auto fe = MakeFrontEnd(c); - uint64_t count = 8, ids[8] = {}; - const char* names[8] = {}; - ffxQueryDescGetVersions versions{}; - versions.header.type = FFX_API_QUERY_DESC_TYPE_GET_VERSIONS; - versions.createDescType = FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE; - versions.device = kDevice; - versions.outputCount = &count; - versions.versionIds = ids; - versions.versionNames = names; - CHECK(fe->Query(nullptr, &versions.header) == FFX_API_RETURN_OK); // AMD's versions known (the AMD route) - bool amd = false; - CreateHosted(*fe, idB, &amd); - CHECK(amd && CountLog("the OptiScaler menu plugin's choice wins (the most recent explicit choice): AMD FSR runs") == 1); - g_asiChosenAt = 4000; - CHECK(CreateHosted(*fe, idB) == "WrongGPU Model M"); - } - } - g_asiPresent = present; - g_asiHooked = hooked; - g_asiModel = saved; -} - -static void TestAsiLauncherPrecedence() { - const bool present = g_asiPresent, hooked = g_asiHooked; - const char saved = g_asiModel; - // The pure rule (model_precedence.h), independent of which models this build has. - { - PluginModelChoice pd; // the plugin's default entry - LauncherModelChoice none, l{'L', 2000}, k{'K', 0}, m0{'M', 0}, m{'M', 3000}; - CHECK(DecideModel(pd, none).model == 'M' && DecideModel(pd, none).winner == ModelWinner::Default); - CHECK(DecideModel(pd, m0).model == 'M' && DecideModel(pd, m0).winner == ModelWinner::Default); - CHECK(DecideModel(pd, l).model == 'L' && DecideModel(pd, l).winner == ModelWinner::Launcher && !DecideModel(pd, l).conflict); - CHECK(DecideModel(pd, k).model == 'K' && DecideModel(pd, k).winner == ModelWinner::Launcher); // unstamped K: explicit - PluginModelChoice pk{'K', true, 1000}, pkNew{'K', true, 5000}, pkOld{'K', true, 0}, pa{kChoiceAmd, true, 1000}; - ModelDecision d = DecideModel(pk, l); // explicit K older than the launcher's L - CHECK(d.model == 'L' && d.winner == ModelWinner::Launcher && d.conflict); - CHECK(d.line.find("the OptiScaler menu plugin chose Model K (wronggpu-asi.ini) chosen=1000") != std::string::npos && - d.line.find("the launcher chose Model L (wronggpu.ini runtime_options, model_chosen) chosen=2000") != std::string::npos && - d.line.find("the launcher's choice wins (the most recent explicit choice): Model L runs") != std::string::npos); - d = DecideModel(pkNew, l); // explicit K newer than the launcher's L - CHECK(d.model == 'K' && d.winner == ModelWinner::Plugin && d.conflict && - d.line.find("the OptiScaler menu plugin's choice wins (the most recent explicit choice): Model K runs") != std::string::npos); - // P2: untimed explicit choices rank as the OLDEST; a tie (also: none timed) goes to the launcher - d = DecideModel(pkOld, LauncherModelChoice{'L', 0}); // neither recorded a time - CHECK(d.model == 'L' && d.winner == ModelWinner::Launcher && d.conflict && - d.line.find("no choice recorded a time") != std::string::npos && d.line.find("most recent") == std::string::npos); - d = DecideModel(pkOld, l); // an earlier version's K (no time) against a timed launcher L - CHECK(d.model == 'L' && d.conflict && d.line.find("Model K (wronggpu-asi.ini) no time recorded, counted as the oldest") != std::string::npos); - d = DecideModel(pk, LauncherModelChoice{'L', 0}); // a timed plugin K against an untimed launcher L: the plugin's - CHECK(d.model == 'K' && d.winner == ModelWinner::Plugin && - d.line.find("Model L (wronggpu.ini runtime_options, model_chosen) no time recorded, counted as the oldest") != std::string::npos); - d = DecideModel(PluginModelChoice{'K', true, 2000}, l); // an exact tie: the launcher, the deliberate settings tool - CHECK(d.model == 'L' && d.winner == ModelWinner::Launcher && d.line.find("the same time") != std::string::npos); - d = DecideModel(pa, l); - CHECK(d.model == 'L' && d.conflict && d.line.find("chose AMD FSR") != std::string::npos); - d = DecideModel(pa, m); // the launcher went back to Model M after the player chose AMD in the game - CHECK(d.model == 'M' && d.winner == ModelWinner::Launcher && d.conflict); - d = DecideModel(pk, LauncherModelChoice{'K', 9000}); // the same model: no conflict - CHECK(d.model == 'K' && !d.conflict && d.line.empty()); - CHECK(DecideModel(pa, none).model == kChoiceAmd && DecideModel(pa, m0).model == kChoiceAmd); - // P1: the launcher RE-APPLIES the same model after a newer in-game choice: its new stamp makes it the newest. - // (L@1000, plugin K@2000, launcher re-applies L@3000 -> L; the same for K and M.) - struct Seq { char launcherModel; PluginModelChoice plugin; }; - for (const Seq& q : {Seq{'L', PluginModelChoice{'K', true, 2000}}, Seq{'K', PluginModelChoice{'L', true, 2000}}, - Seq{'M', PluginModelChoice{'K', true, 2000}}}) { - CHECK(DecideModel(q.plugin, LauncherModelChoice{q.launcherModel, 1000}).model == q.plugin.model); // before the re-apply - d = DecideModel(q.plugin, LauncherModelChoice{q.launcherModel, 3000}); // after it - CHECK(d.model == q.launcherModel && d.winner == ModelWinner::Launcher && d.conflict); - } - // P3: the OptiScaler FFX index as a third source. FfxChoiceSeen: the first entry seen is untimed (not a choice); a - // different one later is stamped; the same one keeps its time; no WrongGPU entry seen changes nothing. - FfxModelChoice f0; - FfxModelChoice f1 = FfxChoiceSeen(f0, 'M', 100); - CHECK(f1.model == 'M' && f1.chosenAt == 0 && !f1.Explicit()); - FfxModelChoice f2 = FfxChoiceSeen(f1, 'L', 200); - CHECK(f2.model == 'L' && f2.chosenAt == 200 && f2.Explicit()); - CHECK(FfxChoiceSeen(f2, 'L', 300).chosenAt == 200 && FfxChoiceSeen(f2, kChoiceNone, 300).model == 'L'); - FfxModelChoice f3 = ParseFfxChoiceFile(FormatFfxChoiceFile(f2)); - CHECK(f3.model == 'L' && f3.chosenAt == 200); - CHECK(ParseFfxChoiceFile("model=k\r\nchosen=133000000000000000\r\n").chosenAt == 133000000000000000ull && - ParseFfxChoiceFile("model=k\r\n").model == 'K' && ParseFfxChoiceFile("model=Q\r\nchosen=5\r\n").model == kChoiceNone && - ParseFfxChoiceFile("model=Q\r\nchosen=5\r\n").chosenAt == 0 && ParseFfxChoiceFile("model=M\r\nchosen=x\r\n").chosenAt == 0); - // all three sources, in every order of their times: the latest explicit choice wins; launcher L, index K, plugin M - const uint64_t orders[6][3] = {{1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}}; - for (const auto& o : orders) { - const LauncherModelChoice lc{'L', 1000 * o[0]}; - const FfxModelChoice fc{'K', 1000 * o[1]}; - const PluginModelChoice pc{'M', true, 1000 * o[2]}; - const char expected = o[0] == 3 ? 'L' : o[1] == 3 ? 'K' : 'M'; - d = DecideModel(pc, lc, fc); - CHECK(d.model == expected && d.conflict); - CHECK(d.line.find("the launcher chose Model L") != std::string::npos && - d.line.find("OptiScaler's upscaler box chose Model K") != std::string::npos && - d.line.find("the OptiScaler menu plugin chose Model M") != std::string::npos); - } - // ties among three: launcher, then the index, then the plugin; an untimed index entry is not a choice - CHECK(DecideModel(PluginModelChoice{'M', true, 5}, LauncherModelChoice{'L', 5}, FfxModelChoice{'K', 5}).model == 'L'); - CHECK(DecideModel(PluginModelChoice{'M', true, 5}, LauncherModelChoice{}, FfxModelChoice{'K', 5}).model == 'K'); - CHECK(DecideModel(PluginModelChoice{'M', true, 5}, LauncherModelChoice{}, FfxModelChoice{'K', 0}).model == 'M'); - CHECK(DecideModel(PluginModelChoice{}, LauncherModelChoice{}, FfxModelChoice{'L', 7}).winner == ModelWinner::Ffx); - } - // Config: model_chosen is read; a bad value is said and ignored. - { - std::string w; - CHECK(ParseConfig("[fsr]\nruntime_options = model=L\nmodel_chosen = 134077000000000000\n", &w).modelChosenAt == 134077000000000000ull && w.empty()); - CHECK(ParseConfig("[fsr]\nmodel_chosen = soon\n", &w).modelChosenAt == 0 && w.find("bad value") != std::string::npos); - } - AsiRun r; -#if WRONGGPU_MODEL_L - // (a) the plugin's default entry + the launcher's Model L -> Model L, no conflict line (the audit's case: before this - // fix Model M ran and read Model M's file). - r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", 'M', 0, 0); - CHECK(r.provider == "WrongGPU Model L" && EndsWith(r.options, "model=L") && !r.amd); - CHECK(CountLog("OptiScaler plugin: WrongGPU Model L selected in the host's upscaler list (the launcher's model choice") == 1); - CHECK(CountLog("model choice conflict") == 0 && g_asiShown.size() == 1 && g_asiShown[0] == 'L'); - // ... also with no time on the launcher's model=L (a hand-edited file): the plugin's default never decides over it - r = RunAsi("[fsr]\nruntime_options = model=L\n", 'M', -1, 0); - CHECK(r.provider == "WrongGPU Model L" && EndsWith(r.options, "model=L")); - // (c) an explicit plugin choice older than the launcher's Model L -> Model L, with the conflict line once - r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", kChoiceAmd, 1, 1000); - CHECK(r.provider == "WrongGPU Model L" && EndsWith(r.options, "model=L") && !r.amd); - CHECK(CountLog("model choice conflict: the launcher chose Model L (wronggpu.ini runtime_options, model_chosen) chosen=2000, " - "the OptiScaler menu plugin chose AMD FSR (wronggpu-asi.ini) chosen=1000; the launcher's choice wins") == 1); - // (d) an explicit plugin choice newer than the launcher's -> the plugin's, with the conflict line - r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", 'M', 1, 3000); - CHECK(r.provider == "WrongGPU Model M" && EndsWith(r.options, "model=M")); - CHECK(CountLog("model choice conflict") == 1 && CountLog("the OptiScaler menu plugin's choice wins (the most recent explicit choice): Model M runs") == 1); - r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", kChoiceAmd, 1, 3000); // ... AMD, newer - CHECK(r.amd && r.provider.empty() && r.runtimeCreates == 0 && - CountLog("OptiScaler plugin: AMD FSR selected in the host's upscaler list") == 1); - CHECK(g_asiShown.size() == 1 && g_asiShown[0] == kChoiceAmd); - // the plugin's own Model L entry (explicit) with the launcher at its default - r = RunAsi("[fsr]\nruntime_options = model=M\n", 'L', 1, 500); - CHECK(r.provider == "WrongGPU Model L" && EndsWith(r.options, "model=L") && CountLog("model choice conflict") == 0); - // (e) Model L chosen (by the launcher, over the plugin's default) and Model L's file missing: the existing refusal -- - // the create is refused with its reason, the runtime is not asked, AMD's FSR upscales (fallback_to_amd); no silent - // switch to Model M or its file. - r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", 'M', 0, 0, - {"G:\\game\\WrongGPU\\model\\model.wgcm", "G:\\game\\WrongGPU\\model\\K\\model.wgcm"}, true); - CHECK(r.runtimeCreates == 0 && r.amd); - CHECK(CountLog("Model L is chosen but no converted Model L was found") >= 1 && CountLog("model: no converted Model L found") == 1); - r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", 'M', 0, 0, {"G:\\game\\WrongGPU\\model\\L\\model.wgcm"}, true); - CHECK(r.runtimeCreates == 1 && !r.amd && r.provider == "WrongGPU Model L" && - r.options.find(";model_dir=G:\\game\\WrongGPU\\model") != std::string::npos); -#else - // A front end without Model L: the launcher's model=L is refused at start-up (IgnoreModelL, its own note), so no - // launcher choice is left: Model M. A plugin built with Model L whose saved entry is Model L, with this front end: - // Model M, said once. - r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", 'M', 0, 0); - CHECK(r.provider == "WrongGPU Model M" && EndsWith(r.options, "model=M")); - CHECK(CountLog("is refused: Model L is not part of this build of the front end") == 1); - r = RunAsi("[fsr]\nruntime_options = model=M\n", 'L', 1, 500); - CHECK(r.provider == "WrongGPU Model M" && EndsWith(r.options, "model=M")); - CHECK(CountLog("note: OptiScaler plugin: Model L is not part of this build of the front end; Model M is used") == 1); -#endif -#if WRONGGPU_MODEL_K - // (b) the plugin unset (no file: its default entry) + the launcher's Model K -> Model K - r = RunAsi("[fsr]\nruntime_options = model=K\nmodel_chosen = 2000\n", 'M', 0, 0); - CHECK(r.provider == "WrongGPU Model K" && EndsWith(r.options, "model=K") && CountLog("model choice conflict") == 0); -#if WRONGGPU_MODEL_L - // explicit K older than the launcher's L -> L; explicit K newer -> K (both with the conflict line) - r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", 'K', 1, 1000); - CHECK(r.provider == "WrongGPU Model L" && EndsWith(r.options, "model=L") && CountLog("model choice conflict") == 1); - r = RunAsi("[fsr]\nruntime_options = model=L\nmodel_chosen = 2000\n", 'K', 1, 3000); - CHECK(r.provider == "WrongGPU Model K" && EndsWith(r.options, "model=K") && CountLog("model choice conflict") == 1); - // the launcher's K newer than the plugin's L - r = RunAsi("[fsr]\nruntime_options = model=K\nmodel_chosen = 4000\n", 'L', 1, 3000); - CHECK(r.provider == "WrongGPU Model K" && CountLog("the launcher's choice wins (the most recent explicit choice): Model K runs") == 1); -#endif -#else - // A front end without Model K: the launcher's model=K is dropped at start-up (IgnoreModelK, its own note): Model M. - // A saved Model K of the plugin: Model M, said once. - r = RunAsi("[fsr]\nruntime_options = model=K\nmodel_chosen = 2000\n", 'M', 0, 0); - CHECK(r.provider == "WrongGPU Model M" && EndsWith(r.options, "model=M")); - CHECK(CountLog("is ignored: Model K is not part of this build") == 1); - r = RunAsi("[fsr]\nruntime_options = model=M\n", 'K', 1, 500); - CHECK(r.provider == "WrongGPU Model M" && EndsWith(r.options, "model=M")); - CHECK(CountLog("note: OptiScaler plugin: Model K is not part of this build of the front end; Model M is used") == 1); + CHECK(HookedCreate("runtime_options = model=M\n", 'M', idOf('M')) == name('M')); + CHECK(CountLog("is corrupt (seq is not a number") == 1); + r = ReadRec(f.record()); + CHECK(r.model == 'M' && r.seq == 1 && r.source == wgchoice::Source::Ffx); +#ifdef _WIN32 + // (8) a record another program holds open without sharing: not read, NEVER written over; the launcher's item decides + HANDLE lock = CreateFileW(f.record().c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + CHECK(lock != INVALID_HANDLE_VALUE); + CHECK(HookedCreate(ini.c_str(), 'M', idOf(b)) == name(b)); + CHECK(CountLog("cannot be read") == 1); + CloseHandle(lock); + CHECK(ReadRec(f.record()).model == 'M' && ReadRec(f.record()).seq == 1); // unchanged #endif - // No model item at all and the plugin's default: Model M as before, no conflict, nothing extra in the log. - r = RunAsi("[fsr]\nruntime_options = timing_log=1\n", 'M', -1, 0); - CHECK(r.provider == "WrongGPU Model M" && EndsWith(r.options, "model=M") && CountLog("model choice conflict") == 0); - CHECK(CountLog("OptiScaler plugin: WrongGPU Model M selected in the host's upscaler list") == 1 && CountLog("launcher's model choice") == 0); + } else { + // Model M only: the record still says what runs and the box's first entry is recorded + CHECK(HookedCreate("runtime_options = model=M\n", 'M', idOf('M')) == name('M')); + CHECK(ReadRec(f.record()).model == 'M' && ReadRec(f.record()).seq == 1); + } + g_choiceRecord.clear(); g_asiPresent = present; g_asiHooked = hooked; g_asiModel = saved; @@ -3821,8 +3608,7 @@ int main() { TestAsiPluginHooked(); TestAsiPluginNotHooked(); TestAsiPluginPresetK(); - TestAsiLauncherPrecedence(); - TestAsiFfxIndexChoice(); + TestAsiChoiceRecord(); { Config profile; const auto original = profile.BackendOptions(); diff --git a/clean/fsr/tests/test_model_choice_record.cpp b/clean/fsr/tests/test_model_choice_record.cpp new file mode 100644 index 00000000..4db9c04b --- /dev/null +++ b/clean/fsr/tests/test_model_choice_record.cpp @@ -0,0 +1,197 @@ +// SPDX-License-Identifier: MIT +// Unit tests of the game's model choice record (clean/fsr/src/model_choice_record.h) on REAL files in a fresh folder under +// the system temporary folder: the strict format, seq order, the OptiScaler list rule (ffx), atomic replacement, a stale +// temporary file, corrupt and overflowing records, and a reader running while a writer replaces the record. +#include +#include +#include +#include +#include + +#include "../src/model_choice_record.h" + +using namespace wgchoice; +namespace fs = std::filesystem; + +static int g_failures = 0, g_checks = 0; +#define CHECK(cond) \ + do { \ + ++g_checks; \ + if (!(cond)) { ++g_failures; std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); } \ + } while (0) + +namespace { + +std::string Valid(const char* model = "L", const char* seq = "7", const char* source = "launcher", const char* ffx = "L") { + return std::string("; c\r\n\r\nmodel=") + model + "\r\nseq=" + seq + "\r\nsource=" + source + "\r\nffx=" + ffx + "\r\n"; +} + +bool Parses(const std::string& text, Record* r = nullptr) { + Record tmp; + std::string why; + return ParseRecord(text, r ? r : &tmp, &why); +} + +void TestStrictFormat() { + Record r; + CHECK(Parses(Valid(), &r) && r.model == 'L' && r.seq == 7 && r.source == Source::Launcher && r.ffx == 'L'); + CHECK(Parses("model=M\nseq=1\nsource=ffx\nffx=-\n", &r) && r.model == 'M' && r.source == Source::Ffx && r.ffx == kUnknown); + CHECK(Parses("model=K\nseq=18446744073709551615\nsource=plugin\nffx=K", &r) && r.seq == UINT64_MAX && r.source == Source::Plugin); + CHECK(!Parses("")); // no record + CHECK(!Parses("model=L\nseq=7\nsource=launcher\n")); // a key missing + CHECK(!Parses(Valid() + "model=K\r\n")); // a key twice + CHECK(!Parses(Valid() + "extra=1\r\n")); // an unknown key + CHECK(!Parses(Valid("l")) && !Parses(Valid("Q")) && !Parses(Valid("LL"))); // model: M, K or L exactly + CHECK(!Parses(Valid("L", "0")) && !Parses(Valid("L", "-1")) && !Parses(Valid("L", "7x")) && !Parses(Valid("L", ""))); + CHECK(!Parses(Valid("L", "18446744073709551616"))); // 2^64: overflow refused + CHECK(!Parses(Valid("L", "99999999999999999999"))); // 20 digits, overflow refused + CHECK(!Parses(Valid("L", "000000000000000000001"))); // 21 digits refused + CHECK(!Parses(Valid("L", "7", "game")) && !Parses(Valid("L", "7", "Launcher"))); + CHECK(!Parses(Valid("L", "7", "launcher", "x")) && !Parses(Valid("L", "7", "launcher", ""))); + CHECK(!Parses("model = L\nseq=7\nsource=launcher\nffx=L\n")); // no spaces around '=' + CHECK(!Parses("model=L\nseq=7\nsource=launcher\nffx=L\ngarbage\n")); // a line that is not key=value + CHECK(Parses(FormatRecord(Record{'K', 42, Source::Plugin, 'M'}), &r) && r.model == 'K' && r.seq == 42 && r.ffx == 'M'); +} + +void TestOrderAndFfxRule() { + Record a, b, c; + CHECK(NextRecord(nullptr, 'L', Source::Launcher, 'L', &a) && a.seq == 1 && a.ffx == 'L'); + CHECK(NextRecord(&a, 'K', Source::Plugin, kUnknown, &b) && b.seq == 2 && b.model == 'K' && b.ffx == 'L'); // keeps ffx + Record max{'M', UINT64_MAX, Source::Launcher, 'M'}; + CHECK(!NextRecord(&max, 'L', Source::Launcher, 'L', &c)); // seq cannot grow: refused, never wraps to 0 + // the list names the entry the record knows: nothing (also after the plugin's choice: the list did not move) + CHECK(FfxObservation(&b, 'L', &c) == FfxStep::None); + CHECK(FfxObservation(&b, kUnknown, &c) == FfxStep::None); // no WrongGPU entry (an AMD version) + // another entry: the player's choice in OptiScaler's list + CHECK(FfxObservation(&b, 'M', &c) == FfxStep::Choice && c.model == 'M' && c.seq == 3 && c.source == Source::Ffx && c.ffx == 'M'); + // the first create without a record: the entry seen counts as a choice + CHECK(FfxObservation(nullptr, 'K', &c) == FfxStep::Choice && c.model == 'K' && c.seq == 1 && c.ffx == 'K'); + // a record that does not know the list's entry: adopted, not a choice (same model, same seq) + Record unk{'L', 5, Source::Plugin, kUnknown}; + CHECK(FfxObservation(&unk, 'M', &c) == FfxStep::Adopt && c.model == 'L' && c.seq == 5 && c.ffx == 'M'); + CHECK(FfxObservation(&max, 'L', &c) == FfxStep::None); // seq at its end: no write +} + +struct Folder { + fs::path dir; + Folder() { + dir = fs::temp_directory_path() / ("wg-choice-test-" + std::to_string( +#ifdef _WIN32 + GetCurrentProcessId() +#else + 0 +#endif + )); + std::error_code ec; + fs::create_directories(dir / kStateFolder, ec); + } + fs::path record() const { return RecordPathIn(dir); } + ~Folder() { // our own files only, one by one + std::error_code ec; + for (auto& e : fs::directory_iterator(dir / kStateFolder, ec)) fs::remove(e.path(), ec); + fs::remove(dir / kStateFolder, ec); + fs::remove(dir, ec); + } +}; + +void WriteRaw(const fs::path& p, const std::string& text) { + std::ofstream f(p, std::ios::binary | std::ios::trunc); + f << text; +} + +void TestFiles() { + Folder f; + Record r; + std::string why; + CHECK(ReadRecordFile(f.record(), &r, &why) == ReadResult::Missing); + // each source winning in turn: launcher L, then the player in OptiScaler's list (K), then the plugin's menu (M), then the + // launcher again (L): the highest seq is always the record + Record cur, next; + CHECK(NextRecord(nullptr, 'L', Source::Launcher, 'L', &next) && WriteRecordFile(f.record(), next, &why)); + CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Ok && cur.model == 'L' && cur.seq == 1 && cur.source == Source::Launcher); + CHECK(FfxObservation(&cur, 'K', &next) == FfxStep::Choice && WriteRecordFile(f.record(), next, &why)); + CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Ok && cur.model == 'K' && cur.seq == 2 && cur.source == Source::Ffx); + CHECK(NextRecord(&cur, 'M', Source::Plugin, kUnknown, &next) && WriteRecordFile(f.record(), next, &why)); + CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Ok && cur.model == 'M' && cur.seq == 3 && cur.ffx == 'K'); + CHECK(FfxObservation(&cur, 'K', &next) == FfxStep::None); // the list still names K: no false choice after the plugin's + // the launcher applies L and sets the list's entry with it: its own index rewrite is never a choice in the game + CHECK(NextRecord(&cur, 'L', Source::Launcher, 'L', &next) && WriteRecordFile(f.record(), next, &why)); + CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Ok && cur.model == 'L' && cur.seq == 4 && cur.ffx == 'L'); + CHECK(FfxObservation(&cur, 'L', &next) == FfxStep::None); + // a stale temporary file a crash left next to the record (and garbage in it): never read, writes still work + const fs::path stale = f.record().string() + ".999.0.0.tmp"; + WriteRaw(stale, "model=K\nseq=999999"); + CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Ok && cur.seq == 4); + CHECK(NextRecord(&cur, 'K', Source::Plugin, kUnknown, &next) && WriteRecordFile(f.record(), next, &why)); + CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Ok && cur.seq == 5 && cur.model == 'K'); + // only a temporary file, no record (a crash before the move): no record + std::error_code ec; + fs::remove(f.record(), ec); + CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Missing); + // corrupt and overflowing records: Corrupt, never a partial choice + WriteRaw(f.record(), Valid("L", "18446744073709551616")); + CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Corrupt && why.find("seq") != std::string::npos); + WriteRaw(f.record(), "model=L\nseq=3\n"); + CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Corrupt); + WriteRaw(f.record(), std::string(4096, 'x')); + CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Corrupt); + // ... and a write over a corrupt record replaces it whole + CHECK(NextRecord(nullptr, 'M', Source::Ffx, 'M', &next) && WriteRecordFile(f.record(), next, &why)); + CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Ok && cur.seq == 1 && cur.model == 'M'); + fs::remove(stale, ec); + // no temporary file is left behind by successful writes + int tmps = 0; + for (auto& e : fs::directory_iterator(f.dir / kStateFolder, ec)) + if (e.path().extension() == ".tmp") ++tmps; + CHECK(tmps == 0); +} + +// A reader that runs while a writer replaces the record many times sees a whole record every time (or, before the first +// write, none), with seq never going down: never an empty or partial file. +void TestConcurrentReader() { + Folder f; + std::atomic done{false}; + std::atomic partial{0}, reads{0}, backwards{0}; + std::thread reader([&] { + uint64_t last = 0; + while (!done.load()) { + Record r; + std::string why; + const ReadResult rr = ReadRecordFile(f.record(), &r, &why); + if (rr == ReadResult::Corrupt) ++partial; + if (rr == ReadResult::Ok) { + ++reads; + if (r.seq < last) ++backwards; + last = r.seq; + } + } + }); + Record cur, next; + int failedWrites = 0; + for (int i = 0; i < 400; ++i) { + std::string why; + NextRecord(i ? &cur : nullptr, "MKL"[i % 3], Source::Launcher, "MKL"[i % 3], &next); + if (WriteRecordFile(f.record(), next, &why)) cur = next; + else ++failedWrites; + } + done.store(true); + reader.join(); + CHECK(partial.load() == 0); + CHECK(backwards.load() == 0); + CHECK(failedWrites == 0); + CHECK(reads.load() > 0); + Record r; + std::string why; + CHECK(ReadRecordFile(f.record(), &r, &why) == ReadResult::Ok && r.seq == 400); +} + +} // namespace + +int main() { + TestStrictFormat(); + TestOrderAndFfxRule(); + TestFiles(); + TestConcurrentReader(); + std::printf("%d checks, %d failures\n", g_checks, g_failures); + return g_failures ? 1 : 0; +} diff --git a/clean/installer/src/wg_core/launcher.cpp b/clean/installer/src/wg_core/launcher.cpp index f2f2fab9..5d477a7c 100644 --- a/clean/installer/src/wg_core/launcher.cpp +++ b/clean/installer/src/wg_core/launcher.cpp @@ -14,6 +14,8 @@ #include #include "gamerules.h" +#include "../../../fsr/asi/asi_thunk.h" // wronggpu-asi.ini (ParseSelection / FormatSelection), pure +#include "../../../fsr/src/model_choice_record.h" // the game's model choice record #include "json_writer.h" #include "model.h" #include "optiscaler.h" @@ -738,6 +740,28 @@ static bool OptInKey(const wstring& exe, const IniKeyChange& c) { return false; } +// The launcher's entry in the game's model choice record (wronggpu-setup\model-choice.ini; model_choice_record.h): read, +// the next seq, written atomically. A record that cannot be read is not written over (said in the notes). +void WriteLauncherModelChoice(Context& ctx, const wstring& dir, char model, char ffx, std::vector& notes, + std::vector* warnings) { + const std::filesystem::path path = Join(StateDir(dir), wgchoice::kRecordFile); + wgchoice::Record cur, next; + std::string why; + const wgchoice::ReadResult rr = wgchoice::ReadRecordFile(path, &cur, &why); + auto warn = [&](const wstring& w) { + LogLine(ctx, w); + notes.push_back(w); + if (warnings) warnings->push_back(w); + }; + if (rr == wgchoice::ReadResult::Unreadable) return warn(L"The model choice record could not be read (" + FromUtf8(why) + L"); it was not changed."); + if (rr == wgchoice::ReadResult::Corrupt) LogLine(ctx, L"model-choice.ini was corrupt (" + FromUtf8(why) + L"); written anew"); + if (!wgchoice::NextRecord(rr == wgchoice::ReadResult::Ok ? &cur : nullptr, model, wgchoice::Source::Launcher, ffx, &next)) + return warn(L"The model choice record could not take another choice (its sequence number is at its end)."); + if (!wgchoice::WriteRecordFile(path, next, &why)) return warn(L"The model choice record could not be written (" + FromUtf8(why) + L")."); + LogLine(ctx, wstring(L"model choice record: Model ") + wchar_t(model) + L" (seq " + std::to_wstring(next.seq) + L", source=launcher, ffx=" + + wchar_t(next.ffx) + L")"); +} + Profile GameProfile(const wstring& dir) { Profile p; if (!LoadProfile(ProfilePath(dir), p)) { @@ -769,12 +793,18 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto if (warnings) warnings->push_back(w); } } + string winiBefore, winiAfter, optiAfter; // the model choice record (below) + bool haveOpti = false; auto renderFile = [&](const wchar_t* name, bool opti) { const wstring path = Join(dir, name); string in; const bool had = ReadAll(path, in); if (opti && !had) return; // OptiScaler.ini: only an existing file (ours) is changed string out; wstring why; + auto keep = [&] { + if (opti) { optiAfter = out; haveOpti = true; } + else { winiBefore = in; winiAfter = out; } + }; if (opti) { RenderOptiIni(q, in, out, ¬es); bool wrote = false; @@ -784,9 +814,8 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto JournalChanges(m.inikeys, name, in, out); recordChanged = recordChanged || out != in; } - // (a model the files cannot run yet, written as Model M above, is not stamped as the player's choice) - else if (!RenderWronggpuIni(q, in, out, &why, 0, modelChosen && q.get("model") == p.get("model"))) - Fail(L"Settings not applied: " + why, EXIT_USAGE); + else if (!RenderWronggpuIni(q, in, out, &why)) Fail(L"Settings not applied: " + why, EXIT_USAGE); + keep(); if (out == in && (had || out.empty())) return; // unchanged, or nothing to write into a missing file WriteFileAtomic(path, out.data(), out.size()); const wstring h = Sha256Bytes(out.data(), out.size()); @@ -795,6 +824,24 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto }; renderFile(L"wronggpu.ini", false); if (HostedRecord(m)) renderFile(L"OptiScaler.ini", true); + // The model choice record (clean/fsr/src/model_choice_record.h): the launcher's model choice, with the next seq, when the + // player explicitly applied a model (also the same one again) or the model the files run changed. ffx: the WrongGPU entry + // OptiScaler.ini now names (set with the model), so the front end never takes that entry for a choice in the game. (A + // model the files cannot run yet, written as Model M above, is recorded as what runs: Model M.) + const char modelBefore = ModelOfWronggpuIni(winiBefore), modelAfter = ModelOfWronggpuIni(winiAfter); + if (modelChosen || modelBefore != modelAfter) { + const char model = modelAfter ? modelAfter : 'M'; + WriteLauncherModelChoice(ctx, dir, model, haveOpti ? ModelEntryOfOptiIni(optiAfter) : wgchoice::kUnknown, notes, warnings); + if (HostedRecord(m)) { // the menu plugin's AMD entry chosen earlier: the launcher's model choice is newer + const wstring asi = Join(dir, L"wronggpu-asi.ini"); + string text; + if (ReadAll(asi, text) && wgasi::ParseSelection(text) == wgasi::kModelAmd) { + const string fresh = wgasi::FormatSelection(model); + WriteFileAtomic(asi, fresh.data(), fresh.size()); + notes.push_back(L"wronggpu-asi.ini: WrongGPU selected again in OptiScaler's list (the launcher's model choice is newer than AMD's FSR there)"); + } + } + } if (RecordHasRr(m)) { // Ray Reconstruction (rr.h): the RR plugin's settings file (RR stays off while its data is not ready) const wstring path = Join(dir, kRrSettings); string in; diff --git a/clean/installer/src/wg_core/launcher.h b/clean/installer/src/wg_core/launcher.h index 94edce5d..1bb167c2 100644 --- a/clean/installer/src/wg_core/launcher.h +++ b/clean/installer/src/wg_core/launcher.h @@ -180,7 +180,7 @@ struct OpRequest { std::vector> movePluginsList, moveModsList; bool otherSetupOk = false; // 0.6.1: Clean up / Adopt of WrongGPU files another mod's setup uses, confirmed (--confirm-other-setup) bool hasProfile = false; // apply: this profile (else the game's profile.ini); install: the profile a new install starts with - bool modelChosen = false; // apply: the player explicitly applied the profile's model (set model=...): stamped + bool modelChosen = false; // apply: the player explicitly applied the profile's model (set model=...): recorded Profile profile; // apply, the OptiScaler tab: edits of editable keys ("Section.Key", value); reset: the editable keys back to what the // install wrote (inikey journal, byte for byte); keep: values OptiScaler's menu saved over the launcher's are kept. @@ -211,10 +211,14 @@ bool NeedsElevation(const wstring& dir); // Writes the profile into the game's files (wronggpu.ini, OptiScaler.ini), the record's hashes of those files and // owned-files.json; saves profile.ini. // warnings: what could not be done that the player should hear (rr_config_fix: the game's Engine.ini, rrconfig.h). -// modelChosen: the player explicitly applied the profile's model (`set model=`): wronggpu.ini's model_chosen is -// stamped now even when the model is the same (profile.h RenderWronggpuIni). +// modelChosen: the player explicitly applied the profile's model (`set model=`): the game's model choice record +// gets the launcher's choice with the next seq even when the model is the same (clean/fsr/src/model_choice_record.h). void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vector& notes, std::vector* warnings = nullptr, bool modelChosen = false); +// The launcher's model choice into the game's model choice record (wronggpu-setup\model-choice.ini), with the next seq; +// ffx: the WrongGPU entry OptiScaler.ini names now ('-' when not known). +void WriteLauncherModelChoice(Context& ctx, const wstring& dir, char model, char ffx, std::vector& notes, + std::vector* warnings); Profile GameProfile(const wstring& dir); // profile.ini, else the profile its wronggpu.ini implies // The OptiScaler tab: reset / keep / edits of OpRequest written into the installed OptiScaler.ini with the inikey // journal in the record. Nothing to do: no change. diff --git a/clean/installer/src/wg_core/profile.cpp b/clean/installer/src/wg_core/profile.cpp index 918e88ef..b35d296f 100644 --- a/clean/installer/src/wg_core/profile.cpp +++ b/clean/installer/src/wg_core/profile.cpp @@ -4,7 +4,6 @@ #include #include -#include #include "record.h" #include "settings.h" @@ -284,12 +283,7 @@ std::map EffectiveSettings(const string& wronggpuIni, const stri return eff; } -uint64_t NowFileTime() { - using namespace std::chrono; - return uint64_t(duration_cast(system_clock::now().time_since_epoch()).count() / 100) + 116444736000000000ull; -} - -bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* why, uint64_t now, bool modelChosen) { +bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* why) { for (auto& d : kSettings) { if (!ValidateSetting(d, p.get(d.key), nullptr, why)) return false; } @@ -327,10 +321,10 @@ bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* if (FindSetting("model")) { auto isModel = [](const std::pair& kv) { return LowerA(kv.first) == "model"; }; const string want = p.get("model"); - if (want == "l" || want == "k" || (modelChosen && want == "m")) { // (Model M explicitly applied: model=M last) + if (want == "l" || want == "k") { std::vector> kept; for (auto& kv : items) if (!isModel(kv)) kept.push_back(kv); - kept.push_back({"model", want == "k" ? "K" : want == "l" ? "L" : "M"}); + kept.push_back({"model", want == "k" ? "K" : "L"}); items = kept; } else { for (auto& kv : items) { @@ -343,21 +337,33 @@ bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* const string joined = JoinOptions(items); // the line is rewritten only when its items change (a player's spacing and comment stay otherwise) if (hadOptions ? joined != JoinOptions(SplitOptions(options)) : !joined.empty()) text = IniSet(text, hadOptions ? section : "fsr", "runtime_options", joined); - // the model choice's time (profile.h): written when the model the front end runs changes, for any model letter, and - // when the player explicitly applied a model (also the same one again) - auto lastModel = [](const string& opts) { - string m; - for (auto& kv : SplitOptions(opts)) if (LowerA(kv.first) == "model") m = LowerA(TrimA(kv.second)); - return m; - }; - const string modelBefore = hadOptions ? lastModel(options) : string(), modelAfter = lastModel(joined); - if (!modelAfter.empty() && (modelAfter != modelBefore || modelChosen)) - text = IniSet(text, hadOptions ? section : "fsr", "model_chosen", - std::to_string(now ? now : NowFileTime())); out = text; return true; } +char ModelOfWronggpuIni(const string& text) { + string options, section; + if (!IniGetFrontEnd(text, "runtime_options", &options, §ion)) return 0; + string m; + for (auto& kv : SplitOptions(options)) if (LowerA(kv.first) == "model") m = TrimA(kv.second); + if (m.size() != 1) return 0; + const char c = char(toupper((unsigned char)m[0])); + return c == 'M' || c == 'K' || c == 'L' ? c : 0; +} + +char ModelEntryOfOptiIni(const string& text) { + string cur; + if (!IniHasKey(text, "WrongGPU", "UpscalerIndex", &cur) && !IniHasKey(text, "FSR", "UpscalerIndex", &cur)) return '-'; + cur = TrimA(cur); +#if WRONGGPU_MODEL_L + if (cur == kModelLEntryIndex) return 'L'; +#endif +#if WRONGGPU_MODEL_K || WRONGGPU_PRESET_K + if (cur == kModelKEntryIndex) return 'K'; +#endif + return cur == "0" ? 'M' : '-'; +} + bool RenderOptiIni(const Profile& p, const string& in, string& out, std::vector* notes) { out = in; // the model (WRONGGPU_MODEL_L / WRONGGPU_MODEL_K builds): the entry of WrongGPU's list OptiScaler starts with. OptiScaler diff --git a/clean/installer/src/wg_core/profile.h b/clean/installer/src/wg_core/profile.h index fb2eb8c3..515f5975 100644 --- a/clean/installer/src/wg_core/profile.h +++ b/clean/installer/src/wg_core/profile.h @@ -75,17 +75,13 @@ std::map EffectiveSettings(const string& wronggpuIni, const stri // runtime items removed from runtime_options (and their own lines) and the non-default ones appended in a fixed // order; unmanaged items and every other line stay as they are. OptiScaler keys only where the key already exists. // false with *why when a profile value does not validate (nothing is rendered then). -// When the rendering changes the last model item of runtime_options (the model the front end runs), or `modelChosen` -// says the player explicitly applied a model (also the same one again; Model M then becomes the last model item), it -// also writes model_chosen = `now` (Windows FILETIME, 100 ns since 1601 UTC; 0: the current time) in that section: the -// time of the launcher's model choice, which the front end weighs against the OptiScaler side's choices (the plugin's -// menu, the entry picked in OptiScaler's FFX box; clean/fsr/src/model_precedence.h: the most recent explicit choice -// wins; a tie goes to the launcher). Otherwise an unchanged model item leaves -// model_chosen as it is (another setting applied is not a model choice). -bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* why, uint64_t now = 0, bool modelChosen = false); -// The current time in Windows FILETIME units (100 ns since 1601-01-01 UTC), the unit every model choice is stamped in. -uint64_t NowFileTime(); +bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* why); bool RenderOptiIni(const Profile& p, const string& in, string& out, std::vector* notes = nullptr); +// The model a wronggpu.ini text runs: its last runtime_options model item, 'M', 'K' or 'L'; 0 without one. +char ModelOfWronggpuIni(const string& text); +// The WrongGPU model entry an OptiScaler.ini text's UpscalerIndex names ([WrongGPU] of OptiScaler 10's slot, else [FSR]): +// 'M' (0), 'K' (kModelKEntryIndex, a build with Model K), 'L' (kModelLEntryIndex, a build with the L choice); '-' otherwise. +char ModelEntryOfOptiIni(const string& text); // The profile a 0.5.x install implies: the effective values of its wronggpu.ini and OptiScaler.ini (defaults and the // stale defaults of earlier versions dropped; upscaler=standin counts as on). Only keys of the settings schema // (kSettings) are taken: developer and test keys (runtime_options items such as timing_log, capture_dir, model_dir, diff --git a/clean/installer/src/wg_core/record.cpp b/clean/installer/src/wg_core/record.cpp index 8ab39512..4f78f1cc 100644 --- a/clean/installer/src/wg_core/record.cpp +++ b/clean/installer/src/wg_core/record.cpp @@ -403,10 +403,13 @@ static wstring LowerRel(wstring r) { // What the state folder holds that WrongGPU wrote, with the bytes it must have: its path below the folder (lower case) -> SHA-256 // ("": by name only). The backups the record lists (the hash is the entry's `orig`), the previous version's files (the hash // previous.txt states) and owned-files.json (the bytes WrongGPU makes of this record) are deleted only while their bytes are -// those; the record, previous.txt, uninstall.exe, setup.log and profile.ini carry no recorded hash and go by their fixed names. +// those; the record, previous.txt, uninstall.exe, setup.log, profile.ini and model-choice.ini carry no recorded hash and go by +// their fixed names. static std::function StateOwned(const wstring& dir, const Record* m) { auto names = std::make_shared>(); - for (const wchar_t* n : {L"install.record", L"uninstall.exe", L"setup.log", L"profile.ini"}) (*names)[n] = L""; + // (model-choice.ini: the game's model choice record, which the launcher, the front end and its menu plugin write, so it + // carries no recorded hash either; clean/fsr/src/model_choice_record.h) + for (const wchar_t* n : {L"install.record", L"uninstall.exe", L"setup.log", L"profile.ini", L"model-choice.ini"}) (*names)[n] = L""; if (m) { const string json = OwnedFilesJson(*m); (*names)[L"owned-files.json"] = Sha256Bytes(json.data(), json.size()); @@ -908,7 +911,7 @@ std::vector DoRestore(Context& ctx, const wstring& dir, Ui& ui, bool fa } static bool SettingsName(const wstring& name, bool folder) { - return folder ? IEq(name, L"previous") || IEq(name, L"rr-config") : IEq(name, L"profile.ini"); + return folder ? IEq(name, L"previous") || IEq(name, L"rr-config") : IEq(name, L"profile.ini") || IEq(name, L"model-choice.ini"); } bool StateHasSettings(const wstring& dir) { const wstring state = StateDir(dir); diff --git a/clean/installer/tests/model_choice_k_tests.cpp b/clean/installer/tests/model_choice_k_tests.cpp index b9a284f8..53445ff1 100644 --- a/clean/installer/tests/model_choice_k_tests.cpp +++ b/clean/installer/tests/model_choice_k_tests.cpp @@ -23,10 +23,10 @@ Profile With(const char* model) { if (!SetSetting(p, "model", model, &why)) throw std::runtime_error("test setup: model"); return p; } -string Wini(const Profile& p, const string& in, uint64_t now = 0, bool chosen = false) { +string Wini(const Profile& p, const string& in) { string out; wstring why; - if (!RenderWronggpuIni(p, in, out, &why, now, chosen)) throw std::runtime_error("test setup: render"); + if (!RenderWronggpuIni(p, in, out, &why)) throw std::runtime_error("test setup: render"); return out; } string Oini(const Profile& p, const string& in, std::vector* notes = nullptr) { @@ -71,29 +71,13 @@ int main() { toK.find("upscaler = network") != string::npos && toK.find("# WrongGPU settings") != string::npos, "Model K: the model item is model=K; the other lines stay"); require(Wini(With("k"), toK) == toK, "Model K again: unchanged (the line is rewritten only when its items change)"); - // #213 review P1: Model K applied again by the player (set model=K): model_chosen = the new time - const string kAt1000 = Wini(With("k"), fresh, 1000); - const string kAt3000 = Wini(With("k"), kAt1000, 3000, true); - require(kAt1000.find("model_chosen=1000\r\n") != string::npos && kAt3000.find("model_chosen=3000\r\n") != string::npos && - kAt3000.find("model_chosen=1000") == string::npos && kAt3000.find("runtime_options=model=K\r\n") != string::npos, - "Model K applied again: stamped again (the newest choice), the model item unchanged"); - require(Wini(With("k"), kAt1000, 3000) == kAt1000, "Model K kept by an apply that is not a model choice: not stamped"); const string mixed = "[fsr]\r\nruntime_options = model=M;timing_log=1;model=L\r\n"; require(Wini(With("k"), mixed).find("runtime_options=timing_log=1;model=K\r\n") != string::npos, "Model K: every model item out (an L item too), model=K last (the last one wins); timing_log kept"); const string backM = Wini(DefaultProfile(), "[fsr]\r\nruntime_options = timing_log=1;model=K\r\n"); require(backM.find("runtime_options=timing_log=1;model=M\r\n") != string::npos, "back to Model M: Model K's item becomes model=M"); - // (model_chosen: the time of the launcher's model choice, written on every model change, profile.h) - auto noTime = [](string s) { - const size_t a = s.find("model_chosen="); - if (a != string::npos) s.erase(a, s.find("\r\n", a) + 2 - a); - return s; - }; - require(toK.find("model_chosen=") != string::npos, "Model K chosen: model_chosen written"); - const string kThenM = Wini(DefaultProfile(), toK); - require(noTime(kThenM) == fresh.substr(0, fresh.find("runtime_options")) + "runtime_options=model=M\r\n" && kThenM.find("model_chosen=") != string::npos, - "K then M: only the runtime_options line is rewritten (the installer's comment on it is gone as it is for L), " - "and model_chosen is the time of that change"); + require(Wini(DefaultProfile(), toK) == fresh.substr(0, fresh.find("runtime_options")) + "runtime_options=model=M\r\n", + "K then M: only the runtime_options line is rewritten (the installer's comment on it is gone as it is for L)"); const string withLItem = "[fsr]\r\nruntime_options = model=L\r\n"; if (withL) { require(Wini(DefaultProfile(), withLItem).find("model=M") != string::npos, "Model M control: Model L's item still goes back to model=M"); @@ -106,6 +90,11 @@ int main() { require(EffectiveSettings(toK, "")["model"] == "k" && EffectiveSettings(fresh, "")["model"] == "m", "the file's model: K from its last model item, M otherwise"); require(EffectiveSettings("[fsr]\r\nruntime_options = model=K;model=M\r\n", "")["model"] == "m", "the file's model: the last model item counts"); + // ---- the model choice record's inputs (launcher.cpp ApplyProfile) + require(ModelOfWronggpuIni(toK) == 'K', "ModelOfWronggpuIni: model=K"); + require(ModelEntryOfOptiIni("[WrongGPU]\r\nUpscalerIndex=" + K + "\r\n") == 'K' && + ModelEntryOfOptiIni("[FSR]\r\nUpscalerIndex=" + L + "\r\n") == (withL ? 'L' : '-'), + "ModelEntryOfOptiIni: K's entry (1); L's entry (2) only with the L choice"); require(EffectiveSettings(withLItem, "")["model"] == (withL ? "l" : "m"), "the file's model: L only with the Model L choice"); // the profile a game's files imply (no profile.ini): K when the files say K (an install that started on Preset K) require(ImportProfile(toK, "").get("model") == "k" && ImportProfile(fresh, "").get("model") == "m", "the imported profile: model=k from model=K"); diff --git a/clean/installer/tests/model_choice_tests.cpp b/clean/installer/tests/model_choice_tests.cpp index 332d0d2e..ca1be3ca 100644 --- a/clean/installer/tests/model_choice_tests.cpp +++ b/clean/installer/tests/model_choice_tests.cpp @@ -22,10 +22,10 @@ Profile With(const char* model) { if (!SetSetting(p, "model", model, &why)) throw std::runtime_error("test setup: model"); return p; } -string Wini(const Profile& p, const string& in, uint64_t now = 0, bool chosen = false) { +string Wini(const Profile& p, const string& in) { string out; wstring why; - if (!RenderWronggpuIni(p, in, out, &why, now, chosen)) throw std::runtime_error("test setup: render"); + if (!RenderWronggpuIni(p, in, out, &why)) throw std::runtime_error("test setup: render"); return out; } string Oini(const Profile& p, const string& in, std::vector* notes = nullptr) { @@ -70,39 +70,14 @@ int main() { require(EffectiveSettings(toL, "")["model"] == "l" && EffectiveSettings(fresh, "")["model"] == "m" && EffectiveSettings(withK, "")["model"] == "m", "the file's model: L from its last model item, M otherwise"); require(EffectiveSettings("[fsr]\r\nruntime_options = model=L;model=M\r\n", "")["model"] == "m", "the file's model: the last model item counts"); - - // ---- wronggpu.ini model_chosen: the time of the launcher's model choice (0.6.5; the front end weighs it against - // the OptiScaler menu plugin's saved choice, clean/fsr/src/model_precedence.h) -------------------------------------- - require(Wini(DefaultProfile(), fresh, 1000) == fresh, "Model M on the installer's file: no model_chosen (nothing changed, byte for byte)"); - const string toLt = Wini(With("l"), fresh, 1000); - require(toLt.find("model_chosen=1000\r\n") != string::npos && toLt.find("runtime_options=model=L") != string::npos, - "Model L chosen: model_chosen = the time of the change, next to runtime_options"); - require(Wini(With("l"), toLt, 2000) == toLt, "Model L again: model_chosen stays (the model did not change)"); - const string otherSetting = Wini([] { Profile q = With("l"); wstring w; SetSetting(q, "sparkle_guard", "on", &w); return q; }(), toLt, 3000); - require(otherSetting.find("model_chosen=1000\r\n") != string::npos && otherSetting.find("model_chosen=3000") == string::npos, - "another setting changed: model_chosen stays (only a model change is a model choice)"); - const string backMt = Wini(DefaultProfile(), toLt, 4000); - require(backMt.find("model=M") != string::npos && backMt.find("model_chosen=4000\r\n") != string::npos && backMt.find("model_chosen=1000") == string::npos, - "back to Model M: model_chosen = the time of that change (replaced, one line)"); - require(Wini(With("l"), "[fsr]\r\nruntime_options = model=K\r\n", 5000).find("model_chosen=5000") != string::npos, - "from another model's item (Model K) to Model L: stamped"); - require(Wini(DefaultProfile(), withK, 6000) == withK, "Model K's item left as it is by Model M: no model_chosen"); - require(Wini(With("l"), "[fsr]\r\nupscaler = network\r\n", 7000).find("model_chosen=7000") != string::npos, - "a file without runtime_options gets model=L and model_chosen"); - require(Wini(With("l"), fresh).find("model_chosen=") != string::npos, "now = 0: the current time is written"); - // #213 review P1: the player explicitly applies the SAME model again (set model=...): stamped again, newest - const string againL = Wini(With("l"), toLt, 3000, true); - require(againL.find("model_chosen=3000\r\n") != string::npos && againL.find("model_chosen=1000") == string::npos && - againL.find("runtime_options=model=L\r\n") != string::npos, - "Model L applied again by the player: model_chosen = the new time (the model item unchanged)"); - const string chosenM = Wini(DefaultProfile(), fresh, 3000, true); - require(chosenM.find("model_chosen=3000\r\n") != string::npos && chosenM.find("runtime_options = model=M ; the model\r\n") != string::npos, - "Model M explicitly applied on the installer's file: its model=M line kept as it is, stamped (an explicit M, not the default)"); - const string againM = Wini(DefaultProfile(), chosenM, 4000, true); - require(againM.find("model_chosen=4000\r\n") != string::npos && againM.find("model_chosen=3000") == string::npos, - "Model M applied again: stamped again"); - require(Wini(DefaultProfile(), chosenM, 5000) == chosenM, "another apply that is not a model choice: model_chosen stays"); - require(NowFileTime() > 133000000000000000ull, "NowFileTime: FILETIME units (100 ns since 1601), after 2022"); + // ---- the model choice record's inputs (launcher.cpp ApplyProfile: the model the files run, the entry OptiScaler names) + require(ModelOfWronggpuIni(toL) == 'L' && ModelOfWronggpuIni(fresh) == 'M' && ModelOfWronggpuIni("[fsr]\r\nupscaler = network\r\n") == 0 && + ModelOfWronggpuIni("[fsr]\r\nruntime_options = model=L;model=m\r\n") == 'M' && ModelOfWronggpuIni("[fsr]\r\nruntime_options = model=Q\r\n") == 0, + "ModelOfWronggpuIni: the last model item, M / K / L, else none"); + require(ModelEntryOfOptiIni("[WrongGPU]\r\nUpscalerIndex=" + string(kModelLEntryIndex) + "\r\n") == 'L' && + ModelEntryOfOptiIni("[FSR]\r\nUpscalerIndex=0\r\n") == 'M' && ModelEntryOfOptiIni("[FSR]\r\nUpscalerIndex=auto\r\n") == '-' && + ModelEntryOfOptiIni("[Menu]\r\nShowFps=auto\r\n") == '-', + "ModelEntryOfOptiIni: the WrongGPU entry UpscalerIndex names (L's index, 0 = M), '-' otherwise"); // ---- OptiScaler.ini: the entry OptiScaler starts with ----------------------------------------------------------- const string L = kModelLEntryIndex; diff --git a/clean/installer/tests/run_model_k_tests.py b/clean/installer/tests/run_model_k_tests.py index 3a9dd447..2446de0c 100644 --- a/clean/installer/tests/run_model_k_tests.py +++ b/clean/installer/tests/run_model_k_tests.py @@ -25,7 +25,7 @@ sys.path.insert(0, HERE) import run_model_l_tests as ml # noqa: E402 (T, the Model L case and the install helpers; it sets WRONGGPU_TESTING) from run_installer_tests import read, write # noqa: E402 -from run_model_l_tests import m_case, l_case, recorded_hash, suite, suite_options_model, upscaler_index, no_stamp, stamp # noqa: E402 +from run_model_l_tests import m_case, l_case, recorded_hash, suite, suite_options_model, upscaler_index, choice_record # noqa: E402 def k_case(): @@ -75,14 +75,18 @@ def test_choice(t): (recorded_hash(b, "wronggpu.ini"), recorded_hash(b, "OptiScaler.ini"))) t.check("...profile.ini says model=k", b"model=k\r\n" in profile_text(b)) k_w, k_o = read(wini), read(oini) + r1 = choice_record(b) + t.check("...the model choice record: model=K, source=launcher, ffx=K (the entry it set)", + r1.get("model") == "K" and r1.get("source") == "launcher" and r1.get("ffx") == "K", r1) rc = t.run("set", exe, "model=K") - t.check("set model=K again: only model_chosen changes (stamped again: the newest choice)", - rc == 0 and no_stamp(read(wini)) == no_stamp(k_w) and read(oini) == k_o and stamp(read(wini)) > stamp(k_w) > 0, rc) + r2 = choice_record(b) + t.check("set model=K again: wronggpu.ini and OptiScaler.ini unchanged; the record's seq grows (the newest choice)", + rc == 0 and read(wini) == k_w and read(oini) == k_o and int(r2.get("seq", "0")) == int(r1.get("seq", "0")) + 1, (rc, r1, r2)) rc = t.run("get", exe, "model") t.check("get model: k", rc == 0 and t.j.get("settings", {}).get("model", {}).get("profile") == "k", t.j.get("settings")) rc = t.run("set", exe, "model=M") - t.check("set model=M: wronggpu.ini (but its model_chosen line) and OptiScaler.ini back byte for byte as the install wrote them", - rc == 0 and no_stamp(read(wini)) == no_stamp(m_w) and read(oini) == m_o and stamp(read(wini)) > 0, (rc, read(wini)[-200:], read(oini)[-200:])) + t.check("set model=M: wronggpu.ini and OptiScaler.ini back byte for byte as the install wrote them", + rc == 0 and read(wini) == m_w and read(oini) == m_o, (rc, read(wini)[-200:], read(oini)[-200:])) t.check("...profile.ini has no model line again", b"model=" not in profile_text(b)) # the Model L control: unchanged by the K choice (its entry follows Model K's, so it is 2) lsrc = os.path.join(t.work, "l-source", "nvngx_dlss.dll") @@ -98,8 +102,7 @@ def test_choice(t): upscaler_index(read(oini).decode("utf-8", "replace")) == "1", (rc, t.j.get("message"))) rc = t.run("set", exe, "model=L") rc2 = t.run("set", exe, "model=M") - t.check("K to L to M: back byte for byte as the install wrote them (but model_chosen)", - rc == 0 and rc2 == 0 and no_stamp(read(wini)) == no_stamp(m_w) and read(oini) == m_o, (rc, rc2)) + t.check("K to L to M: back byte for byte as the install wrote them", rc == 0 and rc2 == 0 and read(wini) == m_w and read(oini) == m_o, (rc, rc2)) # a game saved on K whose data goes away: a repair keeps the player's choice, the files say Model M with a warning rc = t.run("set", exe, "model=K") os.remove(os.path.join(t.lad, "WrongGPU", "model", "K", "model.wgcm")) diff --git a/clean/installer/tests/run_model_l_tests.py b/clean/installer/tests/run_model_l_tests.py index 3a35555f..5d295f20 100644 --- a/clean/installer/tests/run_model_l_tests.py +++ b/clean/installer/tests/run_model_l_tests.py @@ -224,27 +224,23 @@ def recorded_hash(b, name): return None -def no_stamp(data): - """wronggpu.ini without its model_chosen line: the launcher stamps every explicit model choice (also the same model - again, and Model M), so `set model=...` changes that line and nothing else of a file that already says the model.""" - kept = b"".join(l for l in data.splitlines(True) if not l.replace(b" ", b"").lower().startswith(b"model_chosen=")) - return kept.rstrip(b"\r\n") # (appending the line may give a file that had no final line end one) - - -def stamp(data): - """wronggpu.ini's model_chosen value (FILETIME units), 0 without one.""" - for l in data.splitlines(): - k, _, v = l.replace(b" ", b"").partition(b"=") - if k.lower() == b"model_chosen" and v.isdigit(): - return int(v) - return 0 +def choice_record(b): + """The game's model choice record (wronggpu-setup\\model-choice.ini; clean/fsr/src/model_choice_record.h) as a dict, {} without one.""" + p = os.path.join(b, "wronggpu-setup", "model-choice.ini") + if not os.path.exists(p): + return {} + r = {} + for line in read(p).decode("utf-8", "replace").splitlines(): + if line and not line.startswith(";") and "=" in line: + k, v = line.split("=", 1) + r[k] = v + return r def test_choice(t): """The launcher's Model L choice (a build with WRONGGPU_MODEL_L on and the test map): set model=L/M on an installed game. L only with Model L's data on this PC; it writes wronggpu.ini's model item and OptiScaler's UpscalerIndex, the - record's hashes follow (the file-ownership rule); M puts both files back as the install wrote them (wronggpu.ini then - also has model_chosen, the time of the player's explicit model choice); uninstall restores the game.""" + record's hashes follow (the file-ownership rule); M puts both files back byte for byte; uninstall restores the game.""" print("\n[3] the model choice: set model=L / model=M (a build with the choice on)") import run_launcher_tests as rl # (its game and OptiScaler fixtures: names and synthetic bytes only) t.model = m_case() # rl.game() writes t.model.file as the game's DLSS file (this hides T.model, the path helper) @@ -277,16 +273,20 @@ def test_choice(t): recorded_hash(b, "wronggpu.ini") == hashlib.sha256(read(wini)).hexdigest() and recorded_hash(b, "OptiScaler.ini") == hashlib.sha256(read(oini)).hexdigest(), (recorded_hash(b, "wronggpu.ini"), recorded_hash(b, "OptiScaler.ini"))) t.check("...profile.ini says model=l", b"model=l\r\n" in read(os.path.join(b, "wronggpu-setup", "profile.ini"))) - l_stamp = stamp(read(wini)) - t.check("...wronggpu.ini has model_chosen (the time of the choice, FILETIME units)", l_stamp > 133000000000000000, read(wini)) + r1 = choice_record(b) + t.check("...the model choice record: model=L, source=launcher, ffx=L (the entry it set), a seq", r1.get("model") == "L" and + r1.get("source") == "launcher" and r1.get("ffx") == "L" and r1.get("seq", "").isdigit(), r1) rc = t.run("set", exe, "model=L") - t.check("set model=L again: model_chosen stamped again (the newest choice), nothing else changes", - rc == 0 and stamp(read(wini)) > l_stamp and suite_options_model(read(wini).decode("utf-8", "replace")) == "L", (rc, read(wini))) + r2 = choice_record(b) + t.check("set model=L again: the record's seq grows (the newest choice); wronggpu.ini and OptiScaler.ini unchanged", + rc == 0 and r2.get("model") == "L" and int(r2.get("seq", "0")) == int(r1.get("seq", "0")) + 1, (r1, r2)) rc = t.run("set", exe, "model=M") - t.check("set model=M: wronggpu.ini (but its model_chosen line) and OptiScaler.ini back byte for byte as the install wrote them", - rc == 0 and no_stamp(read(wini)) == no_stamp(m_w) and read(oini) == m_o and stamp(read(wini)) > l_stamp, - (rc, read(wini)[-200:], read(oini)[-200:])) + t.check("set model=M: wronggpu.ini and OptiScaler.ini back byte for byte as the install wrote them", + rc == 0 and read(wini) == m_w and read(oini) == m_o, (rc, read(wini)[-200:], read(oini)[-200:])) t.check("...profile.ini has no model line again", b"model=" not in read(os.path.join(b, "wronggpu-setup", "profile.ini"))) + r3 = choice_record(b) + t.check("...the record: model=M, source=launcher, ffx=M, the next seq", r3.get("model") == "M" and r3.get("ffx") == "M" and + int(r3.get("seq", "0")) == int(r2.get("seq", "0")) + 1, r3) # a game saved on L whose data goes away: a repair keeps the player's choice, the files say Model M with a warning rc = t.run("set", exe, "model=L") os.remove(os.path.join(t.lad, "WrongGPU", "model", "L", "model.wgcm")) # (t.model is the case here, not the path helper) From 3d9c0455ef84760c1071ade28bf17f4e0bb5720d Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:44:29 -0500 Subject: [PATCH 05/15] Model choice: choices are events, one cross-process lock per game Review of #213 (third round): concurrent writers could lose a choice or move seq back, an upgrade could take its model from OptiScaler's stored index, the launcher's index and record were separate steps, re-selecting the same entry in OptiScaler's list was invisible, the index was not always set, and the preferred rename ignored its flush result. Reworked as the architect decided: - The record has three keys: model, seq, source. The ffx key is gone; a record with it reads as corrupt. - A choice made in OptiScaler's list is an event: the WrongGPU edition of OptiScaler calls WrongGpuHostSelectedV1(versionId) in the front-end DLL (include/wronggpu_host_event.h) before it recreates the upscaler. The index OptiScaler passes at a create is never taken for a choice, on the hooked route and on the custom slot; the slot's ini poll leaves model entries alone while there is a record. - Every read-modify-write runs under one named mutex per game (Local\WrongGPU-choice-), taken by the launcher, the front end and the menu plugin. An abandoned lock is taken over. - Writes: a temporary file, written and flushed (both checked), then MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH), checked; up to 3 tries. - The launcher writes the record first, then sets OptiScaler's UpscalerIndex to the model's entry whatever it was (AMD's version, another value, or no key: created), both under the lock. The index is display only, so a crash between the two is harmless. - Upgrade: a game without a record gets one from wronggpu.ini's model item (else Model M), seq 1, source=launcher. The old stamp files are ignored. - A choice that cannot be written now runs for the session and is tried again (dropped when a newer choice was recorded meanwhile): the front end's host events at each create, the plugin's clicks at each create and once a second while its menu is drawn; the plugin's entry says "not saved yet, retrying" and the front end asks it (WrongGpuAsiPendingChoiceV1). At the end of the sequence numbers a choice is refused and logged as an error. Tests on real files and real processes (TMP, APPDATA, LOCALAPPDATA and ProgramData redirected): four writer processes and a reader racing the record (no lost update, seq never back), a lock holder that dies, the upgrade migration, each source winning in turn, re-selecting the same entry after a plugin choice, corrupt and overflowing records, the end of seq, a failed write with its retry and a superseded retry, the custom slot ignoring its stored index, the plugin's not-saved label, and in the launcher end-to-end suites: the index set from AMD's value and from a missing key, and an apply stopped between the record and OptiScaler.ini. Negative controls: no lock, the stored index taken as the choice, a retry ignoring newer choices, no end-of-seq check, migration from the index, the launcher not setting the index. Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/fsr/asi/README.md | 29 +- clean/fsr/asi/asi_abi.h | 6 + clean/fsr/asi/asi_thunk.h | 15 +- clean/fsr/asi/exports_asi.def | 1 + clean/fsr/asi/wronggpu_asi.cpp | 77 +++- clean/fsr/include/wronggpu_host_event.h | 29 ++ clean/fsr/src/asi_bridge.cpp | 7 + clean/fsr/src/asi_bridge.h | 3 + clean/fsr/src/dllmain.cpp | 15 + clean/fsr/src/exports.def | 1 + clean/fsr/src/frontend.cpp | 175 ++++++-- clean/fsr/src/frontend.h | 26 +- clean/fsr/src/model_choice_record.h | 277 ++++++++---- clean/fsr/src/settings_bridge.cpp | 9 + clean/fsr/src/settings_bridge.h | 3 + clean/fsr/tests/test_asi_status.cpp | 3 + clean/fsr/tests/test_asi_thunk.cpp | 30 ++ clean/fsr/tests/test_frontend.cpp | 242 +++++++---- clean/fsr/tests/test_model_choice_record.cpp | 396 +++++++++++++----- clean/installer/src/wg_core/launcher.cpp | 73 ++-- clean/installer/src/wg_core/launcher.h | 7 +- clean/installer/src/wg_core/profile.cpp | 24 +- clean/installer/src/wg_core/profile.h | 9 +- .../installer/tests/model_choice_k_tests.cpp | 11 +- clean/installer/tests/model_choice_tests.cpp | 24 +- clean/installer/tests/run_model_k_tests.py | 4 +- clean/installer/tests/run_model_l_tests.py | 57 ++- 27 files changed, 1148 insertions(+), 405 deletions(-) create mode 100644 clean/fsr/include/wronggpu_host_event.h diff --git a/clean/fsr/asi/README.md b/clean/fsr/asi/README.md index b6ee3136..6923e6f6 100644 --- a/clean/fsr/asi/README.md +++ b/clean/fsr/asi/README.md @@ -23,18 +23,23 @@ The FFX box's list is the same with and without the plugin (WrongGPU first). Which model runs (0.6.5, `src/model_choice_record.h`, `TestAsiChoiceRecord`, `tests/test_model_choice_record.cpp`): the plugin's entry says WrongGPU or AMD; which WrongGPU model is the game's **model choice record**, -`wronggpu-setup\model-choice.ini` next to wronggpu.ini (the launcher's state folder). It holds one record: `model=`, -`seq=`, `source=` (launcher, ffx or plugin) and `ffx=` (the WrongGPU entry the writer knew OptiScaler's list to name). -Three places write it, each with the record's seq + 1, so the highest seq is the most recent choice and no clock is -involved: the launcher when it applies a model (it sets OptiScaler's entry with it and writes `ffx` = that entry), the -front end when OptiScaler's FFX box names a WrongGPU entry the record does not know (the player picked it there; also at -the first create when there is no record yet), and this plugin when the player clicks one of its model entries (it keeps -the record's `ffx`, so the unchanged FFX box is never taken for a new choice). Writes are atomic (a temporary file in -the same folder, flushed, renamed over the record); parsing is strict, and a corrupt record counts as no record. Without -a record the launcher's Model K / L item decides, else the plugin's saved entry, else Model M. The front end logs the -model and which choice decided, one line when the record and wronggpu.ini's model item disagree, and tells the plugin -which model runs (`WrongGpuAsiShowModelV1`), so the menu marks that entry. Model L's own entry ("WrongGPU Model L") is in -the menu of a build with `WG_MODEL_L`; a model the front end was built without runs as Model M, with a note in the log. +`wronggpu-setup\model-choice.ini` next to wronggpu.ini (the launcher's state folder). It holds `model=`, `seq=` and +`source=` (launcher, ffx or plugin). It is written only for a choice the player made, each time with the record's seq + 1, +so the highest seq is the most recent choice and no clock is involved: by the launcher when it applies a model (the record +first, then OptiScaler's `UpscalerIndex` set to that model's entry, for display); by the front end when the WrongGPU edition +of OptiScaler reports that the player selected one of WrongGPU's entries in its list (`WrongGpuHostSelectedV1`, +`include/wronggpu_host_event.h`); and by this plugin when the player clicks one of its model entries. The entry OptiScaler's +ini stores is never taken for a choice. Every read and write takes one lock per game shared by all processes (a named +mutex), so no choice is lost and seq never goes back. Writes go to a temporary file in the same folder, flushed, then +`MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH)`, every step checked; parsing is strict, and a corrupt record counts as no +choice until the next choice replaces it. A game without a record (an install from before 0.6.5) gets one from +wronggpu.ini's model item (else Model M). A click that cannot be written now runs for the session, its entry says "not +saved yet, retrying" in the menu, and it is tried again (`WrongGpuAsiPendingChoiceV1` tells the front end); at the end of +the sequence numbers it is refused and logged. Without a record (no launcher state folder) the launcher's Model K / L item +decides, else the plugin's saved entry, else Model M. The front end logs the model and which choice decided, one line when +the record and wronggpu.ini's model item disagree, and tells the plugin which model runs (`WrongGpuAsiShowModelV1`), so +the menu marks that entry. Model L's own entry ("WrongGPU Model L") is in the menu of a build with `WG_MODEL_L`; a model +the front end was built without runs as Model M, with a note in the log. ## How it works diff --git a/clean/fsr/asi/asi_abi.h b/clean/fsr/asi/asi_abi.h index 443b7cef..a4975bdd 100644 --- a/clean/fsr/asi/asi_abi.h +++ b/clean/fsr/asi/asi_abi.h @@ -88,3 +88,9 @@ typedef void (*PfnWrongGpuAsiSetChoiceRecordV1)(const wchar_t* path); // to marking the saved choice. Display only: nothing is saved. #define WRONGGPU_ASI_SHOW_MODEL "WrongGpuAsiShowModelV1" typedef void (*PfnWrongGpuAsiShowModelV1)(char model); + +// The model of a click on one of the plugin's model entries that the plugin could not write to the record yet (the +// record was busy or a write failed; the plugin tries again, and its menu says "not saved yet"), else 0. The front end +// runs that model for the session until the record has it. +#define WRONGGPU_ASI_PENDING_CHOICE "WrongGpuAsiPendingChoiceV1" +typedef char (*PfnWrongGpuAsiPendingChoiceV1)(void); diff --git a/clean/fsr/asi/asi_thunk.h b/clean/fsr/asi/asi_thunk.h index 4131865b..8d3d3cda 100644 --- a/clean/fsr/asi/asi_thunk.h +++ b/clean/fsr/asi/asi_thunk.h @@ -56,12 +56,25 @@ inline const char* LabelOf(char model) { // Shared plugin state. `hooked` is read by the front end through the exported query; `model` is the player's choice // within OptiScaler's FSR 3.X entry (0: AMD). `shown` is the model the front end reported as running (kShowSaved until // it reports one): the menu marks that one, so the model the choice record decided is what the player sees checked. +// `unsaved`: a model click the plugin could not write to the model choice record yet (0: none); its entry says so in +// the menu, "(not saved yet, retrying)", or with `refused` "(not saved: the choice record is full)". struct PluginState { std::atomic hooked{false}; std::atomic model{kDefaultModel}; std::atomic shown{kShowSaved}; + std::atomic unsaved{0}; + std::atomic refused{false}; }; +constexpr const char* kUnsavedSuffix = " (not saved yet, retrying)"; +constexpr const char* kRefusedSuffix = " (not saved: the choice record is full, see the plugin's log)"; + +// The label drawn for entry `e`: its name, with the not-saved note when its click is not in the record yet. +inline std::string EntryLabel(const Entry& e, const PluginState& st) { + if (st.unsaved.load() != e.model) return e.label; + return std::string(e.label) + (st.refused.load() ? kRefusedSuffix : kUnsavedSuffix); +} + inline char ShownModel(const PluginState& st) { const char s = st.shown.load(); return s == kShowSaved ? st.model.load() : s; @@ -84,7 +97,7 @@ bool SelectableThunkLogic(SelFn&& sel, const char* label, bool selected, int fla const char model = ShownModel(st); char clicked = 1; // 1: nothing clicked for (const Entry& e : kEntries) - if (sel(e.label, selected && model == e.model, flags, size) && clicked == 1) clicked = e.model; + if (sel(EntryLabel(e, st).c_str(), selected && model == e.model, flags, size) && clicked == 1) clicked = e.model; if (sel(label, selected && model == kModelAmd, flags, size) && clicked == 1) clicked = kModelAmd; if (clicked == 1) return false; st.model.store(clicked); diff --git a/clean/fsr/asi/exports_asi.def b/clean/fsr/asi/exports_asi.def index fbd2a940..04509e2f 100644 --- a/clean/fsr/asi/exports_asi.def +++ b/clean/fsr/asi/exports_asi.def @@ -6,3 +6,4 @@ EXPORTS WrongGpuAsiQueryStatusV1 WrongGpuAsiSetChoiceRecordV1 WrongGpuAsiShowModelV1 + WrongGpuAsiPendingChoiceV1 diff --git a/clean/fsr/asi/wronggpu_asi.cpp b/clean/fsr/asi/wronggpu_asi.cpp index 2e2bb89b..9d982877 100644 --- a/clean/fsr/asi/wronggpu_asi.cpp +++ b/clean/fsr/asi/wronggpu_asi.cpp @@ -3,7 +3,7 @@ // ("WrongGPU"; with Model K and/or L: "WrongGPU Model M", "WrongGPU Model K", "WrongGPU Model L") in OptiScaler's MAIN // DX12 upscaler dropdown, leaving OptiScaler's "FSR 3.X(/4)" entry to mean AMD's upscaler again. WrongGPU is the default // entry; WrongGPU or AMD is remembered in wronggpu-asi.ini next to the plugin, and a click on a model entry is written to -// the game's model choice record (src/model_choice_record.h), which decides the model. The front end reports back the +// the game's model choice record (src/model_choice_record.h, under its cross-process lock), which decides the model. The front end reports back the // model it runs. // // How: OptiScaler calls our exported InitializeASI() after loading us (see its LoadAsiPlugins). The module that @@ -109,29 +109,72 @@ std::wstring RecordPath() { return g_recordPath.empty() ? wgchoice::RecordPathIn(wgasi::PluginDataDir()).wstring() : g_recordPath; } -// A click on one of the plugin's model entries: the record gets this model with the next seq (source=plugin); the -// entry OptiScaler's list names (ffx) stays what the record knew. +// A click on one of the plugin's model entries: the record gets this model with the next seq (source=plugin), under the +// record's cross-process lock (model_choice_record.h). A click that cannot be written now stays pending: the menu says +// "not saved yet", the front end runs it this session (WrongGpuAsiPendingChoiceV1), and it is tried again (at each create +// and at most once a second while the menu is drawn) until it is written or a newer choice replaces it. At the end of the +// sequence numbers the click is refused, logged and said in the menu. +std::mutex g_pendingMutex; // g_pending, g_lastTry +wgchoice::Pending g_pending; +ULONGLONG g_lastTry = 0; + void RecordModelChoice(char model) { const std::wstring path = RecordPath(); - wgchoice::Record cur, next; + wgchoice::Record after; + wgchoice::Pending pending; std::string why; - const wgchoice::ReadResult rr = wgchoice::ReadRecordFile(path, &cur, &why); - if (rr == wgchoice::ReadResult::Unreadable) { - AsiLog::Get().Write("model choice record " + wgasi::Utf8(path) + " cannot be read (" + why + "); the click is not recorded"); + std::lock_guard lock(g_pendingMutex); + const wgchoice::Outcome o = wgchoice::RecordChoice(path, model, wgchoice::Source::Plugin, &after, &why, &pending, 1000); + g_lastTry = GetTickCount64(); + if (o == wgchoice::Outcome::Written) { + g_pending = wgchoice::Pending{}; + g_state.unsaved.store(0); + g_state.refused.store(false); + AsiLog::Get().Writef("model choice record: Model %c (seq %llu, source=plugin)%s", model, static_cast(after.seq), + why.empty() ? "" : ("; " + why).c_str()); return; } - if (rr == wgchoice::ReadResult::Corrupt) AsiLog::Get().Write("model choice record " + wgasi::Utf8(path) + " is corrupt (" + why + "); replaced"); - if (!wgchoice::NextRecord(rr == wgchoice::ReadResult::Ok ? &cur : nullptr, model, wgchoice::Source::Plugin, wgchoice::kUnknown, &next)) { - AsiLog::Get().Write("model choice record: seq cannot grow; the click is not recorded"); + if (o == wgchoice::Outcome::SeqExhausted) { + g_pending = wgchoice::Pending{}; + g_state.refused.store(true); + g_state.unsaved.store(model); + AsiLog::Get().Write(std::string("ERROR: model choice record ") + wgasi::Utf8(path) + ": " + wgchoice::OutcomeWords(o) + + ". Delete it or apply the model in the launcher."); return; } - if (wgchoice::WriteRecordFile(path, next, &why)) - AsiLog::Get().Writef("model choice record: Model %c (seq %llu, source=plugin)", model, static_cast(next.seq)); - else - AsiLog::Get().Write("model choice record " + wgasi::Utf8(path) + " could not be written (" + why + ")"); + g_pending = pending; + g_state.refused.store(false); + g_state.unsaved.store(model); + AsiLog::Get().Write(std::string("ERROR: model choice record ") + wgasi::Utf8(path) + ": Model " + model + " not written now (" + + wgchoice::OutcomeWords(o) + (why.empty() ? "" : ": " + why) + "); it runs this session and is tried again"); +} + +// Tries a pending click again. throttle: at most once a second (the menu thread); never waits on the lock long there. +void RetryPendingChoice(bool throttle) { + if (!g_state.unsaved.load() || g_state.refused.load()) return; + std::unique_lock lock(g_pendingMutex, std::try_to_lock); + if (!lock.owns_lock() || !g_pending.active()) return; + const ULONGLONG now = GetTickCount64(); + if (throttle && now - g_lastTry < 1000) return; + g_lastTry = now; + const char model = g_pending.model; + wgchoice::Record after; + std::string why; + const wgchoice::Outcome o = wgchoice::RetryPending(RecordPath(), &g_pending, &after, &why, throttle ? 50 : 1000); + if (o == wgchoice::Outcome::Written) { + g_state.unsaved.store(0); + AsiLog::Get().Writef("model choice record: Model %c written now (seq %llu, source=plugin)", model, static_cast(after.seq)); + } else if (o == wgchoice::Outcome::Superseded) { + g_state.unsaved.store(0); + AsiLog::Get().Writef("model choice record: Model %c (not written earlier) dropped: a newer choice was recorded meanwhile", model); + } else if (o == wgchoice::Outcome::SeqExhausted) { + g_state.refused.store(true); + AsiLog::Get().Write(std::string("ERROR: model choice record: Model ") + model + " refused: " + wgchoice::OutcomeWords(o)); + } } extern "C" bool WgSelectableThunk(const char* label, bool selected, int flags, const void* size) { + if (wgasi::IsFsr3xLabel(label)) RetryPendingChoice(true); bool ours = false; const bool clicked = wgasi::SelectableThunkLogic( [](const char* l, bool s, int f, const void* z) { return g_realSelectable(l, s, f, z); }, @@ -333,6 +376,7 @@ extern "C" __declspec(dllexport) __declspec(noinline) void InitializeASI() { // The earlier query (ABI 1): an older front end knows 0, 'M' and 'K' only, so Model L reads as Model M there. extern "C" __declspec(dllexport) int WrongGpuAsiQuery(int* hooked, char* model) { + RetryPendingChoice(false); // the front end asks at each create: a click not written yet is tried again first if (hooked) *hooked = g_state.hooked.load() ? 1 : 0; if (model) { const char m = g_state.model.load(); @@ -352,6 +396,11 @@ extern "C" __declspec(dllexport) void WrongGpuAsiShowModelV1(char model) { if (model == wgasi::kShowSaved || model == wgasi::kModelAmd || wgasi::LabelOf(model)) g_state.shown.store(model); } +// A model click not written to the record yet (0: none). The front end runs it this session. +extern "C" __declspec(dllexport) char WrongGpuAsiPendingChoiceV1() { + return g_state.refused.load() ? 0 : g_state.unsaved.load(); +} + extern "C" __declspec(dllexport) int WrongGpuAsiQueryStatusV1(WrongGpuAsiStatusV1* status, uint32_t caller_size) { return g_diagnostics.Query(status, caller_size, g_state.hooked.load(), g_state.model.load()); } diff --git a/clean/fsr/include/wronggpu_host_event.h b/clean/fsr/include/wronggpu_host_event.h new file mode 100644 index 00000000..2aa9dfc5 --- /dev/null +++ b/clean/fsr/include/wronggpu_host_event.h @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: MIT */ +#pragma once +/* The event a host (the WrongGPU edition of OptiScaler) sends WrongGPU's front end (amd_fidelityfx_dx12.dll in the + * custom WrongGPU slot or next to the game) when the PLAYER selects one of the listed upscaler versions in its menu during + * the session. The host resolves this one export by name in the front-end DLL it loaded (GetProcAddress) and calls it + * with the selected entry's version id (from the list the front end returned to FFX_API_QUERY_DESC_TYPE_GET_VERSIONS), + * BEFORE it recreates the upscaler, so the new context runs the selected model. Only a player's selection is an event: a + * host never sends one for an index it read from its ini or applied at start. + * + * A selection of one of WrongGPU's model entries is written to the game's model choice record + * (clean/fsr/src/model_choice_record.h, source=ffx) and decides the model from then on, until a newer choice (the + * launcher's, the WrongGPU menu plugin's, or another selection). An AMD version or a Ray Reconstruction mode entry is no + * model choice. + * + * Signature: int32_t WrongGpuHostSelectedV1(uint64_t versionId). Callable from any thread; it takes the record's + * cross-process lock for a few milliseconds at most (3 s when another process holds it). */ +#include + +#define WRONGGPU_HOST_SELECTED_EXPORT "WrongGpuHostSelectedV1" + +#define WG_HOST_SELECTED_RECORDED 1 /* a WrongGPU model: written to the record */ +#define WG_HOST_SELECTED_SESSION_ONLY 2 /* a WrongGPU model, no record for this game (no launcher state folder): this session */ +#define WG_HOST_SELECTED_NOT_A_MODEL 0 /* an AMD version or an RR mode entry: nothing recorded */ +#define WG_HOST_SELECTED_PENDING -1 /* not written yet (the record is busy or a write failed): used this session and + written at the next create; the front end's log says why. Hosts show it. */ +#define WG_HOST_SELECTED_REFUSED -2 /* the record's sequence number is at its end: refused (logged). Hosts show it. */ +#define WG_HOST_SELECTED_NOT_READY -3 /* the front end is not hosted or not initialised */ + +typedef int32_t (*PfnWrongGpuHostSelectedV1)(uint64_t versionId); diff --git a/clean/fsr/src/asi_bridge.cpp b/clean/fsr/src/asi_bridge.cpp index 84c86eb2..eb022f6e 100644 --- a/clean/fsr/src/asi_bridge.cpp +++ b/clean/fsr/src/asi_bridge.cpp @@ -38,4 +38,11 @@ void SetAsiChoiceRecord(const std::wstring& path) { set(path.c_str()); } +char QueryAsiPending() { + HMODULE m = GetModuleHandleW(WRONGGPU_ASI_MODULE); + if (!m) return 0; + auto pending = reinterpret_cast(reinterpret_cast(GetProcAddress(m, WRONGGPU_ASI_PENDING_CHOICE))); + return pending ? pending() : 0; +} + } // namespace wgwin diff --git a/clean/fsr/src/asi_bridge.h b/clean/fsr/src/asi_bridge.h index 739d3312..4ed58622 100644 --- a/clean/fsr/src/asi_bridge.h +++ b/clean/fsr/src/asi_bridge.h @@ -16,4 +16,7 @@ void ShowAsiModel(char model); // Tells the plugin where the game's model choice record is (src/model_choice_record.h). Nothing without the plugin. void SetAsiChoiceRecord(const std::wstring& path); +// The plugin's model click that it could not write to the record yet (it tries again), else 0 (also without the plugin). +char QueryAsiPending(); + } // namespace wgwin diff --git a/clean/fsr/src/dllmain.cpp b/clean/fsr/src/dllmain.cpp index db5c017b..4fbdb5ee 100644 --- a/clean/fsr/src/dllmain.cpp +++ b/clean/fsr/src/dllmain.cpp @@ -13,6 +13,7 @@ #include #include +#include "../include/wronggpu_host_event.h" #include "ffx_headers.h" #include "frontend.h" #include "version.h" @@ -239,6 +240,7 @@ FrontEnd& Get() { // mode as before. p.asiPlugin = [](char* model) { return QueryAsiPlugin(model); }; p.asiShowModel = [](char model) { ShowAsiModel(model); }; + p.asiPending = [] { return QueryAsiPending(); }; { const std::wstring& ini = Place().ini; const size_t slash = ini.find_last_of(L"\\/"); @@ -248,6 +250,7 @@ FrontEnd& Get() { if (std::filesystem::is_directory(record.parent_path(), ec)) { // a launcher install: its state folder p.choiceRecord = record; SetAsiChoiceRecord(record.wstring()); // the plugin writes its menu's model clicks there too + SetHostIniPollModels(false); // the host's stored index is no model choice (the record decides) } else { L().Write("model choice: no launcher state folder next to wronggpu.ini: no model choice record (the model item decides)"); } @@ -302,6 +305,18 @@ FFX_API_ENTRY ffxReturnCode_t ffxDispatch(ffxContext* context, const ffxDispatch return Guard("ffxDispatch", [&] { return Get().Dispatch(context, desc); }); } +// The WrongGPU edition of OptiScaler: the player selected the listed version `versionId` in its upscaler list +// (include/wronggpu_host_event.h). Not hosted or not initialised: WG_HOST_SELECTED_NOT_READY. +__declspec(dllexport) int32_t WrongGpuHostSelectedV1(uint64_t versionId) { + int32_t rc = WG_HOST_SELECTED_NOT_READY; + Guard("WrongGpuHostSelectedV1", [&] { + FrontEnd& fe = Get(); + if (fe.GetConfig().hosted) rc = fe.HostSelected(versionId); + return FFX_API_RETURN_OK; + }); + return rc; +} + } // extern "C" BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved) { diff --git a/clean/fsr/src/exports.def b/clean/fsr/src/exports.def index fe3e4936..a1ed40ee 100644 --- a/clean/fsr/src/exports.def +++ b/clean/fsr/src/exports.def @@ -6,3 +6,4 @@ EXPORTS ffxDestroyContext ffxDispatch ffxQuery + WrongGpuHostSelectedV1 diff --git a/clean/fsr/src/frontend.cpp b/clean/fsr/src/frontend.cpp index 6a011d39..05c2affd 100644 --- a/clean/fsr/src/frontend.cpp +++ b/clean/fsr/src/frontend.cpp @@ -9,6 +9,7 @@ #include #include +#include "../include/wronggpu_host_event.h" #include "ffx_describe.h" #include "diagnostics.h" #include "wg_settings_io.h" // pure part: describe() (the registry's log words) @@ -568,20 +569,17 @@ ffxReturnCode_t FrontEnd::CreateUpscale(ffxContext* context, ffxCreateContextDes // OptiScaler ASI plugin (clean/fsr/asi): when it has hooked the host's MAIN upscaler list, its entry says WrongGPU or // AMD ("FSR 3.X(/4)"), and the game's model choice record (model_choice_record.h) says which WrongGPU model: the - // launcher, OptiScaler's FFX box (a WrongGPU entry the record did not know: the player picked it there) and the - // plugin's own model entries all write it, the highest seq is the most recent choice. A WrongGPU model -> WrongGPU, - // whatever AMD version the FFX box names. AMD -> AMD: the version the FFX sub-box names when that is one of AMD's, - // else AMD's newest listed version (FSR 4 when the AMD provider has it). + // launcher, a player's selection in OptiScaler's list (an event the WrongGPU edition of OptiScaler sends, + // HostSelected) and the plugin's own model entries write it, the highest seq is the most recent choice. The entry the + // FFX box stores is never a choice. A WrongGPU model -> WrongGPU, whatever version the FFX box names. AMD -> AMD: the + // version the FFX sub-box names when that is one of AMD's, else AMD's newest listed version (FSR 4 when the AMD + // provider has it). char asiModel = 0; const bool asiHooked = config_.hosted && platform_.asiPlugin && platform_.asiPlugin(&asiModel); bool forceAmd = false; if (asiHooked) { - char seen = wgchoice::kUnknown; // the WrongGPU model entry the FFX box names, if any - if (u->hasOverride) - if (const WgEntryDef* e = OwnEntryOfId(u->overrideId)) - if (e->slot == WG_OPT_SR_MODEL && e->value >= 0 && e->value < WG_SR_MODEL_COUNT) seen = kWgModelRows[e->value].name[0]; std::string why; - char model = ChooseModel(seen, asiModel, tag, &why); + char model = asiModel != 0 ? ChooseModel(asiModel, platform_.asiPending ? platform_.asiPending() : 0, 0, tag, &why) : 0; if (asiModel != 0) { const int32_t m = ModelOfName(std::string(1, model)); const WgEntryDef* sr = m >= 0 ? SrEntryOfModel(m) : nullptr; @@ -1401,56 +1399,120 @@ void FrontEnd::LogOnce(const std::string& tag, const std::string& line) { Log(tag + " " + line); } -char FrontEnd::ChooseModel(char seen, char plugin, const std::string& tag, std::string* why) { +char FrontEnd::ChooseModel(char plugin, char pluginPending, char entry, const std::string& tag, std::string* why) { const char launcher = LauncherModel(); - // no record: the launcher's K / L item, else the plugin's saved WrongGPU entry (0.6.0's rule), else Model M - auto noRecord = [&] { + const std::filesystem::path& path = platform_.choiceRecord; + std::lock_guard lock(choiceMutex_); + // without a record: a host selection made this session, the host's entry, the launcher's K / L item, the plugin's + // saved WrongGPU entry (0.6.0's rule), Model M + auto noRecord = [&](const std::string& reason) { + if (wgchoice::IsModel(sessionChoice_)) { + *why = reason + "; selected in OptiScaler's upscaler list this session"; + return sessionChoice_; + } + if (wgchoice::IsModel(entry)) { + *why = reason + "; the host's entry"; + return entry; + } if (launcher == 'K' || launcher == 'L') { - *why = std::string("no model choice record; the launcher's model item, wronggpu.ini model=") + launcher; + *why = reason + "; the launcher's model item, wronggpu.ini model=" + launcher; return launcher; } if (wgchoice::IsModel(plugin)) { - *why = std::string("no model choice record; the plugin's saved entry"); + *why = reason + "; the plugin's saved entry"; return plugin; } - *why = launcher ? std::string("no model choice record; wronggpu.ini model=") + launcher : std::string("no model choice record; the default"); + *why = launcher ? reason + "; wronggpu.ini model=" + launcher : reason + "; the default"; return 'M'; }; - if (platform_.choiceRecord.empty()) return noRecord(); - std::lock_guard lock(choiceMutex_); // one read-modify-write of the record at a time in this process - wgchoice::Record cur; + if (path.empty()) return noRecord("no model choice record"); + // A host selection that could not be written when it was made: tried again (dropped when a newer choice exists). + if (hostPending_.active()) { + const char model = hostPending_.model; + wgchoice::Record after; + std::string err; + const wgchoice::Outcome o = wgchoice::RetryPending(path, &hostPending_, &after, &err); + if (o == wgchoice::Outcome::Written) + Log(tag + " model choice: Model " + model + " (selected in OptiScaler's upscaler list earlier) written now (seq " + + std::to_string(after.seq) + ")"); + else if (o == wgchoice::Outcome::Superseded) + Log(tag + " model choice: Model " + model + " (selected in OptiScaler's upscaler list earlier, not written then) is " + "dropped: a newer choice was recorded meanwhile"); + else if (o == wgchoice::Outcome::SeqExhausted) + Log(tag + " ERROR: model choice: Model " + model + " selected in OptiScaler's upscaler list is refused: " + wgchoice::OutcomeWords(o)); + if (hostPending_.active()) { + LogOnce(tag, std::string("ERROR: model choice: Model ") + model + " (selected in OptiScaler's upscaler list) still cannot be " + "written (" + wgchoice::OutcomeWords(o) + (err.empty() ? "" : ": " + err) + "); it runs this session, tried again at each create"); + *why = "selected in OptiScaler's upscaler list this session, not saved yet"; + return model; + } + } + if (wgchoice::IsModel(pluginPending)) { + *why = "the plugin's click this session, not saved yet (the plugin tries again)"; + return pluginPending; + } + wgchoice::Record rec; + bool migrated = false; std::string err; - const wgchoice::ReadResult rr = wgchoice::ReadRecordFile(platform_.choiceRecord, &cur, &err); - if (rr == wgchoice::ReadResult::Corrupt) - LogOnce(tag, "model choice: the record (wronggpu-setup\\model-choice.ini) is corrupt (" + err + "): treated as no choice"); + const wgchoice::ReadResult rr = wgchoice::LoadOrMigrateRecord(path, launcher, &rec, &migrated, &err); + if (rr == wgchoice::ReadResult::Corrupt) { + LogOnce(tag, "model choice: the record (wronggpu-setup\\model-choice.ini) is corrupt (" + err + "): treated as no choice until the next choice replaces it"); + return noRecord("the model choice record is corrupt"); + } if (rr == wgchoice::ReadResult::Unreadable) { // (never written over: a record held open for a moment must not be replaced by a guess) LogOnce(tag, "model choice: the record (wronggpu-setup\\model-choice.ini) cannot be read (" + err + "): treated as no record"); - return noRecord(); - } - const wgchoice::Record* have = rr == wgchoice::ReadResult::Ok ? &cur : nullptr; - wgchoice::Record next; - const wgchoice::FfxStep step = wgchoice::FfxObservation(have, seen, &next); - if (step != wgchoice::FfxStep::None) { - if (wgchoice::WriteRecordFile(platform_.choiceRecord, next, &err)) { - if (step == wgchoice::FfxStep::Choice) - Log(tag + " model choice: Model " + next.model + " picked in OptiScaler's upscaler list (seq " + std::to_string(next.seq) + - (have ? std::string(", replacing Model ") + have->model + " from " + wgchoice::SourceWords(have->source) + - ", seq " + std::to_string(have->seq) + ")" - : std::string(", the first choice recorded for this game)"))); - } else { - LogOnce(tag, "ERROR: model choice: the record (wronggpu-setup\\model-choice.ini) could not be written (" + err + ")" + - (step == wgchoice::FfxStep::Choice ? "; this session uses the choice, the next one may not" : "")); - } - cur = next; // the player's choice in the list is real even when it could not be saved - have = &cur; + return noRecord("the model choice record cannot be read"); } - if (!have) return noRecord(); - *why = std::string("the model choice record: ") + wgchoice::SourceWords(have->source) + ", seq " + std::to_string(have->seq); - if (launcher && launcher != have->model) + if (rr == wgchoice::ReadResult::Missing) { + LogOnce(tag, "ERROR: model choice: no record yet, and it could not be written (" + err + ")"); + return noRecord("no model choice record (not written)"); + } + if (migrated) + Log(tag + " model choice: no record yet (an install from before 0.6.5): Model " + rec.model + " from " + + (launcher ? std::string("wronggpu.ini's model item") : std::string("the default")) + " recorded (seq 1, source=launcher)"); + *why = std::string("the model choice record: ") + wgchoice::SourceWords(rec.source) + ", seq " + std::to_string(rec.seq); + if (launcher && launcher != rec.model) LogOnce(tag, std::string("model choice conflict: wronggpu.ini's model item says Model ") + launcher + "; the more recent choice, Model " + - have->model + " from " + wgchoice::SourceWords(have->source) + " (seq " + std::to_string(have->seq) + "), runs"); - return have->model; + rec.model + " from " + wgchoice::SourceWords(rec.source) + " (seq " + std::to_string(rec.seq) + "), runs"); + return rec.model; +} + +int32_t FrontEnd::HostSelected(uint64_t versionId) { + const std::string tag = "host event:"; + const WgEntryDef* e = OwnEntryOfId(versionId); + if (!e || e->slot != WG_OPT_SR_MODEL || e->value < 0 || e->value >= WG_SR_MODEL_COUNT) { + Log(tag + " the player selected " + (e ? std::string(EntryProviderName(*e)) : "version " + Hex(versionId)) + + " in OptiScaler's upscaler list: no WrongGPU model choice"); + return WG_HOST_SELECTED_NOT_A_MODEL; + } + const char model = kWgModelRows[e->value].name[0]; + std::lock_guard lock(choiceMutex_); + if (platform_.choiceRecord.empty()) { + sessionChoice_ = model; + Log(tag + " the player selected Model " + model + " in OptiScaler's upscaler list; no model choice record (no launcher " + "state folder): it runs this session"); + return WG_HOST_SELECTED_SESSION_ONLY; + } + wgchoice::Record after; + wgchoice::Pending pending; + std::string err; + const wgchoice::Outcome o = wgchoice::RecordChoice(platform_.choiceRecord, model, wgchoice::Source::Ffx, &after, &err, &pending); + if (o == wgchoice::Outcome::Written) { + hostPending_ = wgchoice::Pending{}; + Log(tag + " the player selected Model " + model + " in OptiScaler's upscaler list: recorded (seq " + std::to_string(after.seq) + + ", source=ffx)" + (err.empty() ? "" : "; " + err)); + return WG_HOST_SELECTED_RECORDED; + } + if (o == wgchoice::Outcome::SeqExhausted) { + Log(tag + " ERROR: the player selected Model " + model + " in OptiScaler's upscaler list: " + wgchoice::OutcomeWords(o) + + ". Delete wronggpu-setup\\model-choice.ini or apply the model in the launcher."); + return WG_HOST_SELECTED_REFUSED; + } + hostPending_ = pending; + Log(tag + " ERROR: the player selected Model " + model + " in OptiScaler's upscaler list, but " + wgchoice::OutcomeWords(o) + + (err.empty() ? "" : " (" + err + ")") + ": it runs this session and is written at the next create"); + return WG_HOST_SELECTED_PENDING; } void FrontEnd::ApplyEntry(const WgEntryDef& e, UpscaleContext& u, const std::string& tag, const char* source) { @@ -1458,6 +1520,27 @@ void FrontEnd::ApplyEntry(const WgEntryDef& e, UpscaleContext& u, const std::str std::string described; if (model < 0 && ConfiguredModel(&model, &described)) Log(tag + " settings: " + described + " (the SR context's model)"); + // With a model choice record (a launcher install), the entry the host passes at a create is the index its ini stores, + // not a choice: the record decides the SR context's model (ChooseModel; a player's selection in the host's list + // reaches the record as an event, HostSelected). One folder per choice keeps its folder's model. + const WgEntryDef* shown = &e; // the entry written to the shared settings and logged + if (config_.hosted && !platform_.choiceRecord.empty() && std::strcmp(source, "folder") != 0) { + std::string why; + const char entry = model >= 0 && model < WG_SR_MODEL_COUNT ? kWgModelRows[model].name[0] : 0; + const char chosen = ChooseModel(0, platform_.asiPending ? platform_.asiPending() : 0, entry, tag, &why); + const int32_t m = ModelOfName(std::string(1, chosen)); + if (m >= 0 && SrEntryOfModel(m)) { + if (m != model) + Log(tag + " model choice: the host's entry names " + (entry ? std::string("Model ") + entry : std::string("no model")) + + "; Model " + chosen + " runs (" + why + "; an entry the host stores is not a choice)"); + else + Log(tag + " model choice: Model " + chosen + " (" + why + ")"); + model = m; + if (e.slot == WG_OPT_SR_MODEL) shown = SrEntryOfModel(m); + } else { + LogOnce(tag, std::string("note: model choice: Model ") + chosen + " is not part of this build of the front end; the host's entry is used"); + } + } if (const WgEntryDef* sr = model >= 0 ? SrEntryOfModel(model) : nullptr) { u.selectedModel = kWgModelRows[model].name[0]; u.modelOption = kWgModelRows[model].runtime_option; @@ -1469,9 +1552,9 @@ void FrontEnd::ApplyEntry(const WgEntryDef& e, UpscaleContext& u, const std::str if (OwnEntry(i)->slot == WG_OPT_SR_MODEL && std::strcmp(EntryProviderName(*OwnEntry(i)), u.modelProviderName) == 0) u.modelProviderId = OwnEntry(i)->id; } - const bool written = platform_.menu.set && platform_.menu.set(e.slot, e.value, source); + const bool written = platform_.menu.set && platform_.menu.set(shown->slot, shown->value, source); wg::Source word = std::strcmp(source, "folder") == 0 ? wg::Source::Sidecar : wg::Source::Menu; - Log(tag + " the host chose " + EntryProviderName(e) + " (" + Hex(e.id) + "): settings: " + wg::describe(e.slot, e.value, word) + + Log(tag + " the host chose " + EntryProviderName(e) + " (" + Hex(e.id) + "): settings: " + wg::describe(shown->slot, shown->value, word) + (written ? std::string() : platform_.menu.set ? " (not written: another module writes the shared settings)" : std::string()) + (e.slot == WG_OPT_SR_MODEL ? std::string() : std::string("; the SR context runs ") + u.modelProviderName)); } diff --git a/clean/fsr/src/frontend.h b/clean/fsr/src/frontend.h index 99128354..d0cac871 100644 --- a/clean/fsr/src/frontend.h +++ b/clean/fsr/src/frontend.h @@ -95,6 +95,8 @@ struct Platform { std::function asiPlugin; // Tells the plugin which model the context runs (0 AMD, 'M', 'K', 'L'), so its menu marks that entry. May be empty. std::function asiShowModel; + // The plugin's model click that could not be written to the record yet (it retries), else 0. May be empty. + std::function asiPending; // The game's model choice record (model_choice_record.h: wronggpu-setup\model-choice.ini next to wronggpu.ini), read // and written with real files. Empty: no record (the launcher's model item decides, as before). std::filesystem::path choiceRecord; @@ -162,6 +164,12 @@ class FrontEnd { size_t OwnContextCount(); // for tests bool HasParked(); // for tests + // The host tells the front end that the PLAYER selected the listed version `versionId` in its upscaler list during + // this session (the WrongGPU edition of OptiScaler calls the exported WrongGpuHostSelectedV1 before it recreates the + // upscaler). One of WrongGPU's SR model entries is a model choice: written to the model choice record (source=ffx). + // Returns kHostSelected* (wronggpu_host_event.h). + int32_t HostSelected(uint64_t versionId); + struct UpscaleContext; private: @@ -211,11 +219,15 @@ class FrontEnd { bool ConfiguredModel(int32_t* model, std::string* described); // The model the launcher's wronggpu.ini names (the last model item of runtime_options: 'M', 'K', 'L'), else 0. char LauncherModel() const; - // With the plugin hooked: the model choice record after a create that sees OptiScaler's list name `seen` (a WrongGPU - // model's entry, or wgchoice::kUnknown); writes the record when the list names an entry it did not know. The model - // that runs: the record's; without a record, the launcher's model item when it names Model K or L, else the plugin's - // saved WrongGPU entry (`plugin`; what decided before 0.6.5), else Model M. *why: which choice decided, for the log. - char ChooseModel(char seen, char plugin, const std::string& tag, std::string* why); + // The WrongGPU model a hosted create runs (with the plugin hooked, or for a host entry naming a WrongGPU model): a + // choice made this session that could not be saved yet (the host's, tried again first, or the plugin's, + // `pluginPending`), else the model choice record's (a game without one gets one from wronggpu.ini's model item, + // else Model M: LoadOrMigrateRecord). The entry OptiScaler's list stores is never taken for a choice while there is + // a record. Without one (no launcher state folder, or a record that cannot be read or is corrupt): a host selection + // made this session, else the host's entry (`entry`, 0 for none; how the custom slot chose before 0.6.5), else the + // launcher's model item when it names Model K or L, else the plugin's saved WrongGPU entry (`plugin`; what decided + // before 0.6.5), else Model M. *why: which choice decided, for the log. + char ChooseModel(char plugin, char pluginPending, char entry, const std::string& tag, std::string* why); // `line` logged once per session (after `tag`). void LogOnce(const std::string& tag, const std::string& line); // AMD's DLL behind a forwarded context (the one that created it), else AMD's original. @@ -278,7 +290,9 @@ class FrontEnd { uint32_t inputRefusedRun_ = 0; // refusals in a row with that key (mutex_) std::atomic inputRefusedAny_{false}; // inputRefusedRun_ > 0 (the taken-frame path's cheap check) std::map modelLogged_; // ApplyModelDir: each distinct choice logged once (mutex_) - std::mutex choiceMutex_; // ChooseModel: one read-modify-write of the choice record at a time + std::mutex choiceMutex_; // ChooseModel / HostSelected: hostPending_ and sessionChoice_ + wgchoice::Pending hostPending_; // a host selection not written yet (tried again at each create) + char sessionChoice_ = 0; // a host selection without a record (no launcher state folder) std::atomic reentered_{0}; // calls refused because they re-entered this front end on one thread std::mutex parkMutex_; // guards the three below; held while a parked context is destroyed UpscaleContext* parked_ = nullptr; diff --git a/clean/fsr/src/model_choice_record.h b/clean/fsr/src/model_choice_record.h index 7f93b9d2..45d4f2cb 100644 --- a/clean/fsr/src/model_choice_record.h +++ b/clean/fsr/src/model_choice_record.h @@ -2,38 +2,35 @@ #pragma once // The model choice record (0.6.5): ONE small file per game, wronggpu-setup\model-choice.ini in the folder of the front // end's wronggpu.ini (the launcher's state folder: an uninstall removes it by that name, a reinstall keeps it with the -// game's settings; without that folder there is no record), that every place which can choose WrongGPU's model writes, -// and which decides the model: -// - the launcher, when it applies a model (`WrongGPU.exe set model=`, or a change of the model item); -// - the front end, when the WrongGPU entry picked in OptiScaler's upscaler list (the FFX box, or OptiScaler 10's WrongGPU -// box) is not the one the record knows (`ffx`): the player picked it there; +// game's settings; without that folder there is no record). It decides which WrongGPU model runs. Three places write it, +// each only for an EVENT, a choice the player made: +// - the launcher, when it applies a model (`WrongGPU.exe set model=`, or a change of the model item); it then +// sets OptiScaler's UpscalerIndex to that model's entry, for display only; +// - the front end, when OptiScaler tells it that the player selected one of WrongGPU's entries in its upscaler list +// during the session (the WrongGPU edition of OptiScaler calls WrongGpuHostSelectedV1 in the front-end DLL); the +// stored index OptiScaler passes at a create is never taken for a choice; // - the WrongGPU menu plugin (clean/fsr/asi), when the player clicks one of its model entries. -// "Most recent" is the highest sequence number: a writer reads the record and writes seq + 1. No clock is involved, so a -// clock set back or forward changes nothing. +// "Most recent" is the highest sequence number. Every read-modify-write (read, seq + 1, write) runs under ONE lock per +// game shared by all processes (a named mutex, Local\WrongGPU-choice-), so no update is +// lost and seq never goes back. No clock is involved. // // The file, strictly (anything else is CORRUPT: logged and treated as "no choice", never as a partial one): // ; comment lines and blank lines // model= // seq=<1..18446744073709551615> (decimal digits only, overflow refused) // source= -// ffx= (the WrongGPU entry the writer knew OptiScaler's list to name; - = not known) -// each key exactly once, no other key, no spaces around '='. Writes are atomic: a temporary file in the same folder, -// flushed, then renamed over the record (on Windows through its handle with POSIX semantics, else MoveFileExW -// REPLACE_EXISTING | WRITE_THROUGH); a reader sees the old -// record or the new one, never part of one. A temporary file a crash left behind is never read. +// each key exactly once, no other key, no spaces around '='. Writes: a temporary file in the same folder, written in full +// and flushed (both checked), then MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH) over the record (checked). Readers take +// the lock too, so a reader never sees part of a record. A temporary file a crash left behind is never read. // -// Why `ffx`: OptiScaler's list keeps naming the entry it last selected. The launcher sets that entry with its model (and -// writes ffx = the entry it set), the plugin keeps the record's ffx (it cannot move OptiScaler's list), so an unchanged -// list never looks like a new choice; only a list entry the record does not know is the player's choice there. With no -// record at all, the entry seen at the first create counts as a choice (the launcher writes the record whenever it sets a -// model and the entry together, so a game without a record has had no model choice yet). +// Upgrade: a game without a record gets one from the launcher's existing choice (wronggpu.ini's model item, else Model M): +// seq 1, source=launcher (MigrateRecord). The model is never taken from OptiScaler's stored index. #include #include #include #include #include #include -#include #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN @@ -51,15 +48,13 @@ constexpr const wchar_t* kStateFolder = L"wronggpu-setup"; // the launcher's st constexpr const wchar_t* kRecordFile = L"model-choice.ini"; // The record of the game whose wronggpu.ini is in `iniDir`. inline std::filesystem::path RecordPathIn(const std::filesystem::path& iniDir) { return iniDir / kStateFolder / kRecordFile; } -constexpr char kUnknown = '-'; enum class Source { Launcher, Ffx, Plugin }; struct Record { - char model = 'M'; // 'M', 'K', 'L' - uint64_t seq = 0; // >= 1 in a valid record + char model = 'M'; // 'M', 'K', 'L' + uint64_t seq = 0; // >= 1 in a valid record Source source = Source::Launcher; - char ffx = kUnknown; // 'M', 'K', 'L' or kUnknown }; inline const char* SourceName(Source s) { return s == Source::Launcher ? "launcher" : s == Source::Ffx ? "ffx" : "plugin"; } @@ -86,7 +81,7 @@ inline bool ParseSeq(const std::string& v, uint64_t* out) { // false (with *why) for anything but one valid record. inline bool ParseRecord(const std::string& text, Record* out, std::string* why) { Record r; - bool hasModel = false, hasSeq = false, hasSource = false, hasFfx = false; + bool hasModel = false, hasSeq = false, hasSource = false; auto fail = [&](const std::string& w) { if (why) *why = w; return false; @@ -120,16 +115,11 @@ inline bool ParseRecord(const std::string& text, Record* out, std::string* why) else if (v == "plugin") r.source = Source::Plugin; else return fail("source is not launcher, ffx or plugin"); hasSource = true; - } else if (k == "ffx") { - if (hasFfx) return fail("ffx given twice"); - if (v.size() != 1 || !(IsModel(v[0]) || v[0] == kUnknown)) return fail("ffx is not M, K, L or -"); - r.ffx = v[0]; - hasFfx = true; } else { return fail("unknown key \"" + k + "\""); } } - if (!hasModel || !hasSeq || !hasSource || !hasFfx) return fail("model, seq, source and ffx are all needed"); + if (!hasModel || !hasSeq || !hasSource) return fail("model, seq and source are all needed"); *out = r; return true; } @@ -137,52 +127,76 @@ inline bool ParseRecord(const std::string& text, Record* out, std::string* why) inline std::string FormatRecord(const Record& r) { return std::string("; WrongGPU: the model chosen last for this game, by the launcher, OptiScaler's upscaler list (ffx) or the\r\n" "; WrongGPU menu plugin. The highest seq is the most recent choice. Written by WrongGPU; do not edit.\r\n") + - "model=" + r.model + "\r\nseq=" + std::to_string(r.seq) + "\r\nsource=" + SourceName(r.source) + "\r\nffx=" + r.ffx + "\r\n"; + "model=" + r.model + "\r\nseq=" + std::to_string(r.seq) + "\r\nsource=" + SourceName(r.source) + "\r\n"; } -// The record after a new choice of `model` by `source`, given the current one (`cur`, or none). `ffx`: what that writer -// knows OptiScaler's list names (kUnknown to keep the current record's). false when seq cannot grow (2^64 - 1 reached). -inline bool NextRecord(const Record* cur, char model, Source source, char ffx, Record* out) { - if (cur && cur->seq == UINT64_MAX) return false; - out->model = model; - out->seq = cur ? cur->seq + 1 : 1; - out->source = source; - out->ffx = ffx != kUnknown ? ffx : cur ? cur->ffx : kUnknown; - return true; -} +// ---- the lock ------------------------------------------------------------------------------------------------------- -enum class FfxStep { - None, // nothing to write: the list names the entry the record knows (or no WrongGPU entry) - Adopt, // the record did not know the list's entry (ffx = -): written with it, not a new choice - Choice, // the player picked another WrongGPU entry in OptiScaler's list (or the first create without a record) -}; +// The lock's name for a record: Local\WrongGPU-choice-. +// The launcher, the front end and the plugin (different processes and modules) derive the same name from the same file. +inline std::wstring LockName(const std::filesystem::path& record) { + std::wstring full = record.wstring(); +#ifdef _WIN32 + wchar_t buf[1024]; + const DWORD n = GetFullPathNameW(full.c_str(), 1024, buf, nullptr); + if (n > 0 && n < 1024) full.assign(buf, n); +#endif + uint64_t h = 1469598103934665603ull; + for (wchar_t c : full) { + if (c == L'/') c = L'\\'; + if (c >= L'A' && c <= L'Z') c = wchar_t(c - L'A' + L'a'); + h ^= uint64_t(uint16_t(c)); + h *= 1099511628211ull; + } + wchar_t hex[17]; + for (int i = 15; i >= 0; --i, h >>= 4) hex[i] = L"0123456789abcdef"[h & 15]; + hex[16] = 0; + return std::wstring(L"Local\\WrongGPU-choice-") + hex; +} -// What a create that sees OptiScaler's list naming `seen` ('M', 'K', 'L', or kUnknown for none / an AMD version) does -// to the record `cur` (or none): *out is the record to write for Adopt and Choice. -inline FfxStep FfxObservation(const Record* cur, char seen, Record* out) { - if (!IsModel(seen)) return FfxStep::None; - if (!cur) { - NextRecord(nullptr, seen, Source::Ffx, seen, out); - return FfxStep::Choice; +// Holds the record's lock for its lifetime. ok(): taken (within `timeoutMs`). An abandoned lock (a holder that died) is +// taken over: the record on disk is whole either way (atomic replacement). +class Lock { +public: + explicit Lock(const std::filesystem::path& record, unsigned timeoutMs = 3000) { +#ifdef _WIN32 + handle_ = CreateMutexW(nullptr, FALSE, LockName(record).c_str()); + if (!handle_) return; + const DWORD w = WaitForSingleObject(handle_, timeoutMs); + ok_ = w == WAIT_OBJECT_0 || w == WAIT_ABANDONED; +#else + (void)record; + (void)timeoutMs; + ok_ = true; +#endif } - if (cur->ffx == seen) return FfxStep::None; - if (cur->ffx == kUnknown) { - *out = *cur; - out->ffx = seen; - return FfxStep::Adopt; + ~Lock() { +#ifdef _WIN32 + if (handle_) { + if (ok_) ReleaseMutex(handle_); + CloseHandle(handle_); + } +#endif } - if (!NextRecord(cur, seen, Source::Ffx, seen, out)) return FfxStep::None; - return FfxStep::Choice; -} + bool ok() const { return ok_; } + Lock(const Lock&) = delete; + Lock& operator=(const Lock&) = delete; + +private: + bool ok_ = false; +#ifdef _WIN32 + HANDLE handle_ = nullptr; +#endif +}; -// ---- files -------------------------------------------------------------------------------------------------------- +// ---- files ---------------------------------------------------------------------------------------------------------- enum class ReadResult { Missing, Ok, Corrupt, Unreadable }; +// Reads the record (call it under the record's Lock). inline ReadResult ReadRecordFile(const std::filesystem::path& path, Record* out, std::string* why) { std::string text; #ifdef _WIN32 - // FILE_SHARE_DELETE: a writer may replace the record while it is read (the reader keeps the old one) HANDLE h = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (h == INVALID_HANDLE_VALUE) { @@ -223,8 +237,9 @@ inline ReadResult ReadRecordFile(const std::filesystem::path& path, Record* out, return ParseRecord(text, out, why) ? ReadResult::Ok : ReadResult::Corrupt; } -// Atomic replace: a temporary file next to the record (its name ends in .tmp; never read), written in full, flushed, then -// moved over the record. Up to `attempts` tries (a reader or scanner can hold the record for a moment). false with *why. +// Atomic replace: a temporary file next to the record (its name ends in .tmp; never read), written in full and flushed +// (both checked), then MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH) over the record (checked). Up to `attempts` tries, +// 20 ms apart. false with *why. Call it under the record's Lock. inline bool WriteRecordFile(const std::filesystem::path& path, const Record& r, std::string* why, int attempts = 3) { const std::string text = FormatRecord(r); std::string last; @@ -232,41 +247,32 @@ inline bool WriteRecordFile(const std::filesystem::path& path, const Record& r, #ifdef _WIN32 const std::wstring tmp = path.wstring() + L"." + std::to_wstring(GetCurrentProcessId()) + L"." + std::to_wstring(GetTickCount64()) + L"." + std::to_wstring(i) + L".tmp"; - HANDLE h = CreateFileW(tmp.c_str(), GENERIC_WRITE | DELETE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); + HANDLE h = CreateFileW(tmp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); if (h == INVALID_HANDLE_VALUE) { last = "cannot create the temporary file (Windows error " + std::to_string(GetLastError()) + ")"; } else { DWORD written = 0; const bool wrote = WriteFile(h, text.data(), DWORD(text.size()), &written, nullptr) && written == text.size(); const bool flushed = wrote && FlushFileBuffers(h); - bool moved = false; - if (wrote && flushed) { - // Rename through the handle with POSIX semantics (Windows 10 1809+, NTFS): the record is replaced also while - // a reader holds it open (readers open it with FILE_SHARE_DELETE and keep the old one); then flushed. - const std::wstring target = path.wstring(); - std::vector buf(sizeof(FILE_RENAME_INFO) + target.size() * sizeof(wchar_t)); - auto* info = reinterpret_cast(buf.data()); - const DWORD flags = 0x1 /* FILE_RENAME_FLAG_REPLACE_IF_EXISTS */ | 0x2 /* FILE_RENAME_FLAG_POSIX_SEMANTICS */; - std::memcpy(buf.data(), &flags, sizeof flags); // the union { ReplaceIfExists; Flags } at offset 0 - info->RootDirectory = nullptr; - info->FileNameLength = DWORD(target.size() * sizeof(wchar_t)); - std::memcpy(info->FileName, target.c_str(), target.size() * sizeof(wchar_t)); - moved = SetFileInformationByHandle(h, static_cast(22) /* FileRenameInfoEx */, info, - DWORD(buf.size())) != 0; - if (moved) FlushFileBuffers(h); - } - CloseHandle(h); - if (!wrote || !flushed) { - last = wrote ? "cannot flush the temporary file" : "cannot write the temporary file"; + const DWORD flushError = flushed ? 0 : GetLastError(); + const bool closed = CloseHandle(h) != 0; + if (!wrote) { + last = "cannot write the temporary file"; + DeleteFileW(tmp.c_str()); + } else if (!flushed) { + last = "cannot flush the temporary file (Windows error " + std::to_string(flushError) + ")"; DeleteFileW(tmp.c_str()); - } else if (moved || MoveFileExW(tmp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { - return true; // (MoveFileExW: older Windows or file systems without the POSIX rename) + } else if (!closed) { + last = "cannot close the temporary file"; + DeleteFileW(tmp.c_str()); + } else if (MoveFileExW(tmp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { + return true; } else { last = "cannot replace the record (Windows error " + std::to_string(GetLastError()) + ")"; DeleteFileW(tmp.c_str()); } } - Sleep(20); + if (i + 1 < attempts) Sleep(20); #else const std::filesystem::path tmp = path.string() + "." + std::to_string(i) + ".tmp"; { @@ -291,4 +297,101 @@ inline bool WriteRecordFile(const std::filesystem::path& path, const Record& r, return false; } +// ---- the operations, each one read-modify-write under the lock ------------------------------------------------------ + +enum class Outcome { Written, NoLock, Unreadable, SeqExhausted, WriteFailed, Superseded }; + +inline const char* OutcomeWords(Outcome o) { + switch (o) { + case Outcome::Written: return "written"; + case Outcome::Superseded: return "a newer choice was recorded meanwhile (this one is dropped)"; + case Outcome::NoLock: return "the record's lock could not be taken"; + case Outcome::Unreadable: return "the record cannot be read (not written over)"; + case Outcome::SeqExhausted: return "the record's sequence number is at its end (18446744073709551615): choice refused"; + case Outcome::WriteFailed: return "the record could not be written"; + } + return "?"; +} + +// A choice that could not be written when it was made (NoLock, Unreadable, WriteFailed): kept by its writer, used for +// the session and written later (RetryPending). base: the seq the record had when the choice was made (0: no record or a +// corrupt one); baseKnown false: the record could not be read then. +struct Pending { + char model = 0; // 0: nothing pending + Source source = Source::Plugin; + bool baseKnown = false; + uint64_t baseSeq = 0; + bool active() const { return model != 0; } +}; + +// A choice of `model` by `source`: read the record and write seq + 1 (seq 1 without a record, or over a corrupt one, +// which *why then names). `retry`: a pending choice being written later: dropped (Superseded) when the record moved past +// its base meanwhile. *after: the record written. *pending (when given): filled on a failure that can be retried. Any +// failure leaves the record as it was. Call it under the record's Lock (RecordChoice / RetryPending take it). +inline Outcome RecordChoiceUnlocked(const std::filesystem::path& path, char model, Source source, Record* after, std::string* why, + Pending* pending = nullptr, const Pending* retry = nullptr) { + Record cur; + std::string err; + const ReadResult rr = ReadRecordFile(path, &cur, &err); + if (rr == ReadResult::Unreadable) { + if (why) *why = err; + if (pending) *pending = Pending{model, source, false, 0}; + return Outcome::Unreadable; + } + const uint64_t seqNow = rr == ReadResult::Ok ? cur.seq : 0; + if (retry && retry->baseKnown && seqNow != retry->baseSeq) return Outcome::Superseded; + if (rr == ReadResult::Corrupt && why) *why = "a corrupt record was replaced (" + err + ")"; + if (rr == ReadResult::Ok && cur.seq == UINT64_MAX) return Outcome::SeqExhausted; + const Record next{model, seqNow + 1, source}; + if (!WriteRecordFile(path, next, &err)) { + if (why) *why = err; + if (pending) *pending = Pending{model, source, true, seqNow}; + return Outcome::WriteFailed; + } + if (after) *after = next; + return Outcome::Written; +} + +inline Outcome RecordChoice(const std::filesystem::path& path, char model, Source source, Record* after, std::string* why, + Pending* pending = nullptr, unsigned lockMs = 3000) { + Lock lock(path, lockMs); + if (!lock.ok()) { + if (pending) *pending = Pending{model, source, false, 0}; + return Outcome::NoLock; + } + return RecordChoiceUnlocked(path, model, source, after, why, pending); +} + +// Writes a pending choice (see Pending). Written or Superseded: nothing is pending any more (*p cleared); SeqExhausted: +// cleared too (refused for good); otherwise *p stays for a later try. +inline Outcome RetryPending(const std::filesystem::path& path, Pending* p, Record* after, std::string* why, unsigned lockMs = 3000) { + if (!p->active()) return Outcome::Superseded; + Lock lock(path, lockMs); + if (!lock.ok()) return Outcome::NoLock; + const Pending retry = *p; + const Outcome o = RecordChoiceUnlocked(path, retry.model, retry.source, after, why, nullptr, &retry); + if (o == Outcome::Written || o == Outcome::Superseded || o == Outcome::SeqExhausted) *p = Pending{}; + return o; +} + +// The record as it is now, read under the lock. A game without one (an install from before 0.6.5) gets one from the +// launcher's existing choice (`launcherModel`, 'M' / 'K' / 'L', or 0 for none: Model M), seq 1, source=launcher. +// Returns Ok (also after the migration; *out set, *migrated true then), Corrupt or Unreadable (*why; nothing written), or +// Missing when the lock or the migration's write failed (*why). +inline ReadResult LoadOrMigrateRecord(const std::filesystem::path& path, char launcherModel, Record* out, bool* migrated, std::string* why) { + if (migrated) *migrated = false; + Lock lock(path); + if (!lock.ok()) { + if (why) *why = "the record's lock could not be taken"; + return ReadResult::Unreadable; + } + const ReadResult rr = ReadRecordFile(path, out, why); + if (rr != ReadResult::Missing) return rr; + const Record first{IsModel(launcherModel) ? launcherModel : 'M', 1, Source::Launcher}; + if (!WriteRecordFile(path, first, why)) return ReadResult::Missing; + *out = first; + if (migrated) *migrated = true; + return ReadResult::Ok; +} + } // namespace wgchoice diff --git a/clean/fsr/src/settings_bridge.cpp b/clean/fsr/src/settings_bridge.cpp index 2dce4b3b..8d6dff16 100644 --- a/clean/fsr/src/settings_bridge.cpp +++ b/clean/fsr/src/settings_bridge.cpp @@ -6,6 +6,7 @@ #define WG_SETTINGS_IO_IMPLEMENTATION #include "wg_settings_io.h" +#include #include #include "settings_bridge.h" @@ -180,6 +181,9 @@ wgfsr::MenuSettings Menu() { return m; } +std::atomic g_pollModels{true}; +void SetHostIniPollModels(bool apply) { g_pollModels.store(apply); } + bool HostIniPollActive() { State& s = S(); return s.initialised && s.poll.configured() && s.block.is_writer(); @@ -198,6 +202,11 @@ bool PollHostIni() { " is not one of WrongGPU's entries (one of AMD's versions); nothing to apply"); return true; } + if (e->slot == WG_OPT_SR_MODEL && !g_pollModels.load()) { + L().WriteLine("settings: " + N(s.poll.path()) + " [" + s.poll.section() + "] UpscalerIndex=" + std::to_string(index) + " = " + + wgfsr::EntryProviderName(*e) + ": not applied (a stored index is no model choice; the model choice record decides)"); + return true; + } L().WriteLine("settings: " + N(s.poll.path()) + " [" + s.poll.section() + "] UpscalerIndex=" + std::to_string(index) + " = " + wgfsr::EntryProviderName(*e)); WriteChoice(e->slot, e->value, "optiscaler.ini"); diff --git a/clean/fsr/src/settings_bridge.h b/clean/fsr/src/settings_bridge.h index dc812bfc..12058270 100644 --- a/clean/fsr/src/settings_bridge.h +++ b/clean/fsr/src/settings_bridge.h @@ -46,6 +46,9 @@ int32_t Setting(uint32_t slot, std::string* described = nullptr, bool* isDefault // The OptiScaler.ini [] UpscalerIndex poll (mtime at most once per second); applies a changed index as if it // had been chosen in the menu (writer only). True while there is something to poll (custom slot and writer). bool PollHostIni(); +// false: the poll leaves WrongGPU's SR model entries alone (a launcher install: the model choice record decides the +// model, and the index the host's ini stores is no choice); RR mode entries are applied as before. Default true. +void SetHostIniPollModels(bool apply); bool HostIniPollActive(); // For tests and logs. diff --git a/clean/fsr/tests/test_asi_status.cpp b/clean/fsr/tests/test_asi_status.cpp index 761ade63..64c1e597 100644 --- a/clean/fsr/tests/test_asi_status.cpp +++ b/clean/fsr/tests/test_asi_status.cpp @@ -131,6 +131,9 @@ int main(int argc, char** argv) { int hooked = -1; char model = '?'; CHECK(legacy(&hooked, &model) == 1 && hooked == 0 && model == 'M'); // the saved entry is unchanged } + // no click was made: nothing is pending + auto pending = reinterpret_cast(GetProcAddress(module, WRONGGPU_ASI_PENDING_CHOICE)); + CHECK(pending != nullptr && pending() == 0); CHECK(FreeLibrary(module) != 0); // No initialization or patches ever occurred. CHECK(GetModuleHandleA(argv[1]) == nullptr); // Query-only loading did not permanently pin it. } diff --git a/clean/fsr/tests/test_asi_thunk.cpp b/clean/fsr/tests/test_asi_thunk.cpp index fb384cc1..09e42d9a 100644 --- a/clean/fsr/tests/test_asi_thunk.cpp +++ b/clean/fsr/tests/test_asi_thunk.cpp @@ -197,6 +197,35 @@ void TestClickAndShownModel() { #endif } +// A model click the plugin could not write to the model choice record yet: its entry says so in the menu ("not saved +// yet, retrying"; "not saved: the choice record is full" when refused), the other entries are unchanged, and a click on +// the labelled entry is still that model's click. +void TestUnsavedLabel() { + PluginState st; + const int size = 0; + const Entry& last = kEntries[kEntryCount - 1]; + st.unsaved.store(last.model); + FakeSelectable draw; + SelectableThunkLogic(draw, "FSR 3.X", true, 0, &size, st); + CHECK(draw.calls.size() == kEntryCount + 1); + for (size_t i = 0; i + 1 < kEntryCount; ++i) CHECK(draw.calls[i].label == kEntries[i].label); + CHECK(draw.calls[kEntryCount - 1].label == std::string(last.label) + kUnsavedSuffix); + CHECK(draw.calls[kEntryCount].label == "FSR 3.X"); + st.refused.store(true); + FakeSelectable refused; + SelectableThunkLogic(refused, "FSR 3.X", true, 0, &size, st); + CHECK(refused.calls[kEntryCount - 1].label == std::string(last.label) + kRefusedSuffix); + st.refused.store(false); + FakeSelectable click; + click.clickLabel = std::string(last.label) + kUnsavedSuffix; + bool clicked = false; + CHECK(SelectableThunkLogic(click, "FSR 3.X", true, 0, &size, st, &clicked) && clicked && st.model.load() == last.model); + st.unsaved.store(0); + FakeSelectable plain; + SelectableThunkLogic(plain, "FSR 3.X", true, 0, &size, st); + CHECK(plain.calls[kEntryCount - 1].label == last.label); +} + } // namespace int main() { @@ -209,6 +238,7 @@ int main() { TestPreviewRelabel(); TestSelectionFile(); TestClickAndShownModel(); + TestUnsavedLabel(); std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } diff --git a/clean/fsr/tests/test_frontend.cpp b/clean/fsr/tests/test_frontend.cpp index f6a2b091..6d364c04 100644 --- a/clean/fsr/tests/test_frontend.cpp +++ b/clean/fsr/tests/test_frontend.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -20,6 +21,7 @@ #include #include +#include "../include/wronggpu_host_event.h" #include "../src/config.h" #include "../src/ffx_describe.h" #include "../src/frontend.h" @@ -241,6 +243,7 @@ static bool g_asiHooked = false; // and it reports a successful hook static char g_asiModel = 0; // 0 (AMD), 'M', 'K' static std::vector g_asiShown; // Platform::asiShowModel calls static std::filesystem::path g_choiceRecord; // Platform::choiceRecord (a real file; empty: none) +static char g_asiPendingModel = 0; // Platform::asiPending (the plugin's unsaved click) // Fake shared settings (Platform::menu, settings_bridge.h in the DLL): values set "somewhere" (block / env / ini), // the writes of the menu's choices, whether this module is the writer, the folder sidecar's entry. @@ -284,6 +287,7 @@ static std::unique_ptr MakeFrontEnd(const Config& config) { if (g_asiPresent) p.asiPlugin = [](char* model) { if (model) *model = g_asiModel; return g_asiHooked; }; if (g_asiPresent) p.asiShowModel = [](char model) { g_asiShown.push_back(model); }; + if (g_asiPresent) p.asiPending = [] { return g_asiPendingModel; }; p.choiceRecord = g_choiceRecord; p.compareApi = []() -> const OriginalApi* { return g_compareApi; }; p.backend = [](const Config&, std::string&) -> const WgUpscalerBackend* { return g_useBackend; }; @@ -378,6 +382,7 @@ static void Reset() { g_asiHooked = false; g_asiModel = 0; g_asiShown.clear(); + g_asiPendingModel = 0; g_createInfo = WgCreateInfo{}; g_compare = false; g_statuses.clear(); @@ -2605,10 +2610,13 @@ static void TestAsiPluginPresetK() { #endif } -// 0.6.5 (#213): with the plugin hooked, the game's model choice record (model_choice_record.h) decides the WrongGPU model, -// on REAL files in a fresh folder under the temporary folder: the launcher's, OptiScaler's list's (ffx) and the plugin's -// choices, the highest seq winning; the launcher's own index rewrite never a choice; the first create without a record; -// corrupt and unreadable records. Plus the audit's case without any record (the launcher's model item). +// 0.6.5 (#213): the game's model choice record (model_choice_record.h) decides the WrongGPU model of a hosted create, on +// REAL files in a fresh folder under the temporary folder, through the front end: the upgrade migration (wronggpu.ini's +// model item, never the stored index); the index OptiScaler stores is never a choice (hooked route and custom slot); +// a player's selection in OptiScaler's list arrives as an event (HostSelected) and is recorded, also re-selecting the +// same entry after a plugin choice; each source winning in turn; AMD; corrupt, unreadable and exhausted records; a +// failed event write that runs for the session and is written at the next create (or dropped when superseded); the +// plugin's unsaved click; a game without a record. Plus the audit's case without any record (the launcher's model item). struct RecordFolder { std::filesystem::path dir; RecordFolder() { @@ -2631,13 +2639,20 @@ static wgchoice::Record ReadRec(const std::filesystem::path& p, wgchoice::ReadRe std::string why; const wgchoice::ReadResult res = wgchoice::ReadRecordFile(p, &r, &why); if (rr) *rr = res; - if (res != wgchoice::ReadResult::Ok) r = wgchoice::Record{0, 0, wgchoice::Source::Launcher, wgchoice::kUnknown}; + if (res != wgchoice::ReadResult::Ok) r = wgchoice::Record{0, 0, wgchoice::Source::Launcher}; return r; } -// One hosted create with the plugin hooked (its entry `plugin`: 0 AMD or a WrongGPU model), OptiScaler's FFX box naming -// `overrideId`; the provider the context runs ("" for AMD). -static std::string HookedCreate(const char* ini, char plugin, uint64_t overrideId) { +static void WriteRec(const std::filesystem::path& p, const std::string& text) { + std::ofstream o(p, std::ios::binary | std::ios::trunc); + o << text; +} + +// One hosted create, OptiScaler's list naming `overrideId` (0: none). hooked: the plugin hooked with its entry `plugin` +// (0 AMD or a WrongGPU model); else the custom slot / FFX route without the plugin (the host's entry). `before` runs on +// the front end first (a host event). The provider the context runs ("" for AMD). +static std::string HostedCreate(const char* ini, char plugin, uint64_t overrideId, bool hooked = true, + const std::function& before = {}) { Reset(); g_resources[kOutput] = {dxgi::R16G16B16A16_FLOAT, 2560, 1440}; std::string warnings; @@ -2646,12 +2661,13 @@ static std::string HookedCreate(const char* ini, char plugin, uint64_t overrideI c.hosted = true; c.upscaler = UpscalerChoice::Network; c.contextParkMs = 0; - g_asiPresent = true; - g_asiHooked = true; + g_asiPresent = hooked; + g_asiHooked = hooked; g_asiModel = plugin; auto fe = MakeFrontEnd(c); + if (before) before(*fe); const size_t amd = g_amd.size(); - UpscaleCreate create(FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE, true); + UpscaleCreate create(FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE, overrideId != 0); create.version.versionId = overrideId; ffxContext ctx = nullptr; CHECK(fe->CreateContext(&ctx, &create.upscale.header, kMemCb) == FFX_API_RETURN_OK && ctx); @@ -2671,89 +2687,161 @@ static void TestAsiChoiceRecord() { const bool hasL = ModelOfName("L") >= 0, hasK = ModelOfName("K") >= 0; auto idOf = [](char m) { return SrEntryOfModel(ModelOfName(std::string(1, m)))->id; }; auto name = [](char m) { return std::string("WrongGPU Model ") + m; }; - // A second model to choose (L, else K); a build with neither checks the record rule with Model M only (below). + auto lines = [](const std::string& s) { return CountLog(s.c_str()); }; + // A second model to choose (L, else K); a build with neither checks the record with Model M only (below). const char b = hasL ? 'L' : hasK ? 'K' : 0; const char c3 = hasL && hasK ? 'K' : 0; // a third model, in a build with both RecordFolder f; + const std::filesystem::path& rec = f.record(); std::string why; // The audit's case without a record (a front end without the state folder): the launcher's K / L item decides over the // plugin's saved default entry (Model M). if (b) { const std::string ini = std::string("runtime_options = model=") + b + "\n"; - CHECK(HookedCreate(ini.c_str(), 'M', kWrongGpuProviderVersionId) == name(b)); + CHECK(HostedCreate(ini.c_str(), 'M', kWrongGpuProviderVersionId) == name(b)); CHECK(CountLog("no model choice record; the launcher's model item") == 1); + // a host event without a record (no launcher state folder): it runs this session only + int32_t rc = 0; + CHECK(HostedCreate(ini.c_str(), 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name('M')); + CHECK(rc == WG_HOST_SELECTED_SESSION_ONLY && CountLog("selected in OptiScaler's upscaler list this session") == 1); } - g_choiceRecord = f.record(); + g_choiceRecord = rec; if (b) { - const std::string ini = std::string("runtime_options = model=") + b + "\n"; - // (1) the launcher applied b and set OptiScaler's entry with it (record: b, seq 1, ffx=b): b runs, nothing written - wgchoice::Record next; - CHECK(wgchoice::NextRecord(nullptr, b, wgchoice::Source::Launcher, b, &next) && wgchoice::WriteRecordFile(f.record(), next, &why)); - CHECK(HookedCreate(ini.c_str(), 'M', idOf(b)) == name(b)); - CHECK(ReadRec(f.record()).seq == 1 && g_asiShown.size() == 1 && g_asiShown[0] == b); - CHECK(CountLog("selected in the host's upscaler list (the model choice record: the launcher, seq 1)") == 1); - // (2) the player picks Model M in OptiScaler's FFX box: a choice there (seq 2, source=ffx); M runs, with its line - CHECK(HookedCreate(ini.c_str(), 'M', idOf('M')) == name('M')); - wgchoice::Record r = ReadRec(f.record()); - CHECK(r.model == 'M' && r.seq == 2 && r.source == wgchoice::Source::Ffx && r.ffx == 'M'); - CHECK(CountLog((std::string("model choice: Model M picked in OptiScaler's upscaler list (seq 2, replacing Model ") + b + - " from the launcher, seq 1)").c_str()) == 1); - CHECK(CountLog((std::string("model choice conflict: wronggpu.ini's model item says Model ") + b).c_str()) == 1); - // (3) the player clicks b in the plugin's menu (the plugin writes seq 3, source=plugin, keeping ffx=M); OptiScaler's - // box still names M: that is no new choice, b runs - CHECK(wgchoice::NextRecord(&r, b, wgchoice::Source::Plugin, wgchoice::kUnknown, &next) && wgchoice::WriteRecordFile(f.record(), next, &why)); - CHECK(HookedCreate(ini.c_str(), b, idOf('M')) == name(b)); - r = ReadRec(f.record()); - CHECK(r.model == b && r.seq == 3 && r.source == wgchoice::Source::Plugin && r.ffx == 'M'); - CHECK(CountLog("picked in OptiScaler's upscaler list") == 0); - // (4) the launcher re-applies Model M (seq 4) and sets the box to M: its own index rewrite is no choice; M runs - CHECK(wgchoice::NextRecord(&r, 'M', wgchoice::Source::Launcher, 'M', &next) && wgchoice::WriteRecordFile(f.record(), next, &why)); - CHECK(HookedCreate("runtime_options = model=M\n", b, idOf('M')) == name('M')); - CHECK(ReadRec(f.record()).seq == 4 && CountLog("picked in OptiScaler's upscaler list") == 0); - // (5) a third model in the box (a build with K and L): the player's choice again (seq 5) + const std::string iniB = std::string("runtime_options = model=") + b + "\n"; + const char* iniM = "runtime_options = model=M\n"; + // (1) upgrade: no record, wronggpu.ini says b, OptiScaler's box names Model M: the record is migrated from the model + // item (b, seq 1, source=launcher), never from the box; b runs + CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M')) == name(b)); + wgchoice::Record r = ReadRec(rec); + CHECK(r.model == b && r.seq == 1 && r.source == wgchoice::Source::Launcher); + CHECK(lines(std::string("model choice: no record yet (an install from before 0.6.5): Model ") + b + " from wronggpu.ini's model item") == 1); + CHECK(lines("selected in the host's upscaler list (the model choice record: the launcher, seq 1)") == 1); + // (2) the stored index is never a choice: the box names M at every create, the record stays b, seq 1 + CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M')) == name(b)); + CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M')) == name(b)); + CHECK(ReadRec(rec).seq == 1 && g_asiShown.size() == 1 && g_asiShown[0] == b); + // (3) the player selects Model M in OptiScaler's list: the event is recorded (seq 2, source=ffx); M runs + int32_t rc = 0; + CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name('M')); + r = ReadRec(rec); + CHECK(rc == WG_HOST_SELECTED_RECORDED && r.model == 'M' && r.seq == 2 && r.source == wgchoice::Source::Ffx); + CHECK(lines("the player selected Model M in OptiScaler's upscaler list: recorded (seq 2, source=ffx)") == 1); + CHECK(lines(std::string("model choice conflict: wronggpu.ini's model item says Model ") + b) == 1); + // (4) the player clicks b in the plugin's menu (the plugin writes seq 3, source=plugin); the box still names M: b runs + wgchoice::Record after; + CHECK(wgchoice::RecordChoice(rec, b, wgchoice::Source::Plugin, &after, &why) == wgchoice::Outcome::Written); + CHECK(HostedCreate(iniB.c_str(), b, idOf('M')) == name(b)); + CHECK(ReadRec(rec).seq == 3); + // (5) the player selects the SAME entry (M) in OptiScaler's list again after the plugin's choice: it wins (seq 4) + CHECK(HostedCreate(iniB.c_str(), b, idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name('M')); + r = ReadRec(rec); + CHECK(rc == WG_HOST_SELECTED_RECORDED && r.model == 'M' && r.seq == 4 && r.source == wgchoice::Source::Ffx); + // (6) the launcher applies b (seq 5): b runs + CHECK(wgchoice::RecordChoice(rec, b, wgchoice::Source::Launcher, &after, &why) == wgchoice::Outcome::Written); + CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M')) == name(b)); + // (7) a third model selected in the list (a build with K and L) if (c3) { - CHECK(HookedCreate("runtime_options = model=M\n", b, idOf(c3)) == name(c3)); - r = ReadRec(f.record()); - CHECK(r.model == c3 && r.seq == 5 && r.source == wgchoice::Source::Ffx); + CHECK(HostedCreate(iniM, b, idOf(b), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf(c3)); }) == name(c3)); + r = ReadRec(rec); + CHECK(r.model == c3 && r.seq == 6 && r.source == wgchoice::Source::Ffx); } - // the plugin's AMD entry: AMD runs; the record is untouched - const wgchoice::Record before = ReadRec(f.record()); - CHECK(HookedCreate("runtime_options = model=M\n", 0, idOf(before.ffx)).empty()); - CHECK(ReadRec(f.record()).seq == before.seq); - CHECK(CountLog("OptiScaler plugin: AMD FSR selected in the host's upscaler list") == 1); - // an AMD version in the FFX box is no model choice - const uint64_t s2 = ReadRec(f.record()).seq; - HookedCreate("runtime_options = model=M\n", 'M', g_versionIds[0]); - CHECK(ReadRec(f.record()).seq == s2); - // (6) the first create without a record: the entry the box names counts as a choice (seq 1, source=ffx) - std::error_code ec; - std::filesystem::remove(f.record(), ec); - CHECK(HookedCreate(ini.c_str(), 'M', idOf(b)) == name(b)); - r = ReadRec(f.record()); - CHECK(r.model == b && r.seq == 1 && r.source == wgchoice::Source::Ffx && r.ffx == b); - CHECK(CountLog("the first choice recorded for this game") == 1); - // (7) a corrupt record (seq overflow): said once, treated as no choice, replaced by the box's entry + // (8) an AMD version selected in the list is no model choice; the plugin's AMD entry runs AMD; the record is untouched + const uint64_t s0 = ReadRec(rec).seq; + CHECK(HostedCreate(iniM, 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(g_versionIds[0]); }) != ""); + CHECK(rc == WG_HOST_SELECTED_NOT_A_MODEL && ReadRec(rec).seq == s0); + CHECK(HostedCreate(iniM, 0, idOf('M')).empty()); + CHECK(ReadRec(rec).seq == s0 && CountLog("OptiScaler plugin: AMD FSR selected in the host's upscaler list") == 1); + // (9) the custom slot / FFX route without the plugin: the host's entry names M, the record says b: b runs + CHECK(wgchoice::RecordChoice(rec, b, wgchoice::Source::Launcher, &after, &why) == wgchoice::Outcome::Written); + CHECK(HostedCreate(iniM, 0, idOf('M'), false) == name(b)); + CHECK(lines(std::string("model choice: the host's entry names Model M; Model ") + b + " runs") == 1); + // ... and a selection event there is recorded and runs + CHECK(HostedCreate(iniM, 0, idOf(b), false, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name('M')); + CHECK(rc == WG_HOST_SELECTED_RECORDED && ReadRec(rec).model == 'M'); +#ifdef _WIN32 + // (10) a selection whose write fails (the record held open without delete sharing): it runs this session, said as an + // ERROR, and is written at the next create once the record is free + CHECK(wgchoice::RecordChoice(rec, 'M', wgchoice::Source::Launcher, &after, &why) == wgchoice::Outcome::Written); + const uint64_t s1 = after.seq; + HANDLE hold = CreateFileW(rec.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + CHECK(hold != INVALID_HANDLE_VALUE); { - std::ofstream o(f.record(), std::ios::binary | std::ios::trunc); - o << "model=L\nseq=18446744073709551616\nsource=launcher\nffx=L\n"; + Reset(); + g_resources[kOutput] = {dxgi::R16G16B16A16_FLOAT, 2560, 1440}; + std::string w; + Config c = ParseConfig(iniM, &w); + c.hosted = true; + c.upscaler = UpscalerChoice::Network; + c.contextParkMs = 0; + g_asiPresent = g_asiHooked = true; + g_asiModel = 'M'; + auto fe = MakeFrontEnd(c); + CHECK(fe->HostSelected(idOf(b)) == WG_HOST_SELECTED_PENDING); + CHECK(CountLog("is written at the next create") == 1 && ReadRec(rec).seq == s1); + auto create = [&] { + UpscaleCreate cr(FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE, true); + cr.version.versionId = idOf('M'); + ffxContext ctx = nullptr; + CHECK(fe->CreateContext(&ctx, &cr.upscale.header, kMemCb) == FFX_API_RETURN_OK && ctx); + ffxQueryGetProviderVersion q{}; + q.header.type = FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION; + std::string p; + if (fe->Query(&ctx, &q.header) == FFX_API_RETURN_OK && q.versionName) p = q.versionName; + CHECK(fe->DestroyContext(&ctx, kMemCb) == FFX_API_RETURN_OK); + return p; + }; + CHECK(create() == name(b)); // still held: runs this session + CHECK(CountLog("still cannot be written") == 1 && ReadRec(rec).seq == s1); + CloseHandle(hold); + CHECK(create() == name(b)); // free: written now + r = ReadRec(rec); + CHECK(r.model == b && r.seq == s1 + 1 && r.source == wgchoice::Source::Ffx && CountLog("written now") == 1); + // superseded: a selection that fails, then the launcher writes M; the pending one is dropped, M runs + hold = CreateFileW(rec.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + CHECK(fe->HostSelected(idOf(b)) == WG_HOST_SELECTED_PENDING); + CloseHandle(hold); + CHECK(wgchoice::RecordChoice(rec, 'M', wgchoice::Source::Launcher, &after, &why) == wgchoice::Outcome::Written); + CHECK(create() == name('M')); + CHECK(CountLog("is dropped: a newer choice was recorded meanwhile") == 1 && ReadRec(rec).model == 'M'); } - CHECK(HookedCreate("runtime_options = model=M\n", 'M', idOf('M')) == name('M')); - CHECK(CountLog("is corrupt (seq is not a number") == 1); - r = ReadRec(f.record()); - CHECK(r.model == 'M' && r.seq == 1 && r.source == wgchoice::Source::Ffx); -#ifdef _WIN32 - // (8) a record another program holds open without sharing: not read, NEVER written over; the launcher's item decides - HANDLE lock = CreateFileW(f.record().c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); - CHECK(lock != INVALID_HANDLE_VALUE); - CHECK(HookedCreate(ini.c_str(), 'M', idOf(b)) == name(b)); - CHECK(CountLog("cannot be read") == 1); - CloseHandle(lock); - CHECK(ReadRec(f.record()).model == 'M' && ReadRec(f.record()).seq == 1); // unchanged + // (11) the plugin's click it could not write yet: it runs this session + { + const uint64_t s2 = ReadRec(rec).seq; + CHECK(HostedCreate(iniM, b, idOf('M'), true, [&](FrontEnd&) { g_asiPendingModel = b; }) == name(b)); + g_asiPendingModel = 0; + CHECK(CountLog("the plugin's click this session, not saved yet") == 1 && ReadRec(rec).seq == s2); + } + // (12) a record another program holds open without sharing: not read, NEVER written over; the launcher's item decides + const std::string kept = ReadRec(rec).model == 'M' ? "M" : "?"; + hold = CreateFileW(rec.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + CHECK(hold != INVALID_HANDLE_VALUE); + CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M')) == name(b)); + CHECK(CountLog("model choice: the record (wronggpu-setup\\model-choice.ini) cannot be read (") == 1); + CHECK(CountLog("(the model choice record cannot be read; the launcher's model item") == 1); + CloseHandle(hold); + CHECK(kept == "M" && ReadRec(rec).model == 'M'); #endif + // (13) a corrupt record (seq overflow): said once, treated as no choice (the launcher's item), not written over by a + // create; the next real choice replaces it + WriteRec(rec, "model=L\nseq=18446744073709551616\nsource=launcher\n"); + CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M')) == name(b)); + CHECK(CountLog("is corrupt (seq is not a number") == 1); + wgchoice::ReadResult rr; + ReadRec(rec, &rr); + CHECK(rr == wgchoice::ReadResult::Corrupt); + CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name('M')); + r = ReadRec(rec); + CHECK(rc == WG_HOST_SELECTED_RECORDED && r.model == 'M' && r.seq == 1 && r.source == wgchoice::Source::Ffx); + // (14) the end of the sequence numbers: the selection is refused loudly, the record unchanged + WriteRec(rec, std::string("model=") + b + "\nseq=18446744073709551615\nsource=plugin\n"); + CHECK(HostedCreate(iniM, 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name(b)); + r = ReadRec(rec); + CHECK(rc == WG_HOST_SELECTED_REFUSED && r.model == b && r.seq == UINT64_MAX); + CHECK(CountLog("ERROR: the player selected Model M in OptiScaler's upscaler list: the record's sequence number is at its end") == 1); } else { - // Model M only: the record still says what runs and the box's first entry is recorded - CHECK(HookedCreate("runtime_options = model=M\n", 'M', idOf('M')) == name('M')); - CHECK(ReadRec(f.record()).model == 'M' && ReadRec(f.record()).seq == 1); + // Model M only: the record is migrated (M, seq 1, launcher) and says what runs + CHECK(HostedCreate("runtime_options = model=M\n", 'M', idOf('M')) == name('M')); + CHECK(ReadRec(rec).model == 'M' && ReadRec(rec).seq == 1 && ReadRec(rec).source == wgchoice::Source::Launcher); } g_choiceRecord.clear(); g_asiPresent = present; diff --git a/clean/fsr/tests/test_model_choice_record.cpp b/clean/fsr/tests/test_model_choice_record.cpp index 4db9c04b..729eb88c 100644 --- a/clean/fsr/tests/test_model_choice_record.cpp +++ b/clean/fsr/tests/test_model_choice_record.cpp @@ -1,9 +1,13 @@ // SPDX-License-Identifier: MIT // Unit tests of the game's model choice record (clean/fsr/src/model_choice_record.h) on REAL files in a fresh folder under -// the system temporary folder: the strict format, seq order, the OptiScaler list rule (ffx), atomic replacement, a stale -// temporary file, corrupt and overflowing records, and a reader running while a writer replaces the record. +// the system temporary folder, and with REAL processes (this program started again as a writer, a reader or a lock +// holder that dies): the strict three-key format, seq order with each source winning in turn, the cross-process lock +// (concurrent writers lose no update, seq never goes back; an abandoned lock is taken over), the upgrade migration, +// corrupt and overflowing records, the end of the sequence numbers, a failed write and its retry, a stale temporary file. #include #include +#include +#include #include #include #include @@ -22,8 +26,8 @@ static int g_failures = 0, g_checks = 0; namespace { -std::string Valid(const char* model = "L", const char* seq = "7", const char* source = "launcher", const char* ffx = "L") { - return std::string("; c\r\n\r\nmodel=") + model + "\r\nseq=" + seq + "\r\nsource=" + source + "\r\nffx=" + ffx + "\r\n"; +std::string Valid(const char* model = "L", const char* seq = "7", const char* source = "launcher") { + return std::string("; c\r\n\r\nmodel=") + model + "\r\nseq=" + seq + "\r\nsource=" + source + "\r\n"; } bool Parses(const std::string& text, Record* r = nullptr) { @@ -34,54 +38,42 @@ bool Parses(const std::string& text, Record* r = nullptr) { void TestStrictFormat() { Record r; - CHECK(Parses(Valid(), &r) && r.model == 'L' && r.seq == 7 && r.source == Source::Launcher && r.ffx == 'L'); - CHECK(Parses("model=M\nseq=1\nsource=ffx\nffx=-\n", &r) && r.model == 'M' && r.source == Source::Ffx && r.ffx == kUnknown); - CHECK(Parses("model=K\nseq=18446744073709551615\nsource=plugin\nffx=K", &r) && r.seq == UINT64_MAX && r.source == Source::Plugin); + CHECK(Parses(Valid(), &r) && r.model == 'L' && r.seq == 7 && r.source == Source::Launcher); + CHECK(Parses("model=M\nseq=1\nsource=ffx\n", &r) && r.model == 'M' && r.source == Source::Ffx); + CHECK(Parses("model=K\nseq=18446744073709551615\nsource=plugin", &r) && r.seq == UINT64_MAX && r.source == Source::Plugin); CHECK(!Parses("")); // no record - CHECK(!Parses("model=L\nseq=7\nsource=launcher\n")); // a key missing + CHECK(!Parses("model=L\nseq=7\n")); // a key missing CHECK(!Parses(Valid() + "model=K\r\n")); // a key twice CHECK(!Parses(Valid() + "extra=1\r\n")); // an unknown key + CHECK(!Parses(Valid() + "ffx=L\r\n")); // the earlier design's fourth key: corrupt CHECK(!Parses(Valid("l")) && !Parses(Valid("Q")) && !Parses(Valid("LL"))); // model: M, K or L exactly CHECK(!Parses(Valid("L", "0")) && !Parses(Valid("L", "-1")) && !Parses(Valid("L", "7x")) && !Parses(Valid("L", ""))); CHECK(!Parses(Valid("L", "18446744073709551616"))); // 2^64: overflow refused CHECK(!Parses(Valid("L", "99999999999999999999"))); // 20 digits, overflow refused CHECK(!Parses(Valid("L", "000000000000000000001"))); // 21 digits refused CHECK(!Parses(Valid("L", "7", "game")) && !Parses(Valid("L", "7", "Launcher"))); - CHECK(!Parses(Valid("L", "7", "launcher", "x")) && !Parses(Valid("L", "7", "launcher", ""))); - CHECK(!Parses("model = L\nseq=7\nsource=launcher\nffx=L\n")); // no spaces around '=' - CHECK(!Parses("model=L\nseq=7\nsource=launcher\nffx=L\ngarbage\n")); // a line that is not key=value - CHECK(Parses(FormatRecord(Record{'K', 42, Source::Plugin, 'M'}), &r) && r.model == 'K' && r.seq == 42 && r.ffx == 'M'); -} - -void TestOrderAndFfxRule() { - Record a, b, c; - CHECK(NextRecord(nullptr, 'L', Source::Launcher, 'L', &a) && a.seq == 1 && a.ffx == 'L'); - CHECK(NextRecord(&a, 'K', Source::Plugin, kUnknown, &b) && b.seq == 2 && b.model == 'K' && b.ffx == 'L'); // keeps ffx - Record max{'M', UINT64_MAX, Source::Launcher, 'M'}; - CHECK(!NextRecord(&max, 'L', Source::Launcher, 'L', &c)); // seq cannot grow: refused, never wraps to 0 - // the list names the entry the record knows: nothing (also after the plugin's choice: the list did not move) - CHECK(FfxObservation(&b, 'L', &c) == FfxStep::None); - CHECK(FfxObservation(&b, kUnknown, &c) == FfxStep::None); // no WrongGPU entry (an AMD version) - // another entry: the player's choice in OptiScaler's list - CHECK(FfxObservation(&b, 'M', &c) == FfxStep::Choice && c.model == 'M' && c.seq == 3 && c.source == Source::Ffx && c.ffx == 'M'); - // the first create without a record: the entry seen counts as a choice - CHECK(FfxObservation(nullptr, 'K', &c) == FfxStep::Choice && c.model == 'K' && c.seq == 1 && c.ffx == 'K'); - // a record that does not know the list's entry: adopted, not a choice (same model, same seq) - Record unk{'L', 5, Source::Plugin, kUnknown}; - CHECK(FfxObservation(&unk, 'M', &c) == FfxStep::Adopt && c.model == 'L' && c.seq == 5 && c.ffx == 'M'); - CHECK(FfxObservation(&max, 'L', &c) == FfxStep::None); // seq at its end: no write + CHECK(!Parses("model = L\nseq=7\nsource=launcher\n")); // no spaces around '=' + CHECK(!Parses("model=L\nseq=7\nsource=launcher\ngarbage\n")); // a line that is not key=value + CHECK(Parses(FormatRecord(Record{'K', 42, Source::Plugin}), &r) && r.model == 'K' && r.seq == 42 && r.source == Source::Plugin); +} + +void TestLockName() { + const std::wstring a = LockName(L"C:\\Games\\X\\wronggpu-setup\\model-choice.ini"); + CHECK(a.rfind(L"Local\\WrongGPU-choice-", 0) == 0 && a.size() == std::wstring(L"Local\\WrongGPU-choice-").size() + 16); + CHECK(LockName(L"c:/games/x/WRONGGPU-SETUP/model-choice.ini") == a); // the same file however it is spelt + CHECK(LockName(L"C:\\Games\\Y\\wronggpu-setup\\model-choice.ini") != a); // another game: another lock } struct Folder { fs::path dir; - Folder() { + explicit Folder(const char* name = "") { dir = fs::temp_directory_path() / ("wg-choice-test-" + std::to_string( #ifdef _WIN32 GetCurrentProcessId() #else 0 #endif - )); + ) + name); std::error_code ec; fs::create_directories(dir / kStateFolder, ec); } @@ -99,99 +91,291 @@ void WriteRaw(const fs::path& p, const std::string& text) { f << text; } -void TestFiles() { - Folder f; +std::string ReadRaw(const fs::path& p) { + std::ifstream f(p, std::ios::binary); + return std::string(std::istreambuf_iterator(f), std::istreambuf_iterator()); +} + +Record Rec(const fs::path& p, ReadResult* rr = nullptr) { Record r; std::string why; + const ReadResult res = ReadRecordFile(p, &r, &why); + if (rr) *rr = res; + return res == ReadResult::Ok ? r : Record{0, 0, Source::Launcher}; +} + +int TmpFiles(const Folder& f) { + int n = 0; + std::error_code ec; + for (auto& e : fs::directory_iterator(f.dir / kStateFolder, ec)) + if (e.path().extension() == ".tmp") ++n; + return n; +} + +void TestChoicesInTurn() { + Folder f; + Record r, after; + std::string why; CHECK(ReadRecordFile(f.record(), &r, &why) == ReadResult::Missing); - // each source winning in turn: launcher L, then the player in OptiScaler's list (K), then the plugin's menu (M), then the - // launcher again (L): the highest seq is always the record - Record cur, next; - CHECK(NextRecord(nullptr, 'L', Source::Launcher, 'L', &next) && WriteRecordFile(f.record(), next, &why)); - CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Ok && cur.model == 'L' && cur.seq == 1 && cur.source == Source::Launcher); - CHECK(FfxObservation(&cur, 'K', &next) == FfxStep::Choice && WriteRecordFile(f.record(), next, &why)); - CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Ok && cur.model == 'K' && cur.seq == 2 && cur.source == Source::Ffx); - CHECK(NextRecord(&cur, 'M', Source::Plugin, kUnknown, &next) && WriteRecordFile(f.record(), next, &why)); - CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Ok && cur.model == 'M' && cur.seq == 3 && cur.ffx == 'K'); - CHECK(FfxObservation(&cur, 'K', &next) == FfxStep::None); // the list still names K: no false choice after the plugin's - // the launcher applies L and sets the list's entry with it: its own index rewrite is never a choice in the game - CHECK(NextRecord(&cur, 'L', Source::Launcher, 'L', &next) && WriteRecordFile(f.record(), next, &why)); - CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Ok && cur.model == 'L' && cur.seq == 4 && cur.ffx == 'L'); - CHECK(FfxObservation(&cur, 'L', &next) == FfxStep::None); + // each source winning in turn: launcher L, the player in OptiScaler's list (K, an event), the plugin's menu (M), the + // launcher again (L), the list re-selecting the SAME entry after a plugin choice (it wins): the highest seq is the record + CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::Written && after.seq == 1); + r = Rec(f.record()); + CHECK(r.model == 'L' && r.seq == 1 && r.source == Source::Launcher); + CHECK(RecordChoice(f.record(), 'K', Source::Ffx, &after, &why) == Outcome::Written); + r = Rec(f.record()); + CHECK(r.model == 'K' && r.seq == 2 && r.source == Source::Ffx); + CHECK(RecordChoice(f.record(), 'M', Source::Plugin, &after, &why) == Outcome::Written); + r = Rec(f.record()); + CHECK(r.model == 'M' && r.seq == 3 && r.source == Source::Plugin); + CHECK(RecordChoice(f.record(), 'K', Source::Ffx, &after, &why) == Outcome::Written); // K again in the list: wins + r = Rec(f.record()); + CHECK(r.model == 'K' && r.seq == 4 && r.source == Source::Ffx); + CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::Written); + r = Rec(f.record()); + CHECK(r.model == 'L' && r.seq == 5 && r.source == Source::Launcher); + CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::Written); // the same choice again: seq grows + CHECK(Rec(f.record()).seq == 6); // a stale temporary file a crash left next to the record (and garbage in it): never read, writes still work const fs::path stale = f.record().string() + ".999.0.0.tmp"; WriteRaw(stale, "model=K\nseq=999999"); - CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Ok && cur.seq == 4); - CHECK(NextRecord(&cur, 'K', Source::Plugin, kUnknown, &next) && WriteRecordFile(f.record(), next, &why)); - CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Ok && cur.seq == 5 && cur.model == 'K'); - // only a temporary file, no record (a crash before the move): no record + CHECK(Rec(f.record()).seq == 6); + CHECK(RecordChoice(f.record(), 'K', Source::Plugin, &after, &why) == Outcome::Written && Rec(f.record()).seq == 7); std::error_code ec; + fs::remove(stale, ec); + // only a temporary file, no record (a crash before the move): no record fs::remove(f.record(), ec); - CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Missing); - // corrupt and overflowing records: Corrupt, never a partial choice - WriteRaw(f.record(), Valid("L", "18446744073709551616")); - CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Corrupt && why.find("seq") != std::string::npos); - WriteRaw(f.record(), "model=L\nseq=3\n"); - CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Corrupt); - WriteRaw(f.record(), std::string(4096, 'x')); - CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Corrupt); - // ... and a write over a corrupt record replaces it whole - CHECK(NextRecord(nullptr, 'M', Source::Ffx, 'M', &next) && WriteRecordFile(f.record(), next, &why)); - CHECK(ReadRecordFile(f.record(), &cur, &why) == ReadResult::Ok && cur.seq == 1 && cur.model == 'M'); + WriteRaw(stale, Valid()); + CHECK(ReadRecordFile(f.record(), &r, &why) == ReadResult::Missing); fs::remove(stale, ec); - // no temporary file is left behind by successful writes - int tmps = 0; - for (auto& e : fs::directory_iterator(f.dir / kStateFolder, ec)) - if (e.path().extension() == ".tmp") ++tmps; - CHECK(tmps == 0); + CHECK(TmpFiles(f) == 0); // no temporary file is left behind by the writes } -// A reader that runs while a writer replaces the record many times sees a whole record every time (or, before the first -// write, none), with seq never going down: never an empty or partial file. -void TestConcurrentReader() { +void TestCorruptAndEnd() { Folder f; - std::atomic done{false}; - std::atomic partial{0}, reads{0}, backwards{0}; - std::thread reader([&] { - uint64_t last = 0; - while (!done.load()) { - Record r; - std::string why; - const ReadResult rr = ReadRecordFile(f.record(), &r, &why); - if (rr == ReadResult::Corrupt) ++partial; - if (rr == ReadResult::Ok) { - ++reads; - if (r.seq < last) ++backwards; - last = r.seq; - } - } - }); - Record cur, next; - int failedWrites = 0; - for (int i = 0; i < 400; ++i) { - std::string why; - NextRecord(i ? &cur : nullptr, "MKL"[i % 3], Source::Launcher, "MKL"[i % 3], &next); - if (WriteRecordFile(f.record(), next, &why)) cur = next; - else ++failedWrites; + Record r, after; + std::string why; + // corrupt and overflowing records: Corrupt, never a partial choice; the next choice replaces them whole (seq 1) + for (const std::string& bad : {Valid("L", "18446744073709551616"), std::string("model=L\nseq=3\n"), std::string(4096, 'x'), + Valid() + "ffx=L\r\n"}) { + WriteRaw(f.record(), bad); + CHECK(ReadRecordFile(f.record(), &r, &why) == ReadResult::Corrupt); + why.clear(); + CHECK(RecordChoice(f.record(), 'M', Source::Ffx, &after, &why) == Outcome::Written && after.seq == 1); + CHECK(why.find("corrupt") != std::string::npos); + r = Rec(f.record()); + CHECK(r.model == 'M' && r.seq == 1 && r.source == Source::Ffx); } - done.store(true); - reader.join(); - CHECK(partial.load() == 0); - CHECK(backwards.load() == 0); - CHECK(failedWrites == 0); - CHECK(reads.load() > 0); + // the end of the sequence numbers: refused loudly (SeqExhausted), the record unchanged, never wrapped to 0 + WriteRaw(f.record(), Valid("K", "18446744073709551615", "plugin")); + const std::string before = ReadRaw(f.record()); + CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::SeqExhausted); + CHECK(ReadRaw(f.record()) == before); + CHECK(std::string(OutcomeWords(Outcome::SeqExhausted)).find("refused") != std::string::npos); + CHECK(TmpFiles(f) == 0); +} + +void TestMigration() { + Folder f; Record r; + bool migrated = false; + std::string why; + // an install from before 0.6.5 (no record): wronggpu.ini's model item, seq 1, source=launcher; the stamp files of the + // earlier designs next to it are ignored + WriteRaw(f.dir / kStateFolder / "wronggpu-ffx-choice.ini", "model=K\nchosen=99999999999\n"); + CHECK(LoadOrMigrateRecord(f.record(), 'L', &r, &migrated, &why) == ReadResult::Ok && migrated); + CHECK(r.model == 'L' && r.seq == 1 && r.source == Source::Launcher); + r = Rec(f.record()); + CHECK(r.model == 'L' && r.seq == 1 && r.source == Source::Launcher); + // a record now: returned as it is, nothing written + const std::string text = ReadRaw(f.record()); + CHECK(LoadOrMigrateRecord(f.record(), 'K', &r, &migrated, &why) == ReadResult::Ok && !migrated && r.model == 'L'); + CHECK(ReadRaw(f.record()) == text); + // no model item: Model M + std::error_code ec; + fs::remove(f.record(), ec); + CHECK(LoadOrMigrateRecord(f.record(), 0, &r, &migrated, &why) == ReadResult::Ok && migrated && r.model == 'M' && r.seq == 1); + // a corrupt record is not migrated over (it stays corrupt until a real choice replaces it) + WriteRaw(f.record(), "model=L\n"); + CHECK(LoadOrMigrateRecord(f.record(), 'K', &r, &migrated, &why) == ReadResult::Corrupt && !migrated); + CHECK(ReadRaw(f.record()) == "model=L\n"); + fs::remove(f.dir / kStateFolder / "wronggpu-ffx-choice.ini", ec); +} + +#ifdef _WIN32 +// A write that fails (the record held open without delete sharing, so it cannot be replaced) and its retry; a choice +// superseded while it waited; a lock another thread holds (NoLock); an unreadable record never written over. +void TestFailureAndRetry() { + Folder f; + Record after; + std::string why; + CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::Written); // seq 1 + HANDLE h = CreateFileW(f.record().c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + CHECK(h != INVALID_HANDLE_VALUE); + Pending p; + CHECK(RecordChoice(f.record(), 'K', Source::Plugin, &after, &why, &p) == Outcome::WriteFailed); + CHECK(p.active() && p.model == 'K' && p.baseKnown && p.baseSeq == 1 && !why.empty()); + CHECK(RetryPending(f.record(), &p, &after, &why) == Outcome::WriteFailed && p.active()); // still held: still pending + CloseHandle(h); + CHECK(Rec(f.record()).seq == 1 && Rec(f.record()).model == 'L'); // nothing changed while it failed + CHECK(RetryPending(f.record(), &p, &after, &why) == Outcome::Written && !p.active()); + Record r = Rec(f.record()); + CHECK(r.model == 'K' && r.seq == 2 && r.source == Source::Plugin); + // a pending choice superseded meanwhile (the launcher wrote after it): dropped, the newer choice stays + h = CreateFileW(f.record().c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + CHECK(RecordChoice(f.record(), 'M', Source::Ffx, &after, &why, &p) == Outcome::WriteFailed && p.baseSeq == 2); + CloseHandle(h); + CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::Written && after.seq == 3); + CHECK(RetryPending(f.record(), &p, &after, &why) == Outcome::Superseded && !p.active()); + r = Rec(f.record()); + CHECK(r.model == 'L' && r.seq == 3 && r.source == Source::Launcher); + // the lock held by another thread: NoLock (base unknown), nothing written; once free the retry writes + std::atomic held{false}, release{false}; + std::thread holder([&] { + Lock l(f.record()); + held.store(l.ok()); + while (!release.load()) Sleep(1); + }); + while (!held.load()) Sleep(1); + CHECK(RecordChoice(f.record(), 'K', Source::Ffx, &after, &why, &p, 100) == Outcome::NoLock && p.active() && !p.baseKnown); + CHECK(Rec(f.record()).seq == 3); + release.store(true); + holder.join(); + CHECK(RetryPending(f.record(), &p, &after, &why) == Outcome::Written && Rec(f.record()).seq == 4 && Rec(f.record()).model == 'K'); + // a record held open without any sharing: Unreadable, never written over + h = CreateFileW(f.record().c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + CHECK(RecordChoice(f.record(), 'M', Source::Plugin, &after, &why, &p) == Outcome::Unreadable && p.active() && !p.baseKnown); + CloseHandle(h); + CHECK(Rec(f.record()).seq == 4 && Rec(f.record()).model == 'K'); + CHECK(TmpFiles(f) == 0); +} + +std::wstring Self() { + wchar_t buf[MAX_PATH]; + GetModuleFileNameW(nullptr, buf, MAX_PATH); + return buf; +} + +HANDLE Spawn(const std::wstring& args) { + std::wstring cmd = L"\"" + Self() + L"\" " + args; + STARTUPINFOW si{}; + si.cb = sizeof si; + PROCESS_INFORMATION pi{}; + if (!CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi)) return nullptr; + CloseHandle(pi.hThread); + return pi.hProcess; +} + +DWORD Wait(HANDLE p) { + WaitForSingleObject(p, 120000); + DWORD code = 999; + GetExitCodeProcess(p, &code); + CloseHandle(p); + return code; +} + +// Several REAL processes writing the record at once (the launcher, the front end and the plugin are separate programs or +// modules that all use RecordChoice), and one reading it under the lock: no update is lost (the final seq is the number +// of writes), each writer sees its own seq grow, the reader never sees a partial record or seq going back. +void TestConcurrentProcesses() { + Folder f("-procs"); + const int kWriters = 4, kWrites = 150; + const wchar_t* models = L"MKLM"; + const wchar_t* sources[] = {L"launcher", L"ffx", L"plugin", L"plugin"}; + HANDLE reader = Spawn(L"reader \"" + f.record().wstring() + L"\" " + std::to_wstring(kWriters * kWrites)); + std::vector writers; + for (int i = 0; i < kWriters; ++i) + writers.push_back(Spawn(L"writer \"" + f.record().wstring() + L"\" " + std::wstring(1, models[i]) + L" " + sources[i] + L" " + + std::to_wstring(kWrites))); + int failed = 0; + for (HANDLE w : writers) { + CHECK(w != nullptr); + if (w && Wait(w) != 0) ++failed; + } + CHECK(failed == 0); + CHECK(reader != nullptr && Wait(reader) == 0); + Record r = Rec(f.record()); + CHECK(r.seq == uint64_t(kWriters * kWrites)); // no lost update + std::printf("concurrent processes: %d writers x %d writes, final seq %llu\n", kWriters, kWrites, static_cast(r.seq)); + CHECK(TmpFiles(f) == 0); +} + +// A process that dies while it holds the lock: the next one takes it over (WAIT_ABANDONED) and the record is whole. +void TestAbandonedLock() { + Folder f("-abandon"); + Record after; std::string why; - CHECK(ReadRecordFile(f.record(), &r, &why) == ReadResult::Ok && r.seq == 400); + CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::Written); + HANDLE p = Spawn(L"lock-and-die \"" + f.record().wstring() + L"\""); + CHECK(p != nullptr && Wait(p) == 97); + CHECK(RecordChoice(f.record(), 'K', Source::Ffx, &after, &why, nullptr, 2000) == Outcome::Written && after.seq == 2); + CHECK(Rec(f.record()).model == 'K'); } +int ChildWriter(const fs::path& record, char model, const std::string& source, int count) { + const Source s = source == "launcher" ? Source::Launcher : source == "ffx" ? Source::Ffx : Source::Plugin; + uint64_t last = 0; + int bad = 0; + for (int i = 0; i < count; ++i) { + Record after; + std::string why; + const Outcome o = RecordChoice(record, model, s, &after, &why, nullptr, 20000); + if (o != Outcome::Written) { + std::printf("writer %c: %s (%s)\n", model, OutcomeWords(o), why.c_str()); + ++bad; + continue; + } + if (after.seq <= last) ++bad; // seq went back or stood still for this writer + last = after.seq; + } + return bad; +} + +int ChildReader(const fs::path& record, uint64_t until) { + uint64_t last = 0; + int bad = 0; + const ULONGLONG start = GetTickCount64(); + while (last < until && GetTickCount64() - start < 100000) { + Lock lock(record, 20000); + if (!lock.ok()) return 100; + Record r; + std::string why; + const ReadResult rr = ReadRecordFile(record, &r, &why); + if (rr == ReadResult::Corrupt || rr == ReadResult::Unreadable) ++bad; + if (rr == ReadResult::Ok) { + if (r.seq < last) ++bad; + last = r.seq; + } + } + return bad + (last < until ? 1000 : 0); +} +#endif + } // namespace -int main() { +int main(int argc, char** argv) { +#ifdef _WIN32 + if (argc >= 6 && std::string(argv[1]) == "writer") return ChildWriter(argv[2], argv[3][0], argv[4], std::atoi(argv[5])); + if (argc >= 4 && std::string(argv[1]) == "reader") return ChildReader(argv[2], std::strtoull(argv[3], nullptr, 10)); + if (argc >= 3 && std::string(argv[1]) == "lock-and-die") { + Lock lock(argv[2]); + if (!lock.ok()) return 1; + TerminateProcess(GetCurrentProcess(), 97); // dies holding the lock + } +#else + (void)argc; + (void)argv; +#endif TestStrictFormat(); - TestOrderAndFfxRule(); - TestFiles(); - TestConcurrentReader(); + TestLockName(); + TestChoicesInTurn(); + TestCorruptAndEnd(); + TestMigration(); +#ifdef _WIN32 + TestFailureAndRetry(); + TestConcurrentProcesses(); + TestAbandonedLock(); +#endif std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } diff --git a/clean/installer/src/wg_core/launcher.cpp b/clean/installer/src/wg_core/launcher.cpp index 9acff9d0..d945fd6e 100644 --- a/clean/installer/src/wg_core/launcher.cpp +++ b/clean/installer/src/wg_core/launcher.cpp @@ -991,25 +991,24 @@ static bool OptInKey(const wstring& exe, const IniKeyChange& c) { } // The launcher's entry in the game's model choice record (wronggpu-setup\model-choice.ini; model_choice_record.h): read, -// the next seq, written atomically. A record that cannot be read is not written over (said in the notes). -void WriteLauncherModelChoice(Context& ctx, const wstring& dir, char model, char ffx, std::vector& notes, - std::vector* warnings) { +// the next seq, written atomically; the caller holds the record's lock. A record that cannot be read is not written over; +// every failure is said in the notes and warnings. +bool WriteLauncherModelChoice(Context& ctx, const wstring& dir, char model, std::vector& notes, std::vector* warnings) { const std::filesystem::path path = Join(StateDir(dir), wgchoice::kRecordFile); - wgchoice::Record cur, next; + wgchoice::Record after; std::string why; - const wgchoice::ReadResult rr = wgchoice::ReadRecordFile(path, &cur, &why); - auto warn = [&](const wstring& w) { + const wgchoice::Outcome o = wgchoice::RecordChoiceUnlocked(path, model, wgchoice::Source::Launcher, &after, &why); + if (o != wgchoice::Outcome::Written) { + const wstring w = L"The model choice record was not changed: " + FromUtf8(wgchoice::OutcomeWords(o)) + + (why.empty() ? wstring() : L" (" + FromUtf8(why) + L")") + L". The game may keep running its earlier model choice."; LogLine(ctx, w); notes.push_back(w); if (warnings) warnings->push_back(w); - }; - if (rr == wgchoice::ReadResult::Unreadable) return warn(L"The model choice record could not be read (" + FromUtf8(why) + L"); it was not changed."); - if (rr == wgchoice::ReadResult::Corrupt) LogLine(ctx, L"model-choice.ini was corrupt (" + FromUtf8(why) + L"); written anew"); - if (!wgchoice::NextRecord(rr == wgchoice::ReadResult::Ok ? &cur : nullptr, model, wgchoice::Source::Launcher, ffx, &next)) - return warn(L"The model choice record could not take another choice (its sequence number is at its end)."); - if (!wgchoice::WriteRecordFile(path, next, &why)) return warn(L"The model choice record could not be written (" + FromUtf8(why) + L")."); - LogLine(ctx, wstring(L"model choice record: Model ") + wchar_t(model) + L" (seq " + std::to_wstring(next.seq) + L", source=launcher, ffx=" + - wchar_t(next.ffx) + L")"); + return false; + } + if (!why.empty()) LogLine(ctx, L"model-choice.ini: " + FromUtf8(why)); + LogLine(ctx, wstring(L"model choice record: Model ") + wchar_t(model) + L" (seq " + std::to_wstring(after.seq) + L", source=launcher)"); + return true; } Profile GameProfile(const wstring& dir) { @@ -1043,20 +1042,17 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto if (warnings) warnings->push_back(w); } } - string winiBefore, winiAfter, optiAfter; // the model choice record (below) - bool haveOpti = false; + string winiBefore, winiAfter; // the model choice record (below) + char forcedEntry = 0; // the model whose entry OptiScaler.ini's UpscalerIndex is set to (after the record) auto renderFile = [&](const wchar_t* name, bool opti) { const wstring path = Join(dir, name); string in; const bool had = ReadAll(path, in); if (opti && !had) return; // OptiScaler.ini: only an existing file (ours) is changed string out; wstring why; - auto keep = [&] { - if (opti) { optiAfter = out; haveOpti = true; } - else { winiBefore = in; winiAfter = out; } - }; if (opti) { RenderOptiIni(q, in, out, ¬es); + if (forcedEntry) out = SetOptiModelEntry(out, forcedEntry); bool wrote = false; out = RenderGameOptiKeys(p, m.exe, out, m.inikeys, notes, &wrote); if (wrote) @@ -1065,7 +1061,7 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto recordChanged = recordChanged || out != in; } else if (!RenderWronggpuIni(q, in, out, &why)) Fail(L"Settings not applied: " + why, EXIT_USAGE); - keep(); + else { winiBefore = in; winiAfter = out; } if (out == in && (had || out.empty())) return; // unchanged, or nothing to write into a missing file WriteFileAtomic(path, out.data(), out.size()); const wstring h = Sha256Bytes(out.data(), out.size()); @@ -1073,16 +1069,35 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto notes.push_back(wstring(name) + L" written"); }; renderFile(L"wronggpu.ini", false); - if (HostedRecord(m)) renderFile(L"OptiScaler.ini", true); // The model choice record (clean/fsr/src/model_choice_record.h): the launcher's model choice, with the next seq, when the - // player explicitly applied a model (also the same one again) or the model the files run changed. ffx: the WrongGPU entry - // OptiScaler.ini now names (set with the model), so the front end never takes that entry for a choice in the game. (A - // model the files cannot run yet, written as Model M above, is recorded as what runs: Model M.) + // player explicitly applied a model (also the same one again) or the model the files run changed. Under the record's + // cross-process lock (the game's front end and menu plugin take it too): the record first, then OptiScaler.ini's + // UpscalerIndex set to that model's entry whatever it was (display only: the front end never takes the index for a + // choice, so a crash between the two leaves nothing wrong). A model the files cannot run yet, written as Model M + // above, is recorded as what runs: Model M. const char modelBefore = ModelOfWronggpuIni(winiBefore), modelAfter = ModelOfWronggpuIni(winiAfter); - if (modelChosen || modelBefore != modelAfter) { - const char model = modelAfter ? modelAfter : 'M'; - WriteLauncherModelChoice(ctx, dir, model, haveOpti ? ModelEntryOfOptiIni(optiAfter) : wgchoice::kUnknown, notes, warnings); - if (HostedRecord(m)) { // the menu plugin's AMD entry chosen earlier: the launcher's model choice is newer + const bool modelChoice = modelChosen || modelBefore != modelAfter; + const char model = modelAfter ? modelAfter : 'M'; + { + std::unique_ptr lock; + if (modelChoice) { + lock = std::make_unique(Join(StateDir(dir), wgchoice::kRecordFile)); + if (!lock->ok()) { + const wstring w = L"The model choice record was not changed: " + FromUtf8(wgchoice::OutcomeWords(wgchoice::Outcome::NoLock)) + + L" (the game holds it). Apply the model again."; + LogLine(ctx, w); + notes.push_back(w); + if (warnings) warnings->push_back(w); + } else if (WriteLauncherModelChoice(ctx, dir, model, notes, warnings)) { + forcedEntry = model; +#ifdef WRONGGPU_TESTING + // tests: the apply ends here, after the record and before OptiScaler.ini (a crash between the two) + if (EnvVar(L"WRONGGPU_TEST_STOP_AFTER_CHOICE_RECORD") == L"1") TerminateProcess(GetCurrentProcess(), 97); +#endif + } + } + if (HostedRecord(m)) renderFile(L"OptiScaler.ini", true); + if (forcedEntry && HostedRecord(m)) { // the menu plugin's AMD entry chosen earlier: the launcher's model choice is newer const wstring asi = Join(dir, L"wronggpu-asi.ini"); string text; if (ReadAll(asi, text) && wgasi::ParseSelection(text) == wgasi::kModelAmd) { diff --git a/clean/installer/src/wg_core/launcher.h b/clean/installer/src/wg_core/launcher.h index 1bb167c2..c6b066ee 100644 --- a/clean/installer/src/wg_core/launcher.h +++ b/clean/installer/src/wg_core/launcher.h @@ -215,10 +215,9 @@ bool NeedsElevation(const wstring& dir); // gets the launcher's choice with the next seq even when the model is the same (clean/fsr/src/model_choice_record.h). void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vector& notes, std::vector* warnings = nullptr, bool modelChosen = false); -// The launcher's model choice into the game's model choice record (wronggpu-setup\model-choice.ini), with the next seq; -// ffx: the WrongGPU entry OptiScaler.ini names now ('-' when not known). -void WriteLauncherModelChoice(Context& ctx, const wstring& dir, char model, char ffx, std::vector& notes, - std::vector* warnings); +// The launcher's model choice into the game's model choice record (wronggpu-setup\model-choice.ini), with the next seq, +// source=launcher. Call it holding the record's lock (wgchoice::Lock). false: not written (said in the notes and warnings). +bool WriteLauncherModelChoice(Context& ctx, const wstring& dir, char model, std::vector& notes, std::vector* warnings); Profile GameProfile(const wstring& dir); // profile.ini, else the profile its wronggpu.ini implies // The OptiScaler tab: reset / keep / edits of OpRequest written into the installed OptiScaler.ini with the inikey // journal in the record. Nothing to do: no change. diff --git a/clean/installer/src/wg_core/profile.cpp b/clean/installer/src/wg_core/profile.cpp index b35d296f..a688f60b 100644 --- a/clean/installer/src/wg_core/profile.cpp +++ b/clean/installer/src/wg_core/profile.cpp @@ -351,17 +351,27 @@ char ModelOfWronggpuIni(const string& text) { return c == 'M' || c == 'K' || c == 'L' ? c : 0; } -char ModelEntryOfOptiIni(const string& text) { - string cur; - if (!IniHasKey(text, "WrongGPU", "UpscalerIndex", &cur) && !IniHasKey(text, "FSR", "UpscalerIndex", &cur)) return '-'; - cur = TrimA(cur); +string SetOptiModelEntry(const string& text, char model) { + const char* index = "0"; #if WRONGGPU_MODEL_L - if (cur == kModelLEntryIndex) return 'L'; + if (model == 'L') index = kModelLEntryIndex; #endif #if WRONGGPU_MODEL_K || WRONGGPU_PRESET_K - if (cur == kModelKEntryIndex) return 'K'; + if (model == 'K') index = kModelKEntryIndex; #endif - return cur == "0" ? 'M' : '-'; + // OptiScaler 10's custom upscaler slot: [WrongGPU] (its key, else its section); else [FSR] (the FFX route) + bool slot = IniHasKey(text, "WrongGPU", "UpscalerIndex"); + if (!slot && !IniHasKey(text, "FSR", "UpscalerIndex")) { + size_t at = 0; + while (!slot && at < text.size()) { + size_t end = text.find('\n', at); + if (end == string::npos) end = text.size(); + const string line = LowerA(TrimA(text.substr(at, end - at))); + slot = line == "[wronggpu]"; + at = end + 1; + } + } + return IniSet(text, slot ? "WrongGPU" : "FSR", "UpscalerIndex", index); } bool RenderOptiIni(const Profile& p, const string& in, string& out, std::vector* notes) { diff --git a/clean/installer/src/wg_core/profile.h b/clean/installer/src/wg_core/profile.h index 515f5975..d0597934 100644 --- a/clean/installer/src/wg_core/profile.h +++ b/clean/installer/src/wg_core/profile.h @@ -79,9 +79,12 @@ bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* bool RenderOptiIni(const Profile& p, const string& in, string& out, std::vector* notes = nullptr); // The model a wronggpu.ini text runs: its last runtime_options model item, 'M', 'K' or 'L'; 0 without one. char ModelOfWronggpuIni(const string& text); -// The WrongGPU model entry an OptiScaler.ini text's UpscalerIndex names ([WrongGPU] of OptiScaler 10's slot, else [FSR]): -// 'M' (0), 'K' (kModelKEntryIndex, a build with Model K), 'L' (kModelLEntryIndex, a build with the L choice); '-' otherwise. -char ModelEntryOfOptiIni(const string& text); +// The OptiScaler.ini text with its UpscalerIndex set to `model`'s entry of WrongGPU's list: 0 Model M, kModelKEntryIndex +// (a build with Model K or Preset K), kModelLEntryIndex (a build with the L choice); a model this build cannot choose: 0. +// [WrongGPU] of OptiScaler 10's custom slot when the file has that key or section, else [FSR]; whatever value was there +// (AMD's version, another one, none: the key is created). The launcher's model choice sets it after the record +// (launcher.cpp ApplyProfile); it is for display only, the front end never takes it for a choice. +string SetOptiModelEntry(const string& text, char model); // The profile a 0.5.x install implies: the effective values of its wronggpu.ini and OptiScaler.ini (defaults and the // stale defaults of earlier versions dropped; upscaler=standin counts as on). Only keys of the settings schema // (kSettings) are taken: developer and test keys (runtime_options items such as timing_log, capture_dir, model_dir, diff --git a/clean/installer/tests/model_choice_k_tests.cpp b/clean/installer/tests/model_choice_k_tests.cpp index 53445ff1..f3a9f084 100644 --- a/clean/installer/tests/model_choice_k_tests.cpp +++ b/clean/installer/tests/model_choice_k_tests.cpp @@ -92,9 +92,14 @@ int main() { require(EffectiveSettings("[fsr]\r\nruntime_options = model=K;model=M\r\n", "")["model"] == "m", "the file's model: the last model item counts"); // ---- the model choice record's inputs (launcher.cpp ApplyProfile) require(ModelOfWronggpuIni(toK) == 'K', "ModelOfWronggpuIni: model=K"); - require(ModelEntryOfOptiIni("[WrongGPU]\r\nUpscalerIndex=" + K + "\r\n") == 'K' && - ModelEntryOfOptiIni("[FSR]\r\nUpscalerIndex=" + L + "\r\n") == (withL ? 'L' : '-'), - "ModelEntryOfOptiIni: K's entry (1); L's entry (2) only with the L choice"); + { + string v; + const string toK = SetOptiModelEntry("[WrongGPU]\r\nUpscalerIndex=5\r\n", 'K'); + require(IniHasKey(toK, "WrongGPU", "UpscalerIndex", &v) && v == K, "SetOptiModelEntry: AMD's value to K's entry (1)"); + const string toL = SetOptiModelEntry("[FSR]\r\nUpscalerIndex=0\r\n", 'L'); + require(IniHasKey(toL, "FSR", "UpscalerIndex", &v) && v == (withL ? L : string("0")), + "SetOptiModelEntry: L's entry (2) only with the L choice (else Model M's, 0)"); + } require(EffectiveSettings(withLItem, "")["model"] == (withL ? "l" : "m"), "the file's model: L only with the Model L choice"); // the profile a game's files imply (no profile.ini): K when the files say K (an install that started on Preset K) require(ImportProfile(toK, "").get("model") == "k" && ImportProfile(fresh, "").get("model") == "m", "the imported profile: model=k from model=K"); diff --git a/clean/installer/tests/model_choice_tests.cpp b/clean/installer/tests/model_choice_tests.cpp index ca1be3ca..bca5b3f0 100644 --- a/clean/installer/tests/model_choice_tests.cpp +++ b/clean/installer/tests/model_choice_tests.cpp @@ -70,14 +70,28 @@ int main() { require(EffectiveSettings(toL, "")["model"] == "l" && EffectiveSettings(fresh, "")["model"] == "m" && EffectiveSettings(withK, "")["model"] == "m", "the file's model: L from its last model item, M otherwise"); require(EffectiveSettings("[fsr]\r\nruntime_options = model=L;model=M\r\n", "")["model"] == "m", "the file's model: the last model item counts"); - // ---- the model choice record's inputs (launcher.cpp ApplyProfile: the model the files run, the entry OptiScaler names) + // ---- the model choice record's input (launcher.cpp ApplyProfile: the model the files run) require(ModelOfWronggpuIni(toL) == 'L' && ModelOfWronggpuIni(fresh) == 'M' && ModelOfWronggpuIni("[fsr]\r\nupscaler = network\r\n") == 0 && ModelOfWronggpuIni("[fsr]\r\nruntime_options = model=L;model=m\r\n") == 'M' && ModelOfWronggpuIni("[fsr]\r\nruntime_options = model=Q\r\n") == 0, "ModelOfWronggpuIni: the last model item, M / K / L, else none"); - require(ModelEntryOfOptiIni("[WrongGPU]\r\nUpscalerIndex=" + string(kModelLEntryIndex) + "\r\n") == 'L' && - ModelEntryOfOptiIni("[FSR]\r\nUpscalerIndex=0\r\n") == 'M' && ModelEntryOfOptiIni("[FSR]\r\nUpscalerIndex=auto\r\n") == '-' && - ModelEntryOfOptiIni("[Menu]\r\nShowFps=auto\r\n") == '-', - "ModelEntryOfOptiIni: the WrongGPU entry UpscalerIndex names (L's index, 0 = M), '-' otherwise"); + // ---- the launcher's model choice sets OptiScaler's entry ALWAYS (after the record; display only): from AMD's or any + // other value, and the key created when it is missing; [WrongGPU] of OptiScaler 10's slot, else [FSR] + { + string v; + const string amdSlot = "[WrongGPU]\r\nUpscalerIndex=4\r\n[FSR]\r\nUpscalerIndex=3\r\n"; + const string toLSlot = SetOptiModelEntry(amdSlot, 'L'); + require(IniHasKey(toLSlot, "WrongGPU", "UpscalerIndex", &v) && v == kModelLEntryIndex && IniHasKey(toLSlot, "FSR", "UpscalerIndex", &v) && v == "3", + "SetOptiModelEntry: the slot's index from AMD's value to L's entry; [FSR] (AMD's own) untouched"); + const string toM = SetOptiModelEntry("[FSR]\r\nUpscalerIndex=auto\r\n", 'M'); + require(IniHasKey(toM, "FSR", "UpscalerIndex", &v) && v == "0", "SetOptiModelEntry: another value to Model M's entry (0)"); + const string created = SetOptiModelEntry("[Menu]\r\nShowFps=auto\r\n", 'L'); + require(IniHasKey(created, "FSR", "UpscalerIndex", &v) && v == kModelLEntryIndex && IniHasKey(created, "Menu", "ShowFps"), + "SetOptiModelEntry: no key: created under [FSR], the rest kept"); + const string createdSlot = SetOptiModelEntry("[WrongGPU]\r\nPath=custom\r\n[Menu]\r\nShowFps=auto\r\n", 'M'); + require(IniHasKey(createdSlot, "WrongGPU", "UpscalerIndex", &v) && v == "0" && !IniHasKey(createdSlot, "FSR", "UpscalerIndex"), + "SetOptiModelEntry: a [WrongGPU] section without the key: created there"); + require(SetOptiModelEntry(toLSlot, 'L') == toLSlot, "SetOptiModelEntry: the same entry again changes nothing"); + } // ---- OptiScaler.ini: the entry OptiScaler starts with ----------------------------------------------------------- const string L = kModelLEntryIndex; diff --git a/clean/installer/tests/run_model_k_tests.py b/clean/installer/tests/run_model_k_tests.py index 2446de0c..a74dea97 100644 --- a/clean/installer/tests/run_model_k_tests.py +++ b/clean/installer/tests/run_model_k_tests.py @@ -76,8 +76,8 @@ def test_choice(t): t.check("...profile.ini says model=k", b"model=k\r\n" in profile_text(b)) k_w, k_o = read(wini), read(oini) r1 = choice_record(b) - t.check("...the model choice record: model=K, source=launcher, ffx=K (the entry it set)", - r1.get("model") == "K" and r1.get("source") == "launcher" and r1.get("ffx") == "K", r1) + t.check("...the model choice record: exactly model=K, seq, source=launcher", + r1.get("model") == "K" and r1.get("source") == "launcher" and sorted(r1) == ["model", "seq", "source"], r1) rc = t.run("set", exe, "model=K") r2 = choice_record(b) t.check("set model=K again: wronggpu.ini and OptiScaler.ini unchanged; the record's seq grows (the newest choice)", diff --git a/clean/installer/tests/run_model_l_tests.py b/clean/installer/tests/run_model_l_tests.py index 5d295f20..18975383 100644 --- a/clean/installer/tests/run_model_l_tests.py +++ b/clean/installer/tests/run_model_l_tests.py @@ -215,6 +215,23 @@ def upscaler_index(text): return found.get("wronggpu", found.get("fsr")) +def set_upscaler_index(text, value): + """OptiScaler.ini text with the UpscalerIndex WrongGPU manages ([WrongGPU] when there, else [FSR]) set to `value` (None: the + line removed): a player's change in the game. Other lines, and every line's own ending, stay.""" + lines = text.splitlines(keepends=True) + target = "wronggpu" if any(s.strip().lower() == "[wronggpu]" for s in lines) else "fsr" + out, sec = [], None + for line in lines: + if line.strip().startswith("["): + sec = line.strip().strip("[]").lower() + if sec == target and line.strip().lower().startswith("upscalerindex") and "=" in line: + if value is None: + continue + line = "UpscalerIndex=" + value + line[len(line.rstrip("\r\n")):] + out.append(line) + return "".join(out) + + def recorded_hash(b, name): """The hash the install record holds for a recorded file (its copy entry: action existed orig inst rel).""" for line in read(os.path.join(b, "wronggpu-setup", "install.record")).decode("utf-8", "replace").replace("\r", "").split("\n"): @@ -274,8 +291,8 @@ def test_choice(t): (recorded_hash(b, "wronggpu.ini"), recorded_hash(b, "OptiScaler.ini"))) t.check("...profile.ini says model=l", b"model=l\r\n" in read(os.path.join(b, "wronggpu-setup", "profile.ini"))) r1 = choice_record(b) - t.check("...the model choice record: model=L, source=launcher, ffx=L (the entry it set), a seq", r1.get("model") == "L" and - r1.get("source") == "launcher" and r1.get("ffx") == "L" and r1.get("seq", "").isdigit(), r1) + t.check("...the model choice record: exactly model=L, seq, source=launcher", r1.get("model") == "L" and + r1.get("source") == "launcher" and r1.get("seq", "").isdigit() and sorted(r1) == ["model", "seq", "source"], r1) rc = t.run("set", exe, "model=L") r2 = choice_record(b) t.check("set model=L again: the record's seq grows (the newest choice); wronggpu.ini and OptiScaler.ini unchanged", @@ -285,8 +302,42 @@ def test_choice(t): rc == 0 and read(wini) == m_w and read(oini) == m_o, (rc, read(wini)[-200:], read(oini)[-200:])) t.check("...profile.ini has no model line again", b"model=" not in read(os.path.join(b, "wronggpu-setup", "profile.ini"))) r3 = choice_record(b) - t.check("...the record: model=M, source=launcher, ffx=M, the next seq", r3.get("model") == "M" and r3.get("ffx") == "M" and + t.check("...the record: model=M, source=launcher, the next seq", r3.get("model") == "M" and r3.get("source") == "launcher" and int(r3.get("seq", "0")) == int(r2.get("seq", "0")) + 1, r3) + # the launcher's model choice ALWAYS sets OptiScaler's entry, after the record: from AMD's value (5), and the key created + # when it is missing + write(oini, set_upscaler_index(read(oini).decode("utf-8", "replace"), "5").encode("utf-8")) + rc = t.run("set", exe, "model=M") + r4 = choice_record(b) + t.check("set model=M over AMD's entry (5): OptiScaler's entry is Model M's again (0); the record's seq grows", + rc == 0 and upscaler_index(read(oini).decode("utf-8", "replace")) == "0" and r4.get("model") == "M" and + int(r4.get("seq", "0")) == int(r3.get("seq", "0")) + 1, (rc, r4, read(oini)[-300:])) + write(oini, set_upscaler_index(read(oini).decode("utf-8", "replace"), None).encode("utf-8")) + rc = t.run("set", exe, "model=L") + t.check("set model=L without an UpscalerIndex key: the key is created with Model L's entry (1)", + rc == 0 and upscaler_index(read(oini).decode("utf-8", "replace")) == "1" and choice_record(b).get("model") == "L", + (rc, read(oini)[-300:])) + # an apply interrupted between the record and OptiScaler.ini (a crash): the record has the choice, the entry is stale, + # which is harmless (the front end never takes the entry for a choice); the next apply sets the entry + write(oini, set_upscaler_index(read(oini).decode("utf-8", "replace"), "5").encode("utf-8")) + r5 = choice_record(b) + t.env["WRONGGPU_TEST_STOP_AFTER_CHOICE_RECORD"] = "1" + rc = t.run("set", exe, "model=L") + t.env.pop("WRONGGPU_TEST_STOP_AFTER_CHOICE_RECORD") + r6 = choice_record(b) + t.check("set model=L stopped after the record (exit 97): the record has L with the next seq, OptiScaler's entry is still 5", + rc == 97 and r6.get("model") == "L" and r6.get("source") == "launcher" and int(r6.get("seq", "0")) == int(r5.get("seq", "0")) + 1 and + upscaler_index(read(oini).decode("utf-8", "replace")) == "5", (rc, r5, r6)) + rc = t.run("set", exe, "model=L") + t.check("...the next set model=L: OptiScaler's entry is Model L's (1) again, the record's seq grows", + rc == 0 and upscaler_index(read(oini).decode("utf-8", "replace")) == "1" and int(choice_record(b).get("seq", "0")) == int(r6.get("seq", "0")) + 1, + (rc, choice_record(b))) + rc = t.run("set", exe, "model=M") + t.check("...set model=M: wronggpu.ini back byte for byte as the install wrote it, OptiScaler's entry Model M's (0; the key the player" + " removed was created again, so OptiScaler.ini differs only in where that line is)", + rc == 0 and read(wini) == m_w and upscaler_index(read(oini).decode("utf-8", "replace")) == "0" and + sorted(read(oini).split(b"\r\n")) == sorted(m_o.split(b"\r\n")), + (rc, read(wini) == m_w, set(read(oini).split(b"\r\n")) ^ set(m_o.split(b"\r\n")), read(wini)[-200:])) # a game saved on L whose data goes away: a repair keeps the player's choice, the files say Model M with a warning rc = t.run("set", exe, "model=L") os.remove(os.path.join(t.lad, "WrongGPU", "model", "L", "model.wgcm")) # (t.model is the case here, not the path helper) From 1112b937d5edd5efa4559c971baaf3da84206e11 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:52:27 -0500 Subject: [PATCH 06/15] Shared: the per-game state folder, its lock and atomic writes (wg_state.h) One header-only module for every WrongGPU program that changes per-game state after the install (the launcher, the front end and its menu plugin, the RR plugin): - the ONE state folder \wronggpu-setup (settings.ini: settings chosen in the launcher or a WrongGPU menu in the game, over wronggpu.ini's install defaults; model-choice.ini: the model choice record); - StateLock: a named mutex per game folder, named from the folder's file identity (volume serial + file index, so every spelling of the path gives the same name), open to every integrity level, bounded wait, abandoned = taken; - WriteAtomic: temporary file in the same folder (created only where nothing is), flushed, MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH), the temporary file deleted on any failure; - settings.ini in a strict key=value format (corrupt = no keys); SetSettings is the locked read-modify-write (an unreadable file is never overwritten, the folder never created). test_wg_state (ctest wgshared_state): the format, real-file writes and cleanup, the lock name for several spellings, four child processes doing 50 locked increments each of one counter (200 at the end), a busy lock (bounded wait, nothing written) and a holder that dies (abandoned, taken). Refs #219 Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/wgshared/CMakeLists.txt | 12 + clean/wgshared/include/wg_state.h | 298 +++++++++++++++++++++++++ clean/wgshared/tests/test_wg_state.cpp | 242 ++++++++++++++++++++ 3 files changed, 552 insertions(+) create mode 100644 clean/wgshared/include/wg_state.h create mode 100644 clean/wgshared/tests/test_wg_state.cpp diff --git a/clean/wgshared/CMakeLists.txt b/clean/wgshared/CMakeLists.txt index e868fee9..00721c49 100644 --- a/clean/wgshared/CMakeLists.txt +++ b/clean/wgshared/CMakeLists.txt @@ -45,6 +45,18 @@ if(WIN32) target_link_options(test_cross_reader PRIVATE -static) endif() add_test(NAME wgshared_cross_reader COMMAND test_cross_reader) + + # The per-game state folder (wg_state.h): strict settings.ini, atomic writes, the state lock across real processes. + add_executable(test_wg_state ${CMAKE_CURRENT_LIST_DIR}/tests/test_wg_state.cpp) + target_link_libraries(test_wg_state PRIVATE wg_shared_headers advapi32) + set_target_properties(test_wg_state PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + if(MSVC) + target_compile_options(test_wg_state PRIVATE /W4 /WX /permissive- /utf-8) + else() + target_compile_options(test_wg_state PRIVATE -Wall -Wextra -municode) + target_link_options(test_wg_state PRIVATE -static -municode) + endif() + add_test(NAME wgshared_state COMMAND test_wg_state) endif() find_package(Python3 COMPONENTS Interpreter QUIET) diff --git a/clean/wgshared/include/wg_state.h b/clean/wgshared/include/wg_state.h new file mode 100644 index 00000000..6bb756c7 --- /dev/null +++ b/clean/wgshared/include/wg_state.h @@ -0,0 +1,298 @@ +// SPDX-License-Identifier: MIT +#pragma once +// WrongGPU's per-game state folder (0.6.5): ONE folder per game, \wronggpu-setup (the launcher's state folder, +// beside the install record), holding everything WrongGPU's user interfaces change after the install: +// settings.ini settings chosen in the launcher or in a WrongGPU menu in the game (for example the RR plugin's +// rr_mode): they take precedence over the install's defaults in wronggpu.ini, which no WrongGPU +// program rewrites after the install (wronggpu.ini is the player's to edit); +// model-choice.ini the model choice record (clean/fsr/src/model_choice_record.h). +// The folder is always WrongGPU's: an uninstall removes these files, a repair or update keeps them. +// +// Every read-modify-write of a file in the folder, by any WrongGPU program (the launcher, the elevated worker, the front +// end, the menu plugin, the RR plugin), holds the game's state lock (StateLock): a named mutex per game folder, +// Local\WrongGPU-state-- +// taken from the game folder's file identity, so every spelling of the path (case, 8.3 names, a mapped drive or a +// junction to the same folder) gives the same name. The mutex grants SYNCHRONIZE and MUTEX_MODIFY_STATE to everyone and +// carries a low integrity label, so an elevated launcher and the game (any integrity) share it. A holder that dies leaves +// the mutex abandoned: the next waiter gets it (the files are replaced atomically, so they are whole either way). +// +// Writes are atomic (WriteAtomic): a new temporary file in the same folder (.wgtmp--, created only where +// nothing is), flushed, then MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH) over the file; the temporary file is deleted when +// any step fails. A reader sees the old file or the new one, never part of one. Temporary files never count as state. +// +// settings.ini, strictly (anything else is CORRUPT: readers treat the file as empty and say so; the next write replaces it): +// ; comment lines and blank lines +// key=value key: [a-z0-9_], 1..64 chars; value: [A-Za-z0-9_.+-], 0..256 chars; each key at most once; +// no sections, no spaces around '='; CRLF or LF line ends; UTF-8 without anything outside ASCII. +// Written for this project; Windows API and the C++ standard library only. +#include +#include +#include +#include + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#ifdef _MSC_VER +#pragma comment(lib, "advapi32.lib") +#endif + +namespace wgstate { + +constexpr const wchar_t* kStateFolder = L"wronggpu-setup"; +constexpr const wchar_t* kSettingsFile = L"settings.ini"; +constexpr const wchar_t* kModelChoiceFile = L"model-choice.ini"; +constexpr const wchar_t* kTempMark = L".wgtmp-"; // .wgtmp--: a write in progress (or one a crash left) +constexpr DWORD kDefaultWaitMs = 5000; + +inline std::wstring JoinPath(std::wstring a, const std::wstring& b) { + if (!a.empty() && a.back() != L'\\' && a.back() != L'/') a.push_back(L'\\'); + return a + b; +} +inline std::wstring StateDirOf(const std::wstring& gameDir) { return JoinPath(gameDir, kStateFolder); } +inline std::wstring SettingsPathOf(const std::wstring& gameDir) { return JoinPath(StateDirOf(gameDir), kSettingsFile); } +inline bool IsDirectory(const std::wstring& p) { + const DWORD a = GetFileAttributesW(p.c_str()); + return a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_DIRECTORY); +} +// A temporary file of WriteAtomic (its own name contains the mark; the state files' names never do). +inline bool IsTempName(const std::wstring& name) { return name.find(kTempMark) != std::wstring::npos; } + +// The state lock's name for the game folder `gameDir`; false (and *err) when the folder cannot be opened. +inline bool LockNameFor(const std::wstring& gameDir, std::wstring* name, DWORD* err = nullptr) { + HANDLE h = CreateFileW(gameDir.c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); + if (h == INVALID_HANDLE_VALUE) { + if (err) *err = GetLastError(); + return false; + } + BY_HANDLE_FILE_INFORMATION info{}; + const BOOL ok = GetFileInformationByHandle(h, &info); + const DWORD e = GetLastError(); + CloseHandle(h); + if (!ok) { + if (err) *err = e; + return false; + } + wchar_t buf[96]; + const unsigned long long index = (static_cast(info.nFileIndexHigh) << 32) | info.nFileIndexLow; + swprintf(buf, sizeof buf / sizeof buf[0], L"Local\\WrongGPU-state-%08lX-%016llX", static_cast(info.dwVolumeSerialNumber), index); + *name = buf; + return true; +} + +// The game's state lock, held from construction (when held()) to destruction. Bounded wait: not held after waitMs. +class StateLock { +public: + explicit StateLock(const std::wstring& gameDir, DWORD waitMs = kDefaultWaitMs) { + std::wstring name; + if (!LockNameFor(gameDir, &name, &err_)) return; + PSECURITY_DESCRIPTOR sd = nullptr; + SECURITY_ATTRIBUTES sa{sizeof(sa), nullptr, FALSE}; + // everyone: SYNCHRONIZE | MUTEX_MODIFY_STATE; SYSTEM and administrators: all; low integrity label (no write-up block) + if (ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:(A;;0x00100001;;;WD)(A;;GA;;;SY)(A;;GA;;;BA)S:(ML;;NW;;;LW)", + SDDL_REVISION_1, &sd, nullptr)) + sa.lpSecurityDescriptor = sd; + mutex_ = CreateMutexW(sa.lpSecurityDescriptor ? &sa : nullptr, FALSE, name.c_str()); + if (!mutex_ && GetLastError() == ERROR_ACCESS_DENIED) mutex_ = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, name.c_str()); + if (!mutex_) err_ = GetLastError(); + if (sd) LocalFree(sd); + if (!mutex_) return; + const DWORD w = WaitForSingleObject(mutex_, waitMs); + held_ = w == WAIT_OBJECT_0 || w == WAIT_ABANDONED; + abandoned_ = w == WAIT_ABANDONED; + if (!held_) err_ = w == WAIT_TIMEOUT ? WAIT_TIMEOUT : GetLastError(); + } + ~StateLock() { + if (held_) ReleaseMutex(mutex_); + if (mutex_) CloseHandle(mutex_); + } + StateLock(const StateLock&) = delete; + StateLock& operator=(const StateLock&) = delete; + bool held() const { return held_; } + bool abandoned() const { return abandoned_; } // the previous holder ended without releasing it + DWORD error() const { return err_; } // why not held: WAIT_TIMEOUT, or the Win32 error + +private: + HANDLE mutex_ = nullptr; + bool held_ = false, abandoned_ = false; + DWORD err_ = 0; +}; + +// The whole file. false: missing (*missing = true) or unreadable (*missing = false; *err the Win32 error). +inline bool ReadBytes(const std::wstring& path, std::string* out, bool* missing = nullptr, DWORD* err = nullptr) { + out->clear(); + if (missing) *missing = false; + HANDLE h = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) { + const DWORD e = GetLastError(); + if (missing) *missing = e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND; + if (err) *err = e; + return false; + } + char buf[4096]; + DWORD got = 0; + bool ok = true; + for (;;) { + if (!ReadFile(h, buf, sizeof buf, &got, nullptr)) { ok = false; if (err) *err = GetLastError(); break; } + if (!got) break; + out->append(buf, got); + if (out->size() > (1u << 20)) { ok = false; if (err) *err = ERROR_FILE_TOO_LARGE; break; } // no state file is that large + } + CloseHandle(h); + if (!ok) out->clear(); + return ok; +} + +// The atomic replace described above. false (and *err) when any step failed; the file is then as it was. +inline bool WriteAtomic(const std::wstring& path, const std::string& bytes, DWORD* err = nullptr) { + static volatile LONG counter = 0; + DWORD e = 0; + for (int attempt = 0; attempt < 16; ++attempt) { + const std::wstring tmp = path + kTempMark + std::to_wstring(GetCurrentProcessId()) + L"-" + std::to_wstring(InterlockedIncrement(&counter)); + HANDLE h = CreateFileW(tmp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) { + e = GetLastError(); + if (e == ERROR_FILE_EXISTS || e == ERROR_ALREADY_EXISTS) continue; + break; + } + DWORD put = 0; + bool ok = bytes.empty() || (WriteFile(h, bytes.data(), static_cast(bytes.size()), &put, nullptr) && put == bytes.size()); + if (!ok) e = GetLastError() ? GetLastError() : ERROR_WRITE_FAULT; + if (ok && !FlushFileBuffers(h)) { ok = false; e = GetLastError(); } + CloseHandle(h); + if (ok && !MoveFileExW(tmp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { ok = false; e = GetLastError(); } + if (!ok) { + DeleteFileW(tmp.c_str()); + break; + } + return true; + } + if (err) *err = e ? e : ERROR_FILE_EXISTS; + return false; +} + +// ---- settings.ini ------------------------------------------------------------------------------------------------- +struct Settings { + std::vector> kv; // in file order + bool present = false; // the file was there and read + bool corrupt = false; // it was there and not in the format above (kv empty) + std::string why; // what was wrong (corrupt), or why it could not be read +}; +inline bool KeyChar(char c) { return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_'; } +inline bool ValueChar(char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '.' || c == '+' || c == '-'; +} +inline bool ValidKey(const std::string& k) { + if (k.empty() || k.size() > 64) return false; + for (char c : k) if (!KeyChar(c)) return false; + return true; +} +inline bool ValidValue(const std::string& v) { + if (v.size() > 256) return false; + for (char c : v) if (!ValueChar(c)) return false; + return true; +} +inline const std::string* Get(const Settings& s, const std::string& key) { + for (const auto& p : s.kv) if (p.first == key) return &p.second; + return nullptr; +} +// Sets key=value (added at the end when new). false: not a valid key or value (nothing changed). +inline bool Set(Settings& s, const std::string& key, const std::string& value) { + if (!ValidKey(key) || !ValidValue(value)) return false; + for (auto& p : s.kv) if (p.first == key) { p.second = value; return true; } + s.kv.emplace_back(key, value); + return true; +} +// Parses settings.ini text strictly; a text not in the format gives corrupt = true and no keys. +inline Settings ParseSettings(const std::string& text) { + Settings s; + s.present = true; + size_t a = 0; + int lineNo = 0; + while (a < text.size()) { + size_t e = text.find('\n', a); + if (e == std::string::npos) e = text.size(); + std::string line = text.substr(a, e - a); + a = e + 1; + ++lineNo; + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line.empty() || line[0] == ';') { + for (char c : line) if (static_cast(c) >= 0x80 || (c < 0x20 && c != '\t')) { s.kv.clear(); s.corrupt = true; s.why = "line " + std::to_string(lineNo) + ": not plain text"; return s; } + continue; + } + const size_t eq = line.find('='); + const std::string k = eq == std::string::npos ? line : line.substr(0, eq), v = eq == std::string::npos ? std::string() : line.substr(eq + 1); + if (eq == std::string::npos || !ValidKey(k) || !ValidValue(v) || Get(s, k)) { + s.kv.clear(); + s.corrupt = true; + s.why = "line " + std::to_string(lineNo) + (eq == std::string::npos ? ": no key=value" : !ValidKey(k) ? ": not a valid key" : !ValidValue(v) ? ": not a valid value" : ": the key appears twice"); + return s; + } + s.kv.emplace_back(k, v); + } + return s; +} +inline std::string RenderSettings(const Settings& s) { + std::string out = "; WrongGPU: settings chosen in the launcher or in a WrongGPU menu in the game (they take precedence over wronggpu.ini)\r\n"; + for (const auto& p : s.kv) out += p.first + "=" + p.second + "\r\n"; + return out; +} +// settings.ini of the game in gameDir. Missing: present = false, no keys. Unreadable or corrupt: no keys, why says so. +inline Settings ReadSettings(const std::wstring& gameDir) { + std::string text; + bool missing = false; + DWORD err = 0; + if (!ReadBytes(SettingsPathOf(gameDir), &text, &missing, &err)) { + Settings s; + if (!missing) s.why = "unreadable (error " + std::to_string(err) + ")"; + return s; + } + return ParseSettings(text); +} + +enum class SetResult { Ok, NoStateFolder, Busy, Unreadable, Invalid, WriteFailed }; +inline const char* SetResultWords(SetResult r) { + switch (r) { + case SetResult::Ok: return "saved"; + case SetResult::NoStateFolder: return "no WrongGPU state folder for this game (not installed by the launcher)"; + case SetResult::Busy: return "another WrongGPU program kept the game's state lock"; + case SetResult::Unreadable: return "the settings file could not be read (left as it is)"; + case SetResult::Invalid: return "not a valid key or value"; + case SetResult::WriteFailed: return "the settings file could not be written"; + } + return "?"; +} +// The read-modify-write of settings.ini under the game's state lock: the changes applied to the file as it is now (a +// corrupt file starts empty; an unreadable one is never overwritten). The state folder is never created here: without it +// the game has no WrongGPU install of the launcher (NoStateFolder). *err: the Win32 error of a failure. +inline SetResult SetSettings(const std::wstring& gameDir, const std::vector>& changes, + DWORD waitMs = kDefaultWaitMs, DWORD* err = nullptr) { + for (const auto& c : changes) if (!ValidKey(c.first) || !ValidValue(c.second)) return SetResult::Invalid; + if (!IsDirectory(StateDirOf(gameDir))) return SetResult::NoStateFolder; + StateLock lock(gameDir, waitMs); + if (!lock.held()) { if (err) *err = lock.error(); return SetResult::Busy; } + std::string text; + bool missing = false; + DWORD e = 0; + Settings s; + if (ReadBytes(SettingsPathOf(gameDir), &text, &missing, &e)) s = ParseSettings(text); + else if (!missing) { if (err) *err = e; return SetResult::Unreadable; } + if (s.corrupt) s = Settings(); + bool changed = !s.present; + for (const auto& c : changes) { + const std::string* now = Get(s, c.first); + if (!now || *now != c.second) { Set(s, c.first, c.second); changed = true; } + } + if (!changed) return SetResult::Ok; + if (!WriteAtomic(SettingsPathOf(gameDir), RenderSettings(s), &e)) { if (err) *err = e; return SetResult::WriteFailed; } + return SetResult::Ok; +} + +} // namespace wgstate diff --git a/clean/wgshared/tests/test_wg_state.cpp b/clean/wgshared/tests/test_wg_state.cpp new file mode 100644 index 00000000..779251ee --- /dev/null +++ b/clean/wgshared/tests/test_wg_state.cpp @@ -0,0 +1,242 @@ +// SPDX-License-Identifier: MIT +// Tests of wg_state.h (the per-game state folder, its lock and atomic writes) on real files and real processes: the strict +// settings.ini format, atomic writes and their cleanup, one lock name for every spelling of a folder, mutual exclusion +// across processes (concurrent read-modify-write of one counter from several child processes loses no update), a busy +// lock (bounded wait), an abandoned lock (a child that dies holding it), an unreadable file never overwritten, a corrupt +// file replaced, and no state folder created. The test runs itself as the child process (--child ...). +// Written for this project. +#include +#include +#include +#include + +#include "wg_state.h" + +using namespace wgstate; + +static int g_fail = 0, g_pass = 0; +static void check(bool ok, const char* what) { + if (ok) ++g_pass; + else { ++g_fail; std::printf("FAIL: %s\n", what); } +} + +static std::wstring Exe() { + wchar_t b[MAX_PATH * 2]; + const DWORD n = GetModuleFileNameW(nullptr, b, MAX_PATH * 2); + return std::wstring(b, n); +} +static std::wstring TempRoot() { + wchar_t b[MAX_PATH * 2]; + const DWORD n = GetTempPathW(MAX_PATH * 2, b); + std::wstring r = JoinPath(std::wstring(b, n), L"wg-state-test-" + std::to_wstring(GetCurrentProcessId())); + CreateDirectoryW(r.c_str(), nullptr); + return r; +} +static void WriteText(const std::wstring& p, const std::string& t) { + HANDLE h = CreateFileW(p.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + DWORD put = 0; + if (h != INVALID_HANDLE_VALUE) { WriteFile(h, t.data(), static_cast(t.size()), &put, nullptr); CloseHandle(h); } +} +static std::string ReadText(const std::wstring& p) { std::string t; ReadBytes(p, &t); return t; } +static std::vector List(const std::wstring& dir) { + std::vector out; + WIN32_FIND_DATAW f; + HANDLE h = FindFirstFileW(JoinPath(dir, L"*").c_str(), &f); + if (h == INVALID_HANDLE_VALUE) return out; + do { if (wcscmp(f.cFileName, L".") && wcscmp(f.cFileName, L"..")) out.push_back(f.cFileName); } while (FindNextFileW(h, &f)); + FindClose(h); + return out; +} +static HANDLE Spawn(const std::wstring& args) { + std::wstring cmd = L"\"" + Exe() + L"\" " + args; + STARTUPINFOW si{}; + si.cb = sizeof si; + PROCESS_INFORMATION pi{}; + if (!CreateProcessW(nullptr, &cmd[0], nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi)) return nullptr; + CloseHandle(pi.hThread); + return pi.hProcess; +} +static DWORD WaitExit(HANDLE p, DWORD ms = 60000) { + DWORD code = 999; + if (WaitForSingleObject(p, ms) == WAIT_OBJECT_0) GetExitCodeProcess(p, &code); + CloseHandle(p); + return code; +} +static unsigned long Counter(const std::wstring& game) { + const Settings s = ReadSettings(game); + const std::string* v = Get(s, "counter"); + return v ? std::strtoul(v->c_str(), nullptr, 10) : 0; +} + +static bool WaitFile(const std::wstring& p, DWORD ms = 30000) { + for (DWORD t = 0; t < ms; t += 20) { + if (GetFileAttributesW(p.c_str()) != INVALID_FILE_ATTRIBUTES) return true; + Sleep(20); + } + return false; +} + +// child modes: --child-add : n locked read-modify-write increments; --child-hold : holds the +// lock for ms; --child-die : takes the lock and, once go exists, ends without releasing it +static int Child(int argc, wchar_t** argv) { + const std::wstring mode = argv[1], game = argv[2]; + if (mode == L"--child-add" && argc >= 4) { + const int n = _wtoi(argv[3]); + for (int i = 0; i < n; ++i) { + StateLock lock(game, 30000); + if (!lock.held()) return 3; + const Settings s = ReadSettings(game); + const std::string* v = Get(s, "counter"); + const unsigned long c = v ? std::strtoul(v->c_str(), nullptr, 10) : 0; + Settings w = s; + Set(w, "counter", std::to_string(c + 1)); + Sleep(0); // widen the window a lost update would need + if (!WriteAtomic(SettingsPathOf(game), RenderSettings(w))) return 4; + } + return 0; + } + if (mode == L"--child-hold" && argc >= 5) { + StateLock lock(game, 30000); + if (!lock.held()) return 3; + WriteText(argv[4], "ready"); + Sleep(static_cast(_wtoi(argv[3]))); + return 0; + } + if (mode == L"--child-die" && argc >= 5) { + StateLock* lock = new StateLock(game, 30000); // never released: the process ends holding it + if (!lock->held()) return 3; + WriteText(argv[3], "ready"); + WaitFile(argv[4]); // the parent has its own handle now + ExitProcess(0); + } + return 2; +} + +int wmain(int argc, wchar_t** argv) { + if (argc >= 3 && std::wstring(argv[1]).rfind(L"--child", 0) == 0) return Child(argc, argv); + const std::wstring root = TempRoot(); + + // ---- the strict format + { + Settings s = ParseSettings("; comment\r\n\r\nrr_mode=fast\r\nrr_enabled=1\n"); + check(s.present && !s.corrupt && s.kv.size() == 2 && *Get(s, "rr_mode") == "fast" && *Get(s, "rr_enabled") == "1", "parse: comments, blank lines, CRLF and LF"); + const char* bad[] = {"rr_mode = fast\r\n", "[wronggpu]\r\nrr_mode=fast\r\n", "RR_MODE=fast\r\n", "rr_mode=fast\r\nrr_mode=accurate\r\n", + "rr_mode\r\n", "rr_mode=fa st\r\n", "=fast\r\n", "rr_mode=f\xc3\xa4st\r\n", "; \xc3\xa4\r\n"}; + bool all = true; + for (const char* b : bad) { const Settings x = ParseSettings(b); all = all && x.corrupt && x.kv.empty() && !x.why.empty(); } + check(all, "parse: spaces, sections, upper case, a key twice, no '=', bad value, empty key, non-ASCII: corrupt, no keys"); + Settings r; + check(Set(r, "rr_mode", "fast") && Set(r, "rr_mode", "exact") && r.kv.size() == 1 && !Set(r, "Bad Key", "x") && !Set(r, "k", "a b"), "Set: replace, refuse bad key/value"); + const Settings back = ParseSettings(RenderSettings(r)); + check(!back.corrupt && back.kv == r.kv, "render -> parse round trip"); + } + + // ---- atomic writes and reads on real files + const std::wstring game = JoinPath(root, L"Game"); + CreateDirectoryW(game.c_str(), nullptr); + { + check(ReadSettings(game).present == false && ReadSettings(game).why.empty(), "no settings.ini: not present, no error"); + check(SetSettings(game, {{"rr_mode", "fast"}}) == SetResult::NoStateFolder && !IsDirectory(StateDirOf(game)), + "no state folder: NoStateFolder, the folder is not created"); + CreateDirectoryW(StateDirOf(game).c_str(), nullptr); + check(SetSettings(game, {{"rr_mode", "fast"}}) == SetResult::Ok && *Get(ReadSettings(game), "rr_mode") == "fast", "SetSettings writes the file"); + check(SetSettings(game, {{"rr_enabled", "0"}}) == SetResult::Ok && *Get(ReadSettings(game), "rr_mode") == "fast" && + *Get(ReadSettings(game), "rr_enabled") == "0", "a second key keeps the first"); + check(SetSettings(game, {{"rr mode", "x"}}) == SetResult::Invalid, "an invalid key: Invalid, nothing written"); + std::vector names = List(StateDirOf(game)); + check(names.size() == 1 && names[0] == kSettingsFile, "no temporary file stays after writes"); + DWORD e = 0; + check(!WriteAtomic(JoinPath(JoinPath(root, L"missing-folder"), L"x.ini"), "x", &e) && e != 0, "a write into a missing folder fails with its error"); + // corrupt: readers see no keys; the next write replaces the file + WriteText(SettingsPathOf(game), "rr_mode = fast\r\n"); + const Settings c = ReadSettings(game); + check(c.present && c.corrupt && c.kv.empty(), "a corrupt file reads as corrupt, no keys"); + check(SetSettings(game, {{"rr_mode", "accurate"}}) == SetResult::Ok && !ReadSettings(game).corrupt && *Get(ReadSettings(game), "rr_mode") == "accurate" && + ReadSettings(game).kv.size() == 1, "a corrupt file is replaced by the next write (only the new key)"); + // unreadable (held without sharing): never overwritten + const std::string before = ReadText(SettingsPathOf(game)); + HANDLE h = CreateFileW(SettingsPathOf(game).c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + DWORD err = 0; + const SetResult r = SetSettings(game, {{"rr_mode", "exact"}}, kDefaultWaitMs, &err); + CloseHandle(h); + check(r == SetResult::Unreadable && err != 0 && ReadText(SettingsPathOf(game)) == before, "an unreadable file: Unreadable, left as it was"); + names = List(StateDirOf(game)); + check(names.size() == 1, "no temporary file stays after the refused write"); + } + + // ---- one lock name for every spelling of the folder + { + std::wstring a, b, c, d; + check(LockNameFor(game, &a) && LockNameFor(game + L"\\", &b) && a == b && a.rfind(L"Local\\WrongGPU-state-", 0) == 0, "lock name: trailing backslash"); + std::wstring upper = game; + for (auto& ch : upper) ch = static_cast(towupper(ch)); + check(LockNameFor(upper, &c) && a == c, "lock name: another case"); + wchar_t shortp[MAX_PATH * 2]; + if (GetShortPathNameW(game.c_str(), shortp, MAX_PATH * 2)) check(LockNameFor(shortp, &d) && a == d, "lock name: the short (8.3) path"); + std::wstring other; + const std::wstring g2 = JoinPath(root, L"Other"); + CreateDirectoryW(g2.c_str(), nullptr); + check(LockNameFor(g2, &other) && other != a, "lock name: another folder, another name"); + DWORD e = 0; + check(!LockNameFor(JoinPath(root, L"nope"), &other, &e) && e != 0, "lock name: a missing folder fails"); + } + + // ---- mutual exclusion across processes: 4 children x 50 locked increments of one counter, no update lost + { + WriteText(SettingsPathOf(game), "counter=0\r\n"); + std::vector kids; + for (int i = 0; i < 4; ++i) kids.push_back(Spawn(L"--child-add \"" + game + L"\" 50")); + bool started = true, ok = true; + for (HANDLE k : kids) { if (!k) started = false; else ok = WaitExit(k, 120000) == 0 && ok; } + check(started && ok, "4 child processes ran their locked increments"); + check(Counter(game) == 200, "the counter is 200: the lock serialised every read-modify-write across processes"); + check(List(StateDirOf(game)).size() == 1, "no temporary file stays after concurrent writes"); + } + + // ---- busy: another process holds the lock; a bounded wait gives up (Busy), the file unchanged + { + const std::wstring ready = JoinPath(root, L"ready-hold"); + HANDLE k = Spawn(L"--child-hold \"" + game + L"\" 3000 \"" + ready + L"\""); + const bool up = k && WaitFile(ready); + const std::string before = ReadText(SettingsPathOf(game)); + DWORD err = 0; + const SetResult r = SetSettings(game, {{"rr_mode", "fast"}}, 200, &err); + check(up && r == SetResult::Busy && err == WAIT_TIMEOUT && ReadText(SettingsPathOf(game)) == before, "lock held elsewhere: Busy after the bounded wait, nothing written"); + if (k) WaitExit(k); + check(SetSettings(game, {{"rr_mode", "fast"}}, 5000) == SetResult::Ok, "after the holder ends: the write goes through"); + } + + // ---- abandoned: a child dies holding the lock; the next waiter gets it + { + const std::wstring ready = JoinPath(root, L"ready-die"); + const std::wstring go = JoinPath(root, L"go-die"); + HANDLE k = Spawn(L"--child-die \"" + game + L"\" \"" + ready + L"\" \"" + go + L"\""); + const bool up = k && WaitFile(ready); + std::wstring name; + LockNameFor(game, &name); + HANDLE keep = OpenMutexW(SYNCHRONIZE, FALSE, name.c_str()); // keeps the mutex object alive past the child's end + WriteText(go, "go"); + if (k) WaitExit(k); + { + StateLock lock(game, 5000); + if (!(up && keep && lock.held() && lock.abandoned())) + std::printf(" (up %d, kept handle %d, held %d, abandoned %d, error %lu)\n", up, keep != nullptr, lock.held(), lock.abandoned(), lock.error()); + check(up && keep && lock.held() && lock.abandoned(), "a holder that died: the lock is taken (abandoned), not stuck"); + } + if (keep) CloseHandle(keep); + StateLock again(game, 5000); + check(again.held() && !again.abandoned(), "after that: the lock is taken normally"); + } + + // cleanup (own files only) + for (const auto& n : List(StateDirOf(game))) DeleteFileW(JoinPath(StateDirOf(game), n).c_str()); + RemoveDirectoryW(StateDirOf(game).c_str()); + RemoveDirectoryW(game.c_str()); + RemoveDirectoryW(JoinPath(root, L"Other").c_str()); + DeleteFileW(JoinPath(root, L"ready-hold").c_str()); + DeleteFileW(JoinPath(root, L"ready-die").c_str()); + DeleteFileW(JoinPath(root, L"go-die").c_str()); + RemoveDirectoryW(root.c_str()); + std::printf("wg_state: %d passed, %d failed\n", g_pass, g_fail); + return g_fail ? 1 : 0; +} From 27e86aa9b182225f65a40121d83626ce18d635cf Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:01:46 -0500 Subject: [PATCH 07/15] Shared: the loaded marker (LoadedMarker, IsGameUsingWrongGPU) in wg_state.h A WrongGPU module loaded in the game keeps a named mutex Local\WrongGPU-loaded-- open (never owned) for the game folder; the object exists exactly while some process has it open, and the OS closes every handle of a process that ends or crashes, so a dead game leaves no stale marker. IsGameUsingWrongGPU(gameDir) only opens it (never creates). StateLock and the marker share CreateSharedMutex and NameFor. Tests: a marker in this process (any spelling of the folder), another folder, a missing folder, a child process holding it, and that child killed (TerminateProcess): not in use. Refs #219 Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/wgshared/include/wg_state.h | 74 ++++++++++++++++++++++---- clean/wgshared/tests/test_wg_state.cpp | 33 ++++++++++++ 2 files changed, 96 insertions(+), 11 deletions(-) diff --git a/clean/wgshared/include/wg_state.h b/clean/wgshared/include/wg_state.h index 6bb756c7..79736e98 100644 --- a/clean/wgshared/include/wg_state.h +++ b/clean/wgshared/include/wg_state.h @@ -16,6 +16,9 @@ // carries a low integrity label, so an elevated launcher and the game (any integrity) share it. A holder that dies leaves // the mutex abandoned: the next waiter gets it (the files are replaced atomically, so they are whole either way). // +// While a WrongGPU module is loaded in the game it keeps the game's LoadedMarker open (below); the launcher refuses an +// uninstall, repair or update while IsGameUsingWrongGPU says so. The OS drops the marker when the process ends or crashes. +// // Writes are atomic (WriteAtomic): a new temporary file in the same folder (.wgtmp--, created only where // nothing is), flushed, then MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH) over the file; the temporary file is deleted when // any step fails. A reader sees the old file or the new one, never part of one. Temporary files never count as state. @@ -86,23 +89,36 @@ inline bool LockNameFor(const std::wstring& gameDir, std::wstring* name, DWORD* return true; } +// Another per-game name of the same identity: prefix + "-". +inline bool NameFor(const wchar_t* prefix, const std::wstring& gameDir, std::wstring* name, DWORD* err) { + std::wstring lock; + if (!LockNameFor(gameDir, &lock, err)) return false; + *name = std::wstring(prefix) + lock.substr(lock.find(L"-state-") + 7); + return true; +} +// A named mutex every integrity level may open (created, or opened when it exists); nullptr with GetLastError on failure. +inline HANDLE CreateSharedMutex(const std::wstring& name) { + PSECURITY_DESCRIPTOR sd = nullptr; + SECURITY_ATTRIBUTES sa{sizeof(sa), nullptr, FALSE}; + // everyone: SYNCHRONIZE | MUTEX_MODIFY_STATE; SYSTEM and administrators: all; low integrity label (no write-up block) + if (ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:(A;;0x00100001;;;WD)(A;;GA;;;SY)(A;;GA;;;BA)S:(ML;;NW;;;LW)", SDDL_REVISION_1, &sd, nullptr)) + sa.lpSecurityDescriptor = sd; + HANDLE m = CreateMutexW(sa.lpSecurityDescriptor ? &sa : nullptr, FALSE, name.c_str()); + if (!m && GetLastError() == ERROR_ACCESS_DENIED) m = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, name.c_str()); + const DWORD e = GetLastError(); + if (sd) LocalFree(sd); + SetLastError(e); + return m; +} + // The game's state lock, held from construction (when held()) to destruction. Bounded wait: not held after waitMs. class StateLock { public: explicit StateLock(const std::wstring& gameDir, DWORD waitMs = kDefaultWaitMs) { std::wstring name; if (!LockNameFor(gameDir, &name, &err_)) return; - PSECURITY_DESCRIPTOR sd = nullptr; - SECURITY_ATTRIBUTES sa{sizeof(sa), nullptr, FALSE}; - // everyone: SYNCHRONIZE | MUTEX_MODIFY_STATE; SYSTEM and administrators: all; low integrity label (no write-up block) - if (ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:(A;;0x00100001;;;WD)(A;;GA;;;SY)(A;;GA;;;BA)S:(ML;;NW;;;LW)", - SDDL_REVISION_1, &sd, nullptr)) - sa.lpSecurityDescriptor = sd; - mutex_ = CreateMutexW(sa.lpSecurityDescriptor ? &sa : nullptr, FALSE, name.c_str()); - if (!mutex_ && GetLastError() == ERROR_ACCESS_DENIED) mutex_ = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, name.c_str()); - if (!mutex_) err_ = GetLastError(); - if (sd) LocalFree(sd); - if (!mutex_) return; + mutex_ = CreateSharedMutex(name); + if (!mutex_) { err_ = GetLastError(); return; } const DWORD w = WaitForSingleObject(mutex_, waitMs); held_ = w == WAIT_OBJECT_0 || w == WAIT_ABANDONED; abandoned_ = w == WAIT_ABANDONED; @@ -124,6 +140,42 @@ class StateLock { DWORD err_ = 0; }; +// ---- the loaded marker ---------------------------------------------------------------------------------------------- +// A WrongGPU module loaded in the game (the front end, the menu plugin, the RR plugin) keeps a LoadedMarker for the game +// folder for as long as it is loaded: a named mutex Local\WrongGPU-loaded-- (the same identity as +// the state lock) that it holds OPEN but never owns. The object exists exactly while some process has a handle to it, and the +// OS closes every handle of a process that ends, crashes or is killed: a dead game never leaves a stale marker. The launcher +// refuses an uninstall, repair or update while IsGameUsingWrongGPU(gameDir) is true. Same security as the state lock (every +// integrity level may open it). +class LoadedMarker { +public: + explicit LoadedMarker(const std::wstring& gameDir) { + std::wstring name; + if (!NameFor(L"Local\\WrongGPU-loaded-", gameDir, &name, &err_)) return; + handle_ = CreateSharedMutex(name); + if (!handle_) err_ = GetLastError(); + } + ~LoadedMarker() { if (handle_) CloseHandle(handle_); } + LoadedMarker(const LoadedMarker&) = delete; + LoadedMarker& operator=(const LoadedMarker&) = delete; + bool held() const { return handle_ != nullptr; } + DWORD error() const { return err_; } + +private: + HANDLE handle_ = nullptr; + DWORD err_ = 0; +}; +// A running process has WrongGPU loaded for the game folder gameDir (a LoadedMarker of it is open somewhere). Never creates the +// marker. A folder that cannot be opened: false. +inline bool IsGameUsingWrongGPU(const std::wstring& gameDir) { + std::wstring name; + DWORD err = 0; + if (!NameFor(L"Local\\WrongGPU-loaded-", gameDir, &name, &err)) return false; + HANDLE h = OpenMutexW(SYNCHRONIZE, FALSE, name.c_str()); + if (h) { CloseHandle(h); return true; } + return GetLastError() == ERROR_ACCESS_DENIED; // there, but not ours to open: still in use +} + // The whole file. false: missing (*missing = true) or unreadable (*missing = false; *err the Win32 error). inline bool ReadBytes(const std::wstring& path, std::string* out, bool* missing = nullptr, DWORD* err = nullptr) { out->clear(); diff --git a/clean/wgshared/tests/test_wg_state.cpp b/clean/wgshared/tests/test_wg_state.cpp index 779251ee..1a9f76a6 100644 --- a/clean/wgshared/tests/test_wg_state.cpp +++ b/clean/wgshared/tests/test_wg_state.cpp @@ -95,6 +95,13 @@ static int Child(int argc, wchar_t** argv) { } return 0; } + if (mode == L"--child-loaded" && argc >= 4) { // a "game" with WrongGPU loaded: the marker open until it is killed + LoadedMarker marker(game); + if (!marker.held()) return 3; + WriteText(argv[3], "ready"); + Sleep(120000); + return 0; + } if (mode == L"--child-hold" && argc >= 5) { StateLock lock(game, 30000); if (!lock.held()) return 3; @@ -228,6 +235,32 @@ int wmain(int argc, wchar_t** argv) { check(again.held() && !again.abandoned(), "after that: the lock is taken normally"); } + // ---- the loaded marker: in this process, in another one, and a dead owner (killed) leaves none + { + const std::wstring g2 = JoinPath(root, L"Other"); + check(!IsGameUsingWrongGPU(game) && !IsGameUsingWrongGPU(game), "no marker: not in use (and the check creates none)"); + { + LoadedMarker m(game); + std::wstring upper = game; + for (auto& ch : upper) ch = static_cast(towupper(ch)); + check(m.held() && IsGameUsingWrongGPU(game) && IsGameUsingWrongGPU(upper + L"\\") && !IsGameUsingWrongGPU(g2), + "a marker in this process: in use (any spelling of the folder), another folder not"); + } + check(!IsGameUsingWrongGPU(game), "the marker closed: not in use"); + check(!IsGameUsingWrongGPU(JoinPath(root, L"nope")), "a missing folder: not in use"); + const std::wstring ready = JoinPath(root, L"ready-loaded"); + HANDLE k = Spawn(L"--child-loaded \"" + game + L"\" \"" + ready + L"\""); + const bool up = k && WaitFile(ready); + check(up && IsGameUsingWrongGPU(game), "another process with the marker open: in use"); + if (k) { + TerminateProcess(k, 9); // the game crashes (no cleanup of its own) + WaitForSingleObject(k, 30000); + CloseHandle(k); + } + check(up && !IsGameUsingWrongGPU(game), "the owning process died: no stale marker, not in use"); + DeleteFileW(ready.c_str()); + } + // cleanup (own files only) for (const auto& n : List(StateDirOf(game))) DeleteFileW(JoinPath(StateDirOf(game), n).c_str()); RemoveDirectoryW(StateDirOf(game).c_str()); From fc6cb43d8719e87402ff8ddb5c4dcc2b76cac805 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:29:16 -0500 Subject: [PATCH 08/15] Model choice: the shared state lock, no queued choices, one apply lock Review of #213 (fourth round), cut down as decided: - The record lives in the game's WrongGPU state folder and uses wg_state.h (#226): its state lock (named from the game folder's volume and file identity, so every path alias is one lock) and its atomic write, retried up to 3 times in the call. #213 has no lock code of its own. - No queued choices. A plugin click or a host selection that cannot be saved in time changes nothing: the plugin's entry says "not saved, try again", the host event returns "not saved"; the running model stays. - When the record cannot be read, is corrupt or busy at a create: the last choice read this session, else wronggpu.ini's model item, else Model M. Never the host's stored entry. - The launcher's Apply with a model shown is an explicit choice: the record is always written (also the same model again) and the index set. The launcher holds the state lock across wronggpu.ini, the record and OptiScaler.ini; the model is no longer written into wronggpu.ini. A game without a record gets one from the profile; the launcher's own last choice follows the model's data being ready. - The upgrade migration reads wronggpu.ini's model item while it holds the lock (the file as it is on disk now). - The host event returns 1 when the model that runs changes (also for a re-selection of the same entry), 0 when nothing changes, negative when not saved. No session-only choices. - One shared definition of the entry order (wgshared wg_model_entries.h) for the launcher's UpscalerIndex, checked against the front end's version list. - The front end and the menu plugin keep WrongGPU's loaded marker open while loaded (wg_state.h), for the launcher's refusal to uninstall, repair or update a game in use. - The record decides on the direct route too. Tests: two real processes for the migration against a launcher apply (one dying between wronggpu.ini and the record), a junction and the \\?\ form of one folder as one lock across processes, lock timeout and failed writes changing nothing, a re-selection of the same entry returning 1, an explicit launcher choice of an unchanged model winning over a newer plugin choice, a launcher change of another setting leaving it, the entry order. Negative controls for the migration read, the fallback, the event result, the plugin's failed save and the launcher's explicit choice. Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/fsr/asi/README.md | 36 +-- clean/fsr/asi/asi_abi.h | 6 - clean/fsr/asi/asi_thunk.h | 38 ++- clean/fsr/asi/exports_asi.def | 1 - clean/fsr/asi/wronggpu_asi.cpp | 80 ++---- clean/fsr/include/wronggpu_host_event.h | 36 +-- clean/fsr/src/asi_bridge.cpp | 7 - clean/fsr/src/asi_bridge.h | 3 - clean/fsr/src/dllmain.cpp | 39 ++- clean/fsr/src/frontend.cpp | 157 +++++------ clean/fsr/src/frontend.h | 38 +-- clean/fsr/src/model_choice_record.h | 260 +++++-------------- clean/fsr/tests/test_asi_status.cpp | 4 +- clean/fsr/tests/test_asi_thunk.cpp | 58 +++-- clean/fsr/tests/test_frontend.cpp | 241 ++++++++++------- clean/fsr/tests/test_model_choice_record.cpp | 210 +++++++++++---- clean/installer/src/app/launcher_ui.cpp | 1 + clean/installer/src/wg_core/launcher.cpp | 65 ++--- clean/installer/src/wg_core/launcher.h | 2 +- clean/installer/src/wg_core/profile.h | 15 +- clean/installer/tests/run_model_k_tests.py | 18 +- clean/installer/tests/run_model_l_tests.py | 29 ++- clean/wgshared/include/wg_model_entries.h | 23 ++ 23 files changed, 714 insertions(+), 653 deletions(-) create mode 100644 clean/wgshared/include/wg_model_entries.h diff --git a/clean/fsr/asi/README.md b/clean/fsr/asi/README.md index 6923e6f6..3743daba 100644 --- a/clean/fsr/asi/README.md +++ b/clean/fsr/asi/README.md @@ -22,24 +22,24 @@ whatever the FFX box names; "FSR 3.X(/4)" runs AMD: the AMD version the FFX box The FFX box's list is the same with and without the plugin (WrongGPU first). Which model runs (0.6.5, `src/model_choice_record.h`, `TestAsiChoiceRecord`, `tests/test_model_choice_record.cpp`): the -plugin's entry says WrongGPU or AMD; which WrongGPU model is the game's **model choice record**, -`wronggpu-setup\model-choice.ini` next to wronggpu.ini (the launcher's state folder). It holds `model=`, `seq=` and -`source=` (launcher, ffx or plugin). It is written only for a choice the player made, each time with the record's seq + 1, -so the highest seq is the most recent choice and no clock is involved: by the launcher when it applies a model (the record -first, then OptiScaler's `UpscalerIndex` set to that model's entry, for display); by the front end when the WrongGPU edition -of OptiScaler reports that the player selected one of WrongGPU's entries in its list (`WrongGpuHostSelectedV1`, -`include/wronggpu_host_event.h`); and by this plugin when the player clicks one of its model entries. The entry OptiScaler's -ini stores is never taken for a choice. Every read and write takes one lock per game shared by all processes (a named -mutex), so no choice is lost and seq never goes back. Writes go to a temporary file in the same folder, flushed, then -`MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH)`, every step checked; parsing is strict, and a corrupt record counts as no -choice until the next choice replaces it. A game without a record (an install from before 0.6.5) gets one from -wronggpu.ini's model item (else Model M). A click that cannot be written now runs for the session, its entry says "not -saved yet, retrying" in the menu, and it is tried again (`WrongGpuAsiPendingChoiceV1` tells the front end); at the end of -the sequence numbers it is refused and logged. Without a record (no launcher state folder) the launcher's Model K / L item -decides, else the plugin's saved entry, else Model M. The front end logs the model and which choice decided, one line when -the record and wronggpu.ini's model item disagree, and tells the plugin which model runs (`WrongGpuAsiShowModelV1`), so -the menu marks that entry. Model L's own entry ("WrongGPU Model L") is in the menu of a build with `WG_MODEL_L`; a model -the front end was built without runs as Model M, with a note in the log. +plugin's entry says WrongGPU or AMD; which WrongGPU model is the game's **model choice record**, `model-choice.ini` in the +game's WrongGPU state folder (`wronggpu-setup`, beside `settings.ini`; `clean/wgshared/include/wg_state.h`). It holds +`model=`, `seq=` and `source=` (launcher, ffx or plugin) and is written only for a choice the player made, each time with +the record's seq + 1, so the highest seq is the most recent choice: by the launcher when the player applies a model (Apply, +or `set model=`; always, also the same model again; then OptiScaler's `UpscalerIndex` is set to that model's entry, +for display); by the front end when the WrongGPU edition of OptiScaler reports that the player selected one of WrongGPU's +entries (`WrongGpuHostSelectedV1`, `include/wronggpu_host_event.h`); and by this plugin when the player clicks one of its +model entries. The index OptiScaler stores is never a choice, and wronggpu.ini's model item is the install's default, which +only seeds the record of a game that has none (read under the lock). Every read and write holds the game's state lock (one +named mutex per game folder, from its volume and file identity, shared with every WrongGPU program); writes are atomic. +A click that cannot be saved in time changes nothing: its entry says "not saved, try again" and nothing is kept for later. +When the record cannot be read, is corrupt or busy at a create, the front end runs the last choice it read this session, +else wronggpu.ini's model item, else Model M. Without a record (no launcher state folder) the launcher's Model K / L item +decides, else the plugin's saved entry, else Model M. While the game has the plugin loaded it keeps WrongGPU's loaded +marker open, so the launcher does not uninstall, repair or update it meanwhile. The front end logs the model and which +choice decided and tells the plugin which model runs (`WrongGpuAsiShowModelV1`), so the menu marks that entry. Model L's +own entry ("WrongGPU Model L") is in the menu of a build with `WG_MODEL_L`; a model the front end was built without runs +as Model M, with a note in the log. ## How it works diff --git a/clean/fsr/asi/asi_abi.h b/clean/fsr/asi/asi_abi.h index a4975bdd..443b7cef 100644 --- a/clean/fsr/asi/asi_abi.h +++ b/clean/fsr/asi/asi_abi.h @@ -88,9 +88,3 @@ typedef void (*PfnWrongGpuAsiSetChoiceRecordV1)(const wchar_t* path); // to marking the saved choice. Display only: nothing is saved. #define WRONGGPU_ASI_SHOW_MODEL "WrongGpuAsiShowModelV1" typedef void (*PfnWrongGpuAsiShowModelV1)(char model); - -// The model of a click on one of the plugin's model entries that the plugin could not write to the record yet (the -// record was busy or a write failed; the plugin tries again, and its menu says "not saved yet"), else 0. The front end -// runs that model for the session until the record has it. -#define WRONGGPU_ASI_PENDING_CHOICE "WrongGpuAsiPendingChoiceV1" -typedef char (*PfnWrongGpuAsiPendingChoiceV1)(void); diff --git a/clean/fsr/asi/asi_thunk.h b/clean/fsr/asi/asi_thunk.h index 8d3d3cda..6c101d3f 100644 --- a/clean/fsr/asi/asi_thunk.h +++ b/clean/fsr/asi/asi_thunk.h @@ -56,8 +56,9 @@ inline const char* LabelOf(char model) { // Shared plugin state. `hooked` is read by the front end through the exported query; `model` is the player's choice // within OptiScaler's FSR 3.X entry (0: AMD). `shown` is the model the front end reported as running (kShowSaved until // it reports one): the menu marks that one, so the model the choice record decided is what the player sees checked. -// `unsaved`: a model click the plugin could not write to the model choice record yet (0: none); its entry says so in -// the menu, "(not saved yet, retrying)", or with `refused` "(not saved: the choice record is full)". +// `unsaved`: the model of the last click the plugin could not write to the model choice record (0: none). That click +// changed nothing (nothing is kept for later); its entry says "(not saved, try again)", or with `refused` "(not saved: +// the choice record is full, ...)", until the next click. struct PluginState { std::atomic hooked{false}; std::atomic model{kDefaultModel}; @@ -66,10 +67,10 @@ struct PluginState { std::atomic refused{false}; }; -constexpr const char* kUnsavedSuffix = " (not saved yet, retrying)"; +constexpr const char* kUnsavedSuffix = " (not saved, try again)"; constexpr const char* kRefusedSuffix = " (not saved: the choice record is full, see the plugin's log)"; -// The label drawn for entry `e`: its name, with the not-saved note when its click is not in the record yet. +// The label drawn for entry `e`: its name, with the not-saved note when its last click could not be saved. inline std::string EntryLabel(const Entry& e, const PluginState& st) { if (st.unsaved.load() != e.model) return e.label; return std::string(e.label) + (st.refused.load() ? kRefusedSuffix : kUnsavedSuffix); @@ -84,14 +85,20 @@ inline bool IsFsr3xLabel(const char* label) { return label && (std::strcmp(label, "FSR 3.X") == 0 || std::strcmp(label, "FSR 3.X/4") == 0); } +// The result of saving a model click (SaveFn): saved; not saved (busy, unreadable, a failed write); refused (the +// record's sequence numbers are at their end). +enum class Save { Saved, NotSaved, Refused }; + // The Selectable thunk. `sel` is the real ImGui::Selectable(label, selected, flags, size). For OptiScaler's FSR 3.X // entry it draws the WrongGPU items first, then the original entry, records any click as the selected model, and // returns true (click) to OptiScaler when any of them was clicked so OptiScaler switches to its FSR 3.X backend. // `selected` (OptiScaler's backend is FSR 3.X) marks the item of the model shown (ShownModel). Every other entry passes -// through unchanged. *clickedOut (when given) is set to true on a click on one of these items (the caller saves it). -template +// through unchanged. A click on a WrongGPU model is first written to the model choice record (`save(model)`); when that +// fails NOTHING changes (the selection, the mark, OptiScaler: no click is passed on) and the entry says it was not +// saved. *clickedOut (when given) is set to true on a click that took effect (the caller saves the selection). +template bool SelectableThunkLogic(SelFn&& sel, const char* label, bool selected, int flags, const void* size, PluginState& st, - bool* clickedOut = nullptr) { + SaveFn&& save, bool* clickedOut = nullptr) { if (clickedOut) *clickedOut = false; if (!IsFsr3xLabel(label)) return sel(label, selected, flags, size); const char model = ShownModel(st); @@ -100,12 +107,29 @@ bool SelectableThunkLogic(SelFn&& sel, const char* label, bool selected, int fla if (sel(EntryLabel(e, st).c_str(), selected && model == e.model, flags, size) && clicked == 1) clicked = e.model; if (sel(label, selected && model == kModelAmd, flags, size) && clicked == 1) clicked = kModelAmd; if (clicked == 1) return false; + if (clicked != kModelAmd) { + const Save r = save(clicked); + if (r != Save::Saved) { + st.refused.store(r == Save::Refused); + st.unsaved.store(clicked); + return false; + } + } + st.unsaved.store(0); + st.refused.store(false); st.model.store(clicked); st.shown.store(kShowSaved); // the player's click is the newest choice: it runs and is marked if (clickedOut) *clickedOut = true; return true; } +// The same without a model choice record to write (every click is saved). +template +bool SelectableThunkLogic(SelFn&& sel, const char* label, bool selected, int flags, const void* size, PluginState& st, + bool* clickedOut = nullptr) { + return SelectableThunkLogic(sel, label, selected, flags, size, st, [](char) { return Save::Saved; }, clickedOut); +} + // The BeginCombo thunk: when a WrongGPU model is shown and OptiScaler would show its FSR 3.X name as the closed // combo's preview, show the WrongGPU entry's name instead. `bc` is the real ImGui::BeginCombo(label, preview, flags). template diff --git a/clean/fsr/asi/exports_asi.def b/clean/fsr/asi/exports_asi.def index 04509e2f..fbd2a940 100644 --- a/clean/fsr/asi/exports_asi.def +++ b/clean/fsr/asi/exports_asi.def @@ -6,4 +6,3 @@ EXPORTS WrongGpuAsiQueryStatusV1 WrongGpuAsiSetChoiceRecordV1 WrongGpuAsiShowModelV1 - WrongGpuAsiPendingChoiceV1 diff --git a/clean/fsr/asi/wronggpu_asi.cpp b/clean/fsr/asi/wronggpu_asi.cpp index 9d982877..0b4edb9c 100644 --- a/clean/fsr/asi/wronggpu_asi.cpp +++ b/clean/fsr/asi/wronggpu_asi.cpp @@ -110,79 +110,33 @@ std::wstring RecordPath() { } // A click on one of the plugin's model entries: the record gets this model with the next seq (source=plugin), under the -// record's cross-process lock (model_choice_record.h). A click that cannot be written now stays pending: the menu says -// "not saved yet", the front end runs it this session (WrongGpuAsiPendingChoiceV1), and it is tried again (at each create -// and at most once a second while the menu is drawn) until it is written or a newer choice replaces it. At the end of the -// sequence numbers the click is refused, logged and said in the menu. -std::mutex g_pendingMutex; // g_pending, g_lastTry -wgchoice::Pending g_pending; -ULONGLONG g_lastTry = 0; - -void RecordModelChoice(char model) { +// game's state lock (model_choice_record.h; waited for 1 second at most, on the menu thread). A click that cannot be +// written is NOT kept: nothing changes, the menu says "not saved, try again" (SelectableThunkLogic) and the log says why. +// At the end of the sequence numbers the click is refused, logged and said in the menu. +wgasi::Save RecordModelChoice(char model) { const std::wstring path = RecordPath(); wgchoice::Record after; - wgchoice::Pending pending; std::string why; - std::lock_guard lock(g_pendingMutex); - const wgchoice::Outcome o = wgchoice::RecordChoice(path, model, wgchoice::Source::Plugin, &after, &why, &pending, 1000); - g_lastTry = GetTickCount64(); + const wgchoice::Outcome o = wgchoice::RecordChoice(path, model, wgchoice::Source::Plugin, &after, &why, nullptr, 1000); if (o == wgchoice::Outcome::Written) { - g_pending = wgchoice::Pending{}; - g_state.unsaved.store(0); - g_state.refused.store(false); AsiLog::Get().Writef("model choice record: Model %c (seq %llu, source=plugin)%s", model, static_cast(after.seq), why.empty() ? "" : ("; " + why).c_str()); - return; - } - if (o == wgchoice::Outcome::SeqExhausted) { - g_pending = wgchoice::Pending{}; - g_state.refused.store(true); - g_state.unsaved.store(model); - AsiLog::Get().Write(std::string("ERROR: model choice record ") + wgasi::Utf8(path) + ": " + wgchoice::OutcomeWords(o) + - ". Delete it or apply the model in the launcher."); - return; - } - g_pending = pending; - g_state.refused.store(false); - g_state.unsaved.store(model); - AsiLog::Get().Write(std::string("ERROR: model choice record ") + wgasi::Utf8(path) + ": Model " + model + " not written now (" + - wgchoice::OutcomeWords(o) + (why.empty() ? "" : ": " + why) + "); it runs this session and is tried again"); -} - -// Tries a pending click again. throttle: at most once a second (the menu thread); never waits on the lock long there. -void RetryPendingChoice(bool throttle) { - if (!g_state.unsaved.load() || g_state.refused.load()) return; - std::unique_lock lock(g_pendingMutex, std::try_to_lock); - if (!lock.owns_lock() || !g_pending.active()) return; - const ULONGLONG now = GetTickCount64(); - if (throttle && now - g_lastTry < 1000) return; - g_lastTry = now; - const char model = g_pending.model; - wgchoice::Record after; - std::string why; - const wgchoice::Outcome o = wgchoice::RetryPending(RecordPath(), &g_pending, &after, &why, throttle ? 50 : 1000); - if (o == wgchoice::Outcome::Written) { - g_state.unsaved.store(0); - AsiLog::Get().Writef("model choice record: Model %c written now (seq %llu, source=plugin)", model, static_cast(after.seq)); - } else if (o == wgchoice::Outcome::Superseded) { - g_state.unsaved.store(0); - AsiLog::Get().Writef("model choice record: Model %c (not written earlier) dropped: a newer choice was recorded meanwhile", model); - } else if (o == wgchoice::Outcome::SeqExhausted) { - g_state.refused.store(true); - AsiLog::Get().Write(std::string("ERROR: model choice record: Model ") + model + " refused: " + wgchoice::OutcomeWords(o)); + return wgasi::Save::Saved; } + AsiLog::Get().Write(std::string("ERROR: model choice record ") + wgasi::Utf8(path) + ": Model " + model + " not saved (" + + wgchoice::OutcomeWords(o) + (why.empty() ? "" : ": " + why) + "); nothing changed" + + (o == wgchoice::Outcome::SeqExhausted ? ". Delete the record or apply the model in the launcher." : ", try again")); + return o == wgchoice::Outcome::SeqExhausted ? wgasi::Save::Refused : wgasi::Save::NotSaved; } extern "C" bool WgSelectableThunk(const char* label, bool selected, int flags, const void* size) { - if (wgasi::IsFsr3xLabel(label)) RetryPendingChoice(true); bool ours = false; const bool clicked = wgasi::SelectableThunkLogic( [](const char* l, bool s, int f, const void* z) { return g_realSelectable(l, s, f, z); }, - label, selected, flags, size, g_state, &ours); - if (ours) { // a click on an entry of the FSR 3.X group (rare; on the menu thread) + label, selected, flags, size, g_state, [](char model) { return RecordModelChoice(model); }, &ours); + if (ours) { // a click that took effect on an entry of the FSR 3.X group (rare; on the menu thread) const char after = g_state.model.load(); SaveSelection(after); - if (after != wgasi::kModelAmd) RecordModelChoice(after); AsiLog::Get().Writef("selected: %s", after == wgasi::kModelAmd ? label : wgasi::LabelOf(after)); } return clicked; @@ -369,6 +323,10 @@ extern "C" __declspec(dllexport) __declspec(noinline) void InitializeASI() { std::call_once(g_initOnce, [caller] { g_diagnostics.Begin(); AsiLog::Get().Write("InitializeASI"); + // While the plugin is loaded in the game it keeps WrongGPU's loaded marker of the game folder open (wg_state.h): + // the launcher refuses an uninstall, repair or update meanwhile. Never released: the OS drops it with the process. + static wgstate::LoadedMarker* marker = new wgstate::LoadedMarker(wgasi::PluginDataDir()); + if (!marker->held()) AsiLog::Get().Writef("the loaded marker could not be created (error %lu)", marker->error()); Hook(caller); g_diagnostics.Complete(); }); @@ -376,7 +334,6 @@ extern "C" __declspec(dllexport) __declspec(noinline) void InitializeASI() { // The earlier query (ABI 1): an older front end knows 0, 'M' and 'K' only, so Model L reads as Model M there. extern "C" __declspec(dllexport) int WrongGpuAsiQuery(int* hooked, char* model) { - RetryPendingChoice(false); // the front end asks at each create: a click not written yet is tried again first if (hooked) *hooked = g_state.hooked.load() ? 1 : 0; if (model) { const char m = g_state.model.load(); @@ -396,11 +353,6 @@ extern "C" __declspec(dllexport) void WrongGpuAsiShowModelV1(char model) { if (model == wgasi::kShowSaved || model == wgasi::kModelAmd || wgasi::LabelOf(model)) g_state.shown.store(model); } -// A model click not written to the record yet (0: none). The front end runs it this session. -extern "C" __declspec(dllexport) char WrongGpuAsiPendingChoiceV1() { - return g_state.refused.load() ? 0 : g_state.unsaved.load(); -} - extern "C" __declspec(dllexport) int WrongGpuAsiQueryStatusV1(WrongGpuAsiStatusV1* status, uint32_t caller_size) { return g_diagnostics.Query(status, caller_size, g_state.hooked.load(), g_state.model.load()); } diff --git a/clean/fsr/include/wronggpu_host_event.h b/clean/fsr/include/wronggpu_host_event.h index 2aa9dfc5..ab693739 100644 --- a/clean/fsr/include/wronggpu_host_event.h +++ b/clean/fsr/include/wronggpu_host_event.h @@ -1,29 +1,35 @@ /* SPDX-License-Identifier: MIT */ #pragma once /* The event a host (the WrongGPU edition of OptiScaler) sends WrongGPU's front end (amd_fidelityfx_dx12.dll in the - * custom WrongGPU slot or next to the game) when the PLAYER selects one of the listed upscaler versions in its menu during - * the session. The host resolves this one export by name in the front-end DLL it loaded (GetProcAddress) and calls it - * with the selected entry's version id (from the list the front end returned to FFX_API_QUERY_DESC_TYPE_GET_VERSIONS), - * BEFORE it recreates the upscaler, so the new context runs the selected model. Only a player's selection is an event: a - * host never sends one for an index it read from its ini or applied at start. + * custom WrongGPU slot or next to the game) when the PLAYER selects one of the listed upscaler versions in its menu. The + * host resolves this one export by name in the front-end DLL it loaded (GetProcAddress) and calls it with the selected + * entry's version id (from the list the front end returned to FFX_API_QUERY_DESC_TYPE_GET_VERSIONS), BEFORE it recreates + * the upscaler. Only a player's selection is an event: a host never sends one for an index it read from its ini or applied + * at start. The export is an in-process call with no caller check: any code in the game's process could call it, as it + * could write the record itself; the record only ever holds a model choice, and the next create applies it. * * A selection of one of WrongGPU's model entries is written to the game's model choice record * (clean/fsr/src/model_choice_record.h, source=ffx) and decides the model from then on, until a newer choice (the * launcher's, the WrongGPU menu plugin's, or another selection). An AMD version or a Ray Reconstruction mode entry is no - * model choice. + * model choice. Re-selecting the entry that is already selected is a choice too (it wins over a newer choice made + * elsewhere). * - * Signature: int32_t WrongGpuHostSelectedV1(uint64_t versionId). Callable from any thread; it takes the record's - * cross-process lock for a few milliseconds at most (3 s when another process holds it). */ + * Signature: int32_t WrongGpuHostSelectedV1(uint64_t versionId). Callable from any thread; it takes the game's state lock + * for a few milliseconds (3 s at most when another WrongGPU program holds it). Nothing is ever kept for later: a choice + * that is not saved changes nothing. */ #include #define WRONGGPU_HOST_SELECTED_EXPORT "WrongGpuHostSelectedV1" -#define WG_HOST_SELECTED_RECORDED 1 /* a WrongGPU model: written to the record */ -#define WG_HOST_SELECTED_SESSION_ONLY 2 /* a WrongGPU model, no record for this game (no launcher state folder): this session */ -#define WG_HOST_SELECTED_NOT_A_MODEL 0 /* an AMD version or an RR mode entry: nothing recorded */ -#define WG_HOST_SELECTED_PENDING -1 /* not written yet (the record is busy or a write failed): used this session and - written at the next create; the front end's log says why. Hosts show it. */ -#define WG_HOST_SELECTED_REFUSED -2 /* the record's sequence number is at its end: refused (logged). Hosts show it. */ -#define WG_HOST_SELECTED_NOT_READY -3 /* the front end is not hosted or not initialised */ +#define WG_HOST_SELECTED_RECORDED 1 /* recorded, and this model runs from now on instead of another: recreate the + upscaler (also when the entry was already selected) */ +#define WG_HOST_SELECTED_NOTHING_CHANGED 0 /* nothing changes in what runs: an AMD version or an RR mode entry, a model + that already ran (recorded again), or a game without a record (no launcher + state folder: the host's entry decides, as before) */ +#define WG_HOST_SELECTED_NOT_SAVED -1 /* not saved (the record busy or unreadable, or a failed write): nothing changes + and nothing is kept; the host says "not saved, try again" and does not + recreate the upscaler */ +#define WG_HOST_SELECTED_REFUSED -2 /* the record's sequence number is at its end: refused (logged); as NOT_SAVED */ +#define WG_HOST_SELECTED_NOT_READY -3 /* the front end is not hosted or not initialised; as NOT_SAVED */ typedef int32_t (*PfnWrongGpuHostSelectedV1)(uint64_t versionId); diff --git a/clean/fsr/src/asi_bridge.cpp b/clean/fsr/src/asi_bridge.cpp index eb022f6e..84c86eb2 100644 --- a/clean/fsr/src/asi_bridge.cpp +++ b/clean/fsr/src/asi_bridge.cpp @@ -38,11 +38,4 @@ void SetAsiChoiceRecord(const std::wstring& path) { set(path.c_str()); } -char QueryAsiPending() { - HMODULE m = GetModuleHandleW(WRONGGPU_ASI_MODULE); - if (!m) return 0; - auto pending = reinterpret_cast(reinterpret_cast(GetProcAddress(m, WRONGGPU_ASI_PENDING_CHOICE))); - return pending ? pending() : 0; -} - } // namespace wgwin diff --git a/clean/fsr/src/asi_bridge.h b/clean/fsr/src/asi_bridge.h index 4ed58622..739d3312 100644 --- a/clean/fsr/src/asi_bridge.h +++ b/clean/fsr/src/asi_bridge.h @@ -16,7 +16,4 @@ void ShowAsiModel(char model); // Tells the plugin where the game's model choice record is (src/model_choice_record.h). Nothing without the plugin. void SetAsiChoiceRecord(const std::wstring& path); -// The plugin's model click that it could not write to the record yet (it tries again), else 0 (also without the plugin). -char QueryAsiPending(); - } // namespace wgwin diff --git a/clean/fsr/src/dllmain.cpp b/clean/fsr/src/dllmain.cpp index 4fbdb5ee..145d20e7 100644 --- a/clean/fsr/src/dllmain.cpp +++ b/clean/fsr/src/dllmain.cpp @@ -240,20 +240,33 @@ FrontEnd& Get() { // mode as before. p.asiPlugin = [](char* model) { return QueryAsiPlugin(model); }; p.asiShowModel = [](char model) { ShowAsiModel(model); }; - p.asiPending = [] { return QueryAsiPending(); }; - { - const std::wstring& ini = Place().ini; - const size_t slash = ini.find_last_of(L"\\/"); - const std::filesystem::path record = - wgchoice::RecordPathIn(slash == std::wstring::npos ? std::wstring(L".") : ini.substr(0, slash)); - std::error_code ec; - if (std::filesystem::is_directory(record.parent_path(), ec)) { // a launcher install: its state folder - p.choiceRecord = record; - SetAsiChoiceRecord(record.wstring()); // the plugin writes its menu's model clicks there too - SetHostIniPollModels(false); // the host's stored index is no model choice (the record decides) - } else { - L().Write("model choice: no launcher state folder next to wronggpu.ini: no model choice record (the model item decides)"); + } + // The game's model choice record (model_choice_record.h, in the game's WrongGPU state folder next to wronggpu.ini) + // decides the WrongGPU model on every route; the plugin writes its menu's model clicks there too. Without the + // state folder (no launcher install): no record, as before. + { + const std::wstring ini = Place().ini; + const size_t slash = ini.find_last_of(L"\\/"); + const std::filesystem::path record = + wgchoice::RecordPathIn(slash == std::wstring::npos ? std::wstring(L".") : ini.substr(0, slash)); + std::error_code ec; + if (std::filesystem::is_directory(record.parent_path(), ec)) { // a launcher install: its state folder + // While this DLL is loaded the game keeps WrongGPU's loaded marker open (wg_state.h): the launcher refuses + // an uninstall, repair or update meanwhile. Never released: the OS drops it with the process. + static wgstate::LoadedMarker* marker = new wgstate::LoadedMarker(wgchoice::GameDirOf(record).wstring()); + if (!marker->held()) L().Write("model choice: the loaded marker could not be created (error %lu)", marker->error()); + p.choiceRecord = record; + p.readWronggpuIni = [ini] { // the upgrade migration reads wronggpu.ini's model item under the state lock + std::string text; + wgstate::ReadBytes(ini, &text); + return text; + }; + if (g_hosted) { + SetAsiChoiceRecord(record.wstring()); + SetHostIniPollModels(false); // the host's stored index is no model choice (the record decides) } + } else { + L().Write("model choice: no launcher state folder next to wronggpu.ini: no model choice record (the model item decides)"); } } p.menu = Menu(); diff --git a/clean/fsr/src/frontend.cpp b/clean/fsr/src/frontend.cpp index 05c2affd..bbc4ef2f 100644 --- a/clean/fsr/src/frontend.cpp +++ b/clean/fsr/src/frontend.cpp @@ -579,7 +579,7 @@ ffxReturnCode_t FrontEnd::CreateUpscale(ffxContext* context, ffxCreateContextDes bool forceAmd = false; if (asiHooked) { std::string why; - char model = asiModel != 0 ? ChooseModel(asiModel, platform_.asiPending ? platform_.asiPending() : 0, 0, tag, &why) : 0; + char model = asiModel != 0 ? ChooseModel(asiModel, 0, tag, &why) : 0; if (asiModel != 0) { const int32_t m = ModelOfName(std::string(1, model)); const WgEntryDef* sr = m >= 0 ? SrEntryOfModel(m) : nullptr; @@ -655,8 +655,22 @@ ffxReturnCode_t FrontEnd::CreateUpscale(ffxContext* context, ffxCreateContextDes } u->hasOverride = false; // WrongGPU's own id means nothing to AMD's DLL (fallback, comparison) } - // No entry chose the model (direct route, no override, an id WrongGPU did not list): sr_model when it is set in - // the shared block, the environment or wronggpu.ini; otherwise runtime_options / the runtime's default as before. + // No entry chose the model (direct route, no override, an id WrongGPU did not list): with a model choice record (a + // launcher install) the record's model (ChooseModel); else sr_model when it is set in the shared block, the + // environment or wronggpu.ini; otherwise runtime_options / the runtime's default as before. + if (!forceAmd && !u->selectedModel && !u->modelOption && !platform_.choiceRecord.empty()) { + std::string why; + const int32_t model = ModelOfName(std::string(1, ChooseModel(0, 0, tag, &why))); + if (const WgEntryDef* sr = model >= 0 ? SrEntryOfModel(model) : nullptr) { + u->selectedModel = kWgModelRows[model].name[0]; + u->modelOption = kWgModelRows[model].runtime_option; + u->modelProviderId = sr->id; + u->modelProviderName = EntryProviderName(*sr); + Log(tag + " model choice: Model " + u->selectedModel + " (" + why + ")"); + } else { + LogOnce(tag, "note: model choice: that model is not part of this build of the front end; the configured model is used"); + } + } if (!forceAmd && !u->selectedModel && !u->modelOption) { int32_t model = -1; std::string described; @@ -1399,82 +1413,80 @@ void FrontEnd::LogOnce(const std::string& tag, const std::string& line) { Log(tag + " " + line); } -char FrontEnd::ChooseModel(char plugin, char pluginPending, char entry, const std::string& tag, std::string* why) { - const char launcher = LauncherModel(); +char FrontEnd::WronggpuIniModel() const { + if (!platform_.readWronggpuIni) return LauncherModel(); + std::string warnings; + const Config c = ParseConfig(platform_.readWronggpuIni(), &warnings); + bool found = false; + const std::string v = OptionValue(c.runtimeOptions, "model", &found); + if (!found || v.size() != 1) return 0; + const char m = char(std::toupper(static_cast(v[0]))); + return wgchoice::IsModel(m) ? m : 0; +} + +char FrontEnd::ChooseModel(char plugin, char entry, const std::string& tag, std::string* why) { const std::filesystem::path& path = platform_.choiceRecord; - std::lock_guard lock(choiceMutex_); - // without a record: a host selection made this session, the host's entry, the launcher's K / L item, the plugin's - // saved WrongGPU entry (0.6.0's rule), Model M - auto noRecord = [&](const std::string& reason) { - if (wgchoice::IsModel(sessionChoice_)) { - *why = reason + "; selected in OptiScaler's upscaler list this session"; - return sessionChoice_; - } + if (path.empty()) { + // no launcher state folder (a hand install): as before 0.6.5 + const char launcher = LauncherModel(); if (wgchoice::IsModel(entry)) { - *why = reason + "; the host's entry"; + *why = "no model choice record; the host's entry"; return entry; } if (launcher == 'K' || launcher == 'L') { - *why = reason + "; the launcher's model item, wronggpu.ini model=" + launcher; + *why = std::string("no model choice record; the launcher's model item, wronggpu.ini model=") + launcher; return launcher; } if (wgchoice::IsModel(plugin)) { - *why = reason + "; the plugin's saved entry"; + *why = "no model choice record; the plugin's saved entry"; return plugin; } - *why = launcher ? reason + "; wronggpu.ini model=" + launcher : reason + "; the default"; + *why = launcher ? std::string("no model choice record; wronggpu.ini model=") + launcher : std::string("no model choice record; the default"); return 'M'; - }; - if (path.empty()) return noRecord("no model choice record"); - // A host selection that could not be written when it was made: tried again (dropped when a newer choice exists). - if (hostPending_.active()) { - const char model = hostPending_.model; - wgchoice::Record after; - std::string err; - const wgchoice::Outcome o = wgchoice::RetryPending(path, &hostPending_, &after, &err); - if (o == wgchoice::Outcome::Written) - Log(tag + " model choice: Model " + model + " (selected in OptiScaler's upscaler list earlier) written now (seq " + - std::to_string(after.seq) + ")"); - else if (o == wgchoice::Outcome::Superseded) - Log(tag + " model choice: Model " + model + " (selected in OptiScaler's upscaler list earlier, not written then) is " - "dropped: a newer choice was recorded meanwhile"); - else if (o == wgchoice::Outcome::SeqExhausted) - Log(tag + " ERROR: model choice: Model " + model + " selected in OptiScaler's upscaler list is refused: " + wgchoice::OutcomeWords(o)); - if (hostPending_.active()) { - LogOnce(tag, std::string("ERROR: model choice: Model ") + model + " (selected in OptiScaler's upscaler list) still cannot be " - "written (" + wgchoice::OutcomeWords(o) + (err.empty() ? "" : ": " + err) + "); it runs this session, tried again at each create"); - *why = "selected in OptiScaler's upscaler list this session, not saved yet"; - return model; - } - } - if (wgchoice::IsModel(pluginPending)) { - *why = "the plugin's click this session, not saved yet (the plugin tries again)"; - return pluginPending; } + std::lock_guard lock(choiceMutex_); + // the record cannot be used now: the last record this session read or wrote, else wronggpu.ini's model item, else M + // (never the host's stored entry) + auto fallback = [&](const std::string& reason) { + if (wgchoice::IsModel(lastChoice_)) { + *why = reason + "; the last model choice read this session"; + return lastChoice_; + } + const char ini = LauncherModel(); + *why = ini ? reason + "; wronggpu.ini model=" + ini : reason + "; the default"; + return ini ? ini : 'M'; + }; wgchoice::Record rec; bool migrated = false; std::string err; - const wgchoice::ReadResult rr = wgchoice::LoadOrMigrateRecord(path, launcher, &rec, &migrated, &err); - if (rr == wgchoice::ReadResult::Corrupt) { - LogOnce(tag, "model choice: the record (wronggpu-setup\\model-choice.ini) is corrupt (" + err + "): treated as no choice until the next choice replaces it"); - return noRecord("the model choice record is corrupt"); - } - if (rr == wgchoice::ReadResult::Unreadable) { + const wgchoice::LoadResult lr = + wgchoice::LoadOrMigrateRecord(path, [this] { return WronggpuIniModel(); }, &rec, &migrated, &err); + switch (lr) { + case wgchoice::LoadResult::Ok: break; + case wgchoice::LoadResult::Corrupt: + LogOnce(tag, "model choice: the record (wronggpu-setup\\model-choice.ini) is corrupt (" + err + "): not used until the next choice replaces it"); + return fallback("the model choice record is corrupt"); + case wgchoice::LoadResult::Unreadable: // (never written over: a record held open for a moment must not be replaced by a guess) - LogOnce(tag, "model choice: the record (wronggpu-setup\\model-choice.ini) cannot be read (" + err + "): treated as no record"); - return noRecord("the model choice record cannot be read"); - } - if (rr == wgchoice::ReadResult::Missing) { + LogOnce(tag, "model choice: the record (wronggpu-setup\\model-choice.ini) cannot be read (" + err + ")"); + return fallback("the model choice record cannot be read"); + case wgchoice::LoadResult::NoLock: + Log(tag + " model choice: the record was not read (" + err + ")"); + return fallback("the model choice record was busy"); + case wgchoice::LoadResult::Missing: LogOnce(tag, "ERROR: model choice: no record yet, and it could not be written (" + err + ")"); - return noRecord("no model choice record (not written)"); + return fallback("no model choice record (not written)"); } + lastChoice_ = rec.model; if (migrated) - Log(tag + " model choice: no record yet (an install from before 0.6.5): Model " + rec.model + " from " + - (launcher ? std::string("wronggpu.ini's model item") : std::string("the default")) + " recorded (seq 1, source=launcher)"); + Log(tag + " model choice: no record yet (an install from before 0.6.5): Model " + rec.model + + " from wronggpu.ini's model item (or the default) recorded (seq 1, source=launcher)"); *why = std::string("the model choice record: ") + wgchoice::SourceWords(rec.source) + ", seq " + std::to_string(rec.seq); + const char launcher = LauncherModel(); if (launcher && launcher != rec.model) - LogOnce(tag, std::string("model choice conflict: wronggpu.ini's model item says Model ") + launcher + "; the more recent choice, Model " + - rec.model + " from " + wgchoice::SourceWords(rec.source) + " (seq " + std::to_string(rec.seq) + "), runs"); + LogOnce(tag, std::string("model choice: wronggpu.ini's model item (the install's default) says Model ") + launcher + + "; the model choice record says Model " + rec.model + " (" + wgchoice::SourceWords(rec.source) + ", seq " + + std::to_string(rec.seq) + "), which runs"); return rec.model; } @@ -1484,35 +1496,34 @@ int32_t FrontEnd::HostSelected(uint64_t versionId) { if (!e || e->slot != WG_OPT_SR_MODEL || e->value < 0 || e->value >= WG_SR_MODEL_COUNT) { Log(tag + " the player selected " + (e ? std::string(EntryProviderName(*e)) : "version " + Hex(versionId)) + " in OptiScaler's upscaler list: no WrongGPU model choice"); - return WG_HOST_SELECTED_NOT_A_MODEL; + return WG_HOST_SELECTED_NOTHING_CHANGED; } const char model = kWgModelRows[e->value].name[0]; - std::lock_guard lock(choiceMutex_); if (platform_.choiceRecord.empty()) { - sessionChoice_ = model; + // no launcher state folder: no record to write; the host's entry decides at the next create (as before 0.6.5) Log(tag + " the player selected Model " + model + " in OptiScaler's upscaler list; no model choice record (no launcher " - "state folder): it runs this session"); - return WG_HOST_SELECTED_SESSION_ONLY; + "state folder): the host's entry decides"); + return WG_HOST_SELECTED_NOTHING_CHANGED; } - wgchoice::Record after; - wgchoice::Pending pending; + std::lock_guard lock(choiceMutex_); + wgchoice::Record after, before; std::string err; - const wgchoice::Outcome o = wgchoice::RecordChoice(platform_.choiceRecord, model, wgchoice::Source::Ffx, &after, &err, &pending); + const wgchoice::Outcome o = wgchoice::RecordChoice(platform_.choiceRecord, model, wgchoice::Source::Ffx, &after, &err, &before); if (o == wgchoice::Outcome::Written) { - hostPending_ = wgchoice::Pending{}; + const char was = wgchoice::IsModel(before.model) ? before.model : lastChoice_; + lastChoice_ = model; Log(tag + " the player selected Model " + model + " in OptiScaler's upscaler list: recorded (seq " + std::to_string(after.seq) + ", source=ffx)" + (err.empty() ? "" : "; " + err)); - return WG_HOST_SELECTED_RECORDED; + return was == model ? WG_HOST_SELECTED_NOTHING_CHANGED : WG_HOST_SELECTED_RECORDED; } if (o == wgchoice::Outcome::SeqExhausted) { Log(tag + " ERROR: the player selected Model " + model + " in OptiScaler's upscaler list: " + wgchoice::OutcomeWords(o) + ". Delete wronggpu-setup\\model-choice.ini or apply the model in the launcher."); return WG_HOST_SELECTED_REFUSED; } - hostPending_ = pending; - Log(tag + " ERROR: the player selected Model " + model + " in OptiScaler's upscaler list, but " + wgchoice::OutcomeWords(o) + - (err.empty() ? "" : " (" + err + ")") + ": it runs this session and is written at the next create"); - return WG_HOST_SELECTED_PENDING; + Log(tag + " ERROR: the player selected Model " + model + " in OptiScaler's upscaler list, but it was not saved: " + + wgchoice::OutcomeWords(o) + (err.empty() ? "" : " (" + err + ")") + ". Nothing changes; select it again."); + return WG_HOST_SELECTED_NOT_SAVED; } void FrontEnd::ApplyEntry(const WgEntryDef& e, UpscaleContext& u, const std::string& tag, const char* source) { @@ -1527,7 +1538,7 @@ void FrontEnd::ApplyEntry(const WgEntryDef& e, UpscaleContext& u, const std::str if (config_.hosted && !platform_.choiceRecord.empty() && std::strcmp(source, "folder") != 0) { std::string why; const char entry = model >= 0 && model < WG_SR_MODEL_COUNT ? kWgModelRows[model].name[0] : 0; - const char chosen = ChooseModel(0, platform_.asiPending ? platform_.asiPending() : 0, entry, tag, &why); + const char chosen = ChooseModel(0, entry, tag, &why); const int32_t m = ModelOfName(std::string(1, chosen)); if (m >= 0 && SrEntryOfModel(m)) { if (m != model) diff --git a/clean/fsr/src/frontend.h b/clean/fsr/src/frontend.h index d0cac871..f7f6ac1c 100644 --- a/clean/fsr/src/frontend.h +++ b/clean/fsr/src/frontend.h @@ -95,11 +95,12 @@ struct Platform { std::function asiPlugin; // Tells the plugin which model the context runs (0 AMD, 'M', 'K', 'L'), so its menu marks that entry. May be empty. std::function asiShowModel; - // The plugin's model click that could not be written to the record yet (it retries), else 0. May be empty. - std::function asiPending; // The game's model choice record (model_choice_record.h: wronggpu-setup\model-choice.ini next to wronggpu.ini), read // and written with real files. Empty: no record (the launcher's model item decides, as before). std::filesystem::path choiceRecord; + // wronggpu.ini's text as it is on disk now (the record's upgrade migration reads its model item while it holds the + // game's state lock). Empty: the model item of the configuration read at start. + std::function readWronggpuIni; // Registry options and the menu's choices (shared settings block). Empty members: defaults, nothing written. MenuSettings menu; }; @@ -164,10 +165,11 @@ class FrontEnd { size_t OwnContextCount(); // for tests bool HasParked(); // for tests - // The host tells the front end that the PLAYER selected the listed version `versionId` in its upscaler list during - // this session (the WrongGPU edition of OptiScaler calls the exported WrongGpuHostSelectedV1 before it recreates the - // upscaler). One of WrongGPU's SR model entries is a model choice: written to the model choice record (source=ffx). - // Returns kHostSelected* (wronggpu_host_event.h). + // The host tells the front end that the PLAYER selected the listed version `versionId` in its upscaler list (the + // WrongGPU edition of OptiScaler calls the exported WrongGpuHostSelectedV1, before it would recreate the upscaler). + // One of WrongGPU's SR model entries is a model choice: written to the model choice record (source=ffx). Returns + // WG_HOST_SELECTED_* (include/wronggpu_host_event.h): 1 this model runs from now on (recreate), 0 nothing changed, + // negative not saved (nothing changes, the host says "not saved, try again"). int32_t HostSelected(uint64_t versionId); struct UpscaleContext; @@ -219,15 +221,16 @@ class FrontEnd { bool ConfiguredModel(int32_t* model, std::string* described); // The model the launcher's wronggpu.ini names (the last model item of runtime_options: 'M', 'K', 'L'), else 0. char LauncherModel() const; - // The WrongGPU model a hosted create runs (with the plugin hooked, or for a host entry naming a WrongGPU model): a - // choice made this session that could not be saved yet (the host's, tried again first, or the plugin's, - // `pluginPending`), else the model choice record's (a game without one gets one from wronggpu.ini's model item, - // else Model M: LoadOrMigrateRecord). The entry OptiScaler's list stores is never taken for a choice while there is - // a record. Without one (no launcher state folder, or a record that cannot be read or is corrupt): a host selection - // made this session, else the host's entry (`entry`, 0 for none; how the custom slot chose before 0.6.5), else the - // launcher's model item when it names Model K or L, else the plugin's saved WrongGPU entry (`plugin`; what decided - // before 0.6.5), else Model M. *why: which choice decided, for the log. - char ChooseModel(char plugin, char pluginPending, char entry, const std::string& tag, std::string* why); + // The WrongGPU model a create runs. With a record path (a launcher install, model_choice_record.h): the record's + // model (a game without one gets one from wronggpu.ini's model item, read under the game's state lock, else Model + // M: LoadOrMigrateRecord); when the record cannot be read, is corrupt or its lock is not taken in time: the last + // record this session read or wrote (lastChoice_), else wronggpu.ini's model item, else Model M; NEVER the host's + // stored entry. Without a record path (no launcher state folder: a hand install, as before 0.6.5): the host's entry + // (`entry`, 0 for none), else the launcher's model item when it names Model K or L, else the plugin's saved WrongGPU + // entry (`plugin`), else Model M. *why: which choice decided, for the log. + char ChooseModel(char plugin, char entry, const std::string& tag, std::string* why); + // wronggpu.ini's model item as it is on disk now (readWronggpuIni), else as read at start ('M', 'K', 'L' or 0). + char WronggpuIniModel() const; // `line` logged once per session (after `tag`). void LogOnce(const std::string& tag, const std::string& line); // AMD's DLL behind a forwarded context (the one that created it), else AMD's original. @@ -290,9 +293,8 @@ class FrontEnd { uint32_t inputRefusedRun_ = 0; // refusals in a row with that key (mutex_) std::atomic inputRefusedAny_{false}; // inputRefusedRun_ > 0 (the taken-frame path's cheap check) std::map modelLogged_; // ApplyModelDir: each distinct choice logged once (mutex_) - std::mutex choiceMutex_; // ChooseModel / HostSelected: hostPending_ and sessionChoice_ - wgchoice::Pending hostPending_; // a host selection not written yet (tried again at each create) - char sessionChoice_ = 0; // a host selection without a record (no launcher state folder) + std::mutex choiceMutex_; // ChooseModel / HostSelected: lastChoice_ + char lastChoice_ = 0; // the model of the last record read or written this session std::atomic reentered_{0}; // calls refused because they re-entered this front end on one thread std::mutex parkMutex_; // guards the three below; held while a parked context is destroyed UpscaleContext* parked_ = nullptr; diff --git a/clean/fsr/src/model_choice_record.h b/clean/fsr/src/model_choice_record.h index 45d4f2cb..16bcb027 100644 --- a/clean/fsr/src/model_choice_record.h +++ b/clean/fsr/src/model_choice_record.h @@ -1,53 +1,50 @@ // SPDX-License-Identifier: MIT #pragma once -// The model choice record (0.6.5): ONE small file per game, wronggpu-setup\model-choice.ini in the folder of the front -// end's wronggpu.ini (the launcher's state folder: an uninstall removes it by that name, a reinstall keeps it with the -// game's settings; without that folder there is no record). It decides which WrongGPU model runs. Three places write it, -// each only for an EVENT, a choice the player made: +// The model choice record (0.6.5): ONE small file per game, model-choice.ini in the game's WrongGPU state folder +// (clean/wgshared/include/wg_state.h: \wronggpu-setup, beside settings.ini; always WrongGPU's: an uninstall +// removes it, a repair, update or reinstall keeps it; without that folder there is no record). It decides which WrongGPU +// model runs, on every route; wronggpu.ini's model item is the install's default, which no WrongGPU program rewrites +// after the install and which only seeds the record of a game that has none (the upgrade below). Three places write the +// record, each only for an EVENT, a choice the player made: // - the launcher, when it applies a model (`WrongGPU.exe set model=`, or a change of the model item); it then // sets OptiScaler's UpscalerIndex to that model's entry, for display only; // - the front end, when OptiScaler tells it that the player selected one of WrongGPU's entries in its upscaler list // during the session (the WrongGPU edition of OptiScaler calls WrongGpuHostSelectedV1 in the front-end DLL); the // stored index OptiScaler passes at a create is never taken for a choice; // - the WrongGPU menu plugin (clean/fsr/asi), when the player clicks one of its model entries. -// "Most recent" is the highest sequence number. Every read-modify-write (read, seq + 1, write) runs under ONE lock per -// game shared by all processes (a named mutex, Local\WrongGPU-choice-), so no update is -// lost and seq never goes back. No clock is involved. +// "Most recent" is the highest sequence number. Every read-modify-write (read, seq + 1, write) runs under the game's +// state lock (wgstate::StateLock, one named mutex per game folder, shared by every WrongGPU program and by settings.ini's +// writers), so no update is lost and seq never goes back. No clock is involved. // // The file, strictly (anything else is CORRUPT: logged and treated as "no choice", never as a partial one): // ; comment lines and blank lines // model= // seq=<1..18446744073709551615> (decimal digits only, overflow refused) // source= -// each key exactly once, no other key, no spaces around '='. Writes: a temporary file in the same folder, written in full -// and flushed (both checked), then MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH) over the record (checked). Readers take -// the lock too, so a reader never sees part of a record. A temporary file a crash left behind is never read. +// each key exactly once, no other key, no spaces around '='. Writes: wgstate::WriteAtomic (a temporary file in the same +// folder, written and flushed, then MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH), every step checked), tried up to 3 +// times. Readers take the lock too, so a reader never sees part of a record. A temporary file a crash left behind is +// never read. // // Upgrade: a game without a record gets one from the launcher's existing choice (wronggpu.ini's model item, else Model M): -// seq 1, source=launcher (MigrateRecord). The model is never taken from OptiScaler's stored index. +// seq 1, source=launcher, read and written under the lock (LoadOrMigrateRecord). The model is never taken from OptiScaler's +// stored index. A choice that cannot be saved (the lock not taken in time, an unreadable record, a failed write) is not +// kept for later: its writer says "not saved, try again" and the model that runs does not change. #include #include #include -#include -#include #include -#ifdef _WIN32 -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include -#endif +#include "../../wgshared/include/wg_state.h" // the state folder, its lock, atomic writes (shared with settings.ini) namespace wgchoice { -constexpr const wchar_t* kStateFolder = L"wronggpu-setup"; // the launcher's state folder (installer kStateDirName) -constexpr const wchar_t* kRecordFile = L"model-choice.ini"; -// The record of the game whose wronggpu.ini is in `iniDir`. -inline std::filesystem::path RecordPathIn(const std::filesystem::path& iniDir) { return iniDir / kStateFolder / kRecordFile; } +constexpr const wchar_t* kStateFolder = wgstate::kStateFolder; // wronggpu-setup +constexpr const wchar_t* kRecordFile = wgstate::kModelChoiceFile; +// The record of the game whose WrongGPU files (wronggpu.ini, the state folder) are in `gameDir`. +inline std::filesystem::path RecordPathIn(const std::filesystem::path& gameDir) { return gameDir / kStateFolder / kRecordFile; } +// The game folder of a record (the folder holding its state folder): the game's state lock is taken on it. +inline std::filesystem::path GameDirOf(const std::filesystem::path& record) { return record.parent_path().parent_path(); } enum class Source { Launcher, Ffx, Plugin }; @@ -132,61 +129,17 @@ inline std::string FormatRecord(const Record& r) { // ---- the lock ------------------------------------------------------------------------------------------------------- -// The lock's name for a record: Local\WrongGPU-choice-. -// The launcher, the front end and the plugin (different processes and modules) derive the same name from the same file. -inline std::wstring LockName(const std::filesystem::path& record) { - std::wstring full = record.wstring(); -#ifdef _WIN32 - wchar_t buf[1024]; - const DWORD n = GetFullPathNameW(full.c_str(), 1024, buf, nullptr); - if (n > 0 && n < 1024) full.assign(buf, n); -#endif - uint64_t h = 1469598103934665603ull; - for (wchar_t c : full) { - if (c == L'/') c = L'\\'; - if (c >= L'A' && c <= L'Z') c = wchar_t(c - L'A' + L'a'); - h ^= uint64_t(uint16_t(c)); - h *= 1099511628211ull; - } - wchar_t hex[17]; - for (int i = 15; i >= 0; --i, h >>= 4) hex[i] = L"0123456789abcdef"[h & 15]; - hex[16] = 0; - return std::wstring(L"Local\\WrongGPU-choice-") + hex; -} - -// Holds the record's lock for its lifetime. ok(): taken (within `timeoutMs`). An abandoned lock (a holder that died) is -// taken over: the record on disk is whole either way (atomic replacement). +// Holds the game's state lock (wgstate::StateLock on the record's game folder) for its lifetime. ok(): taken within +// `timeoutMs`. An abandoned lock (a holder that died) is taken over: the files are whole either way (atomic replacement). class Lock { public: - explicit Lock(const std::filesystem::path& record, unsigned timeoutMs = 3000) { -#ifdef _WIN32 - handle_ = CreateMutexW(nullptr, FALSE, LockName(record).c_str()); - if (!handle_) return; - const DWORD w = WaitForSingleObject(handle_, timeoutMs); - ok_ = w == WAIT_OBJECT_0 || w == WAIT_ABANDONED; -#else - (void)record; - (void)timeoutMs; - ok_ = true; -#endif - } - ~Lock() { -#ifdef _WIN32 - if (handle_) { - if (ok_) ReleaseMutex(handle_); - CloseHandle(handle_); - } -#endif - } - bool ok() const { return ok_; } + explicit Lock(const std::filesystem::path& record, unsigned timeoutMs = 3000) : lock_(GameDirOf(record).wstring(), timeoutMs) {} + bool ok() const { return lock_.held(); } Lock(const Lock&) = delete; Lock& operator=(const Lock&) = delete; private: - bool ok_ = false; -#ifdef _WIN32 - HANDLE handle_ = nullptr; -#endif + wgstate::StateLock lock_; }; // ---- files ---------------------------------------------------------------------------------------------------------- @@ -196,7 +149,6 @@ enum class ReadResult { Missing, Ok, Corrupt, Unreadable }; // Reads the record (call it under the record's Lock). inline ReadResult ReadRecordFile(const std::filesystem::path& path, Record* out, std::string* why) { std::string text; -#ifdef _WIN32 HANDLE h = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (h == INVALID_HANDLE_VALUE) { @@ -218,94 +170,31 @@ inline ReadResult ReadRecordFile(const std::filesystem::path& path, Record* out, return ReadResult::Corrupt; } text.assign(buf, got); -#else - std::error_code ec; - if (!std::filesystem::exists(path, ec)) return ReadResult::Missing; - std::ifstream f(path, std::ios::binary); - if (!f) { - if (why) *why = "cannot open"; - return ReadResult::Unreadable; - } - std::ostringstream s; - s << f.rdbuf(); - text = s.str(); - if (text.size() >= 2048) { - if (why) *why = "larger than a record"; - return ReadResult::Corrupt; - } -#endif return ParseRecord(text, out, why) ? ReadResult::Ok : ReadResult::Corrupt; } -// Atomic replace: a temporary file next to the record (its name ends in .tmp; never read), written in full and flushed -// (both checked), then MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH) over the record (checked). Up to `attempts` tries, -// 20 ms apart. false with *why. Call it under the record's Lock. +// The atomic replace of the record (wgstate::WriteAtomic: a temporary file in the same folder, flushed, then +// MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH), every step checked; the temporary file deleted when a step fails), tried +// up to `attempts` times, 20 ms apart. false with *why. Call it under the record's Lock. inline bool WriteRecordFile(const std::filesystem::path& path, const Record& r, std::string* why, int attempts = 3) { const std::string text = FormatRecord(r); - std::string last; + DWORD err = 0; for (int i = 0; i < attempts; ++i) { -#ifdef _WIN32 - const std::wstring tmp = path.wstring() + L"." + std::to_wstring(GetCurrentProcessId()) + L"." + - std::to_wstring(GetTickCount64()) + L"." + std::to_wstring(i) + L".tmp"; - HANDLE h = CreateFileW(tmp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); - if (h == INVALID_HANDLE_VALUE) { - last = "cannot create the temporary file (Windows error " + std::to_string(GetLastError()) + ")"; - } else { - DWORD written = 0; - const bool wrote = WriteFile(h, text.data(), DWORD(text.size()), &written, nullptr) && written == text.size(); - const bool flushed = wrote && FlushFileBuffers(h); - const DWORD flushError = flushed ? 0 : GetLastError(); - const bool closed = CloseHandle(h) != 0; - if (!wrote) { - last = "cannot write the temporary file"; - DeleteFileW(tmp.c_str()); - } else if (!flushed) { - last = "cannot flush the temporary file (Windows error " + std::to_string(flushError) + ")"; - DeleteFileW(tmp.c_str()); - } else if (!closed) { - last = "cannot close the temporary file"; - DeleteFileW(tmp.c_str()); - } else if (MoveFileExW(tmp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { - return true; - } else { - last = "cannot replace the record (Windows error " + std::to_string(GetLastError()) + ")"; - DeleteFileW(tmp.c_str()); - } - } + if (wgstate::WriteAtomic(path.wstring(), text, &err)) return true; if (i + 1 < attempts) Sleep(20); -#else - const std::filesystem::path tmp = path.string() + "." + std::to_string(i) + ".tmp"; - { - std::ofstream f(tmp, std::ios::binary | std::ios::trunc); - f.write(text.data(), std::streamsize(text.size())); - f.flush(); - if (!f) { - last = "cannot write the temporary file"; - std::error_code ec; - std::filesystem::remove(tmp, ec); - continue; - } - } - std::error_code ec; - std::filesystem::rename(tmp, path, ec); - if (!ec) return true; - last = "cannot replace the record"; - std::filesystem::remove(tmp, ec); -#endif } - if (why) *why = last; + if (why) *why = "cannot replace the record (Windows error " + std::to_string(err) + ")"; return false; } // ---- the operations, each one read-modify-write under the lock ------------------------------------------------------ -enum class Outcome { Written, NoLock, Unreadable, SeqExhausted, WriteFailed, Superseded }; +enum class Outcome { Written, NoLock, Unreadable, SeqExhausted, WriteFailed }; inline const char* OutcomeWords(Outcome o) { switch (o) { case Outcome::Written: return "written"; - case Outcome::Superseded: return "a newer choice was recorded meanwhile (this one is dropped)"; - case Outcome::NoLock: return "the record's lock could not be taken"; + case Outcome::NoLock: return "the game's state lock could not be taken in time"; case Outcome::Unreadable: return "the record cannot be read (not written over)"; case Outcome::SeqExhausted: return "the record's sequence number is at its end (18446744073709551615): choice refused"; case Outcome::WriteFailed: return "the record could not be written"; @@ -313,39 +202,25 @@ inline const char* OutcomeWords(Outcome o) { return "?"; } -// A choice that could not be written when it was made (NoLock, Unreadable, WriteFailed): kept by its writer, used for -// the session and written later (RetryPending). base: the seq the record had when the choice was made (0: no record or a -// corrupt one); baseKnown false: the record could not be read then. -struct Pending { - char model = 0; // 0: nothing pending - Source source = Source::Plugin; - bool baseKnown = false; - uint64_t baseSeq = 0; - bool active() const { return model != 0; } -}; - // A choice of `model` by `source`: read the record and write seq + 1 (seq 1 without a record, or over a corrupt one, -// which *why then names). `retry`: a pending choice being written later: dropped (Superseded) when the record moved past -// its base meanwhile. *after: the record written. *pending (when given): filled on a failure that can be retried. Any -// failure leaves the record as it was. Call it under the record's Lock (RecordChoice / RetryPending take it). +// which *why then names). *after: the record written; *before: the record it replaced (model 0 when there was none or it +// was corrupt). Any failure leaves the record as it was and nothing is kept for later: the caller says "not saved". Call +// it holding the game's state lock (RecordChoice takes it). inline Outcome RecordChoiceUnlocked(const std::filesystem::path& path, char model, Source source, Record* after, std::string* why, - Pending* pending = nullptr, const Pending* retry = nullptr) { + Record* before = nullptr) { Record cur; std::string err; const ReadResult rr = ReadRecordFile(path, &cur, &err); + if (before) *before = rr == ReadResult::Ok ? cur : Record{0, 0, Source::Launcher}; if (rr == ReadResult::Unreadable) { if (why) *why = err; - if (pending) *pending = Pending{model, source, false, 0}; return Outcome::Unreadable; } - const uint64_t seqNow = rr == ReadResult::Ok ? cur.seq : 0; - if (retry && retry->baseKnown && seqNow != retry->baseSeq) return Outcome::Superseded; if (rr == ReadResult::Corrupt && why) *why = "a corrupt record was replaced (" + err + ")"; if (rr == ReadResult::Ok && cur.seq == UINT64_MAX) return Outcome::SeqExhausted; - const Record next{model, seqNow + 1, source}; + const Record next{model, rr == ReadResult::Ok ? cur.seq + 1 : 1, source}; if (!WriteRecordFile(path, next, &err)) { if (why) *why = err; - if (pending) *pending = Pending{model, source, true, seqNow}; return Outcome::WriteFailed; } if (after) *after = next; @@ -353,45 +228,38 @@ inline Outcome RecordChoiceUnlocked(const std::filesystem::path& path, char mode } inline Outcome RecordChoice(const std::filesystem::path& path, char model, Source source, Record* after, std::string* why, - Pending* pending = nullptr, unsigned lockMs = 3000) { - Lock lock(path, lockMs); - if (!lock.ok()) { - if (pending) *pending = Pending{model, source, false, 0}; - return Outcome::NoLock; - } - return RecordChoiceUnlocked(path, model, source, after, why, pending); -} - -// Writes a pending choice (see Pending). Written or Superseded: nothing is pending any more (*p cleared); SeqExhausted: -// cleared too (refused for good); otherwise *p stays for a later try. -inline Outcome RetryPending(const std::filesystem::path& path, Pending* p, Record* after, std::string* why, unsigned lockMs = 3000) { - if (!p->active()) return Outcome::Superseded; + Record* before = nullptr, unsigned lockMs = 3000) { Lock lock(path, lockMs); if (!lock.ok()) return Outcome::NoLock; - const Pending retry = *p; - const Outcome o = RecordChoiceUnlocked(path, retry.model, retry.source, after, why, nullptr, &retry); - if (o == Outcome::Written || o == Outcome::Superseded || o == Outcome::SeqExhausted) *p = Pending{}; - return o; + return RecordChoiceUnlocked(path, model, source, after, why, before); } -// The record as it is now, read under the lock. A game without one (an install from before 0.6.5) gets one from the -// launcher's existing choice (`launcherModel`, 'M' / 'K' / 'L', or 0 for none: Model M), seq 1, source=launcher. -// Returns Ok (also after the migration; *out set, *migrated true then), Corrupt or Unreadable (*why; nothing written), or -// Missing when the lock or the migration's write failed (*why). -inline ReadResult LoadOrMigrateRecord(const std::filesystem::path& path, char launcherModel, Record* out, bool* migrated, std::string* why) { +// The record as it is now, read under the game's state lock. A game without one (an install from before 0.6.5) gets one +// from the launcher's existing choice, read WHILE the lock is held (`launcherModel()`: wronggpu.ini's model item, 'M' / +// 'K' / 'L', or 0 for none: Model M), seq 1, source=launcher; so a launcher apply, which holds the same lock, is either +// wholly before or wholly after it. Returns Ok (also after the migration; *out set, *migrated true then), Corrupt or +// Unreadable (*why; nothing written), Missing when the migration's write failed (*why), or NoLock (the lock was not +// taken in `lockMs`; *why). +enum class LoadResult { Ok, Corrupt, Unreadable, Missing, NoLock }; +template +inline LoadResult LoadOrMigrateRecord(const std::filesystem::path& path, LauncherModelFn&& launcherModel, Record* out, bool* migrated, + std::string* why, unsigned lockMs = 3000) { if (migrated) *migrated = false; - Lock lock(path); + Lock lock(path, lockMs); if (!lock.ok()) { - if (why) *why = "the record's lock could not be taken"; - return ReadResult::Unreadable; + if (why) *why = OutcomeWords(Outcome::NoLock); + return LoadResult::NoLock; } const ReadResult rr = ReadRecordFile(path, out, why); - if (rr != ReadResult::Missing) return rr; - const Record first{IsModel(launcherModel) ? launcherModel : 'M', 1, Source::Launcher}; - if (!WriteRecordFile(path, first, why)) return ReadResult::Missing; + if (rr == ReadResult::Ok) return LoadResult::Ok; + if (rr == ReadResult::Corrupt) return LoadResult::Corrupt; + if (rr == ReadResult::Unreadable) return LoadResult::Unreadable; + const char m = launcherModel(); + const Record first{IsModel(m) ? m : 'M', 1, Source::Launcher}; + if (!WriteRecordFile(path, first, why)) return LoadResult::Missing; *out = first; if (migrated) *migrated = true; - return ReadResult::Ok; + return LoadResult::Ok; } } // namespace wgchoice diff --git a/clean/fsr/tests/test_asi_status.cpp b/clean/fsr/tests/test_asi_status.cpp index 64c1e597..58453618 100644 --- a/clean/fsr/tests/test_asi_status.cpp +++ b/clean/fsr/tests/test_asi_status.cpp @@ -131,9 +131,7 @@ int main(int argc, char** argv) { int hooked = -1; char model = '?'; CHECK(legacy(&hooked, &model) == 1 && hooked == 0 && model == 'M'); // the saved entry is unchanged } - // no click was made: nothing is pending - auto pending = reinterpret_cast(GetProcAddress(module, WRONGGPU_ASI_PENDING_CHOICE)); - CHECK(pending != nullptr && pending() == 0); + CHECK(GetProcAddress(module, "WrongGpuAsiPendingChoiceV1") == nullptr); // no queued choice exists any more CHECK(FreeLibrary(module) != 0); // No initialization or patches ever occurred. CHECK(GetModuleHandleA(argv[1]) == nullptr); // Query-only loading did not permanently pin it. } diff --git a/clean/fsr/tests/test_asi_thunk.cpp b/clean/fsr/tests/test_asi_thunk.cpp index 09e42d9a..11d030f0 100644 --- a/clean/fsr/tests/test_asi_thunk.cpp +++ b/clean/fsr/tests/test_asi_thunk.cpp @@ -197,30 +197,48 @@ void TestClickAndShownModel() { #endif } -// A model click the plugin could not write to the model choice record yet: its entry says so in the menu ("not saved -// yet, retrying"; "not saved: the choice record is full" when refused), the other entries are unchanged, and a click on -// the labelled entry is still that model's click. -void TestUnsavedLabel() { +// A model click the plugin cannot write to the model choice record (the lock not taken in time, a failed write, the end of +// the sequence numbers): NOTHING changes (the selection, the mark, no click passed on to OptiScaler, nothing kept for +// later) and the entry says "(not saved, try again)" ("not saved: the choice record is full" when refused) until a click +// that is saved. The AMD entry never writes the record. +void TestUnsavedClick() { PluginState st; const int size = 0; + const Entry& first = kEntries[0]; const Entry& last = kEntries[kEntryCount - 1]; - st.unsaved.store(last.model); + st.model.store(first.model); + st.shown.store(first.model); // the front end runs the first model + int saves = 0; + auto fail = [&](char) { ++saves; return Save::NotSaved; }; + FakeSelectable click; + click.clickLabel = last.label; + bool clicked = true; + CHECK(!SelectableThunkLogic(click, "FSR 3.X", true, 0, &size, st, fail, &clicked) && !clicked && saves == 1); + CHECK(st.model.load() == first.model && st.shown.load() == first.model && st.unsaved.load() == last.model); FakeSelectable draw; - SelectableThunkLogic(draw, "FSR 3.X", true, 0, &size, st); - CHECK(draw.calls.size() == kEntryCount + 1); + SelectableThunkLogic(draw, "FSR 3.X", true, 0, &size, st, fail); + CHECK(draw.calls.size() == kEntryCount + 1 && draw.calls[kEntryCount - 1].label == std::string(last.label) + kUnsavedSuffix); + CHECK(draw.calls[0].selected == true || kEntryCount == 1); // the model that runs stays marked for (size_t i = 0; i + 1 < kEntryCount; ++i) CHECK(draw.calls[i].label == kEntries[i].label); - CHECK(draw.calls[kEntryCount - 1].label == std::string(last.label) + kUnsavedSuffix); - CHECK(draw.calls[kEntryCount].label == "FSR 3.X"); - st.refused.store(true); - FakeSelectable refused; - SelectableThunkLogic(refused, "FSR 3.X", true, 0, &size, st); - CHECK(refused.calls[kEntryCount - 1].label == std::string(last.label) + kRefusedSuffix); - st.refused.store(false); - FakeSelectable click; - click.clickLabel = std::string(last.label) + kUnsavedSuffix; - bool clicked = false; - CHECK(SelectableThunkLogic(click, "FSR 3.X", true, 0, &size, st, &clicked) && clicked && st.model.load() == last.model); - st.unsaved.store(0); + // refused (the end of the sequence numbers): said so + auto refuse = [&](char) { return Save::Refused; }; + FakeSelectable click2; + click2.clickLabel = std::string(last.label) + kUnsavedSuffix; + CHECK(!SelectableThunkLogic(click2, "FSR 3.X", true, 0, &size, st, refuse, &clicked) && st.model.load() == first.model); + FakeSelectable draw2; + SelectableThunkLogic(draw2, "FSR 3.X", true, 0, &size, st, refuse); + CHECK(draw2.calls[kEntryCount - 1].label == std::string(last.label) + kRefusedSuffix); + // the AMD entry: no record write, takes effect + int amdSaves = 0; + FakeSelectable amd; + amd.clickLabel = "FSR 3.X"; + CHECK(SelectableThunkLogic(amd, "FSR 3.X", true, 0, &size, st, [&](char) { ++amdSaves; return Save::NotSaved; }, &clicked) && + clicked && amdSaves == 0 && st.model.load() == kModelAmd && st.unsaved.load() == 0); + // a click that is saved: takes effect, the note goes + FakeSelectable ok; + ok.clickLabel = last.label; + CHECK(SelectableThunkLogic(ok, "FSR 3.X", true, 0, &size, st, [](char) { return Save::Saved; }, &clicked) && clicked && + st.model.load() == last.model && st.unsaved.load() == 0); FakeSelectable plain; SelectableThunkLogic(plain, "FSR 3.X", true, 0, &size, st); CHECK(plain.calls[kEntryCount - 1].label == last.label); @@ -238,7 +256,7 @@ int main() { TestPreviewRelabel(); TestSelectionFile(); TestClickAndShownModel(); - TestUnsavedLabel(); + TestUnsavedClick(); std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } diff --git a/clean/fsr/tests/test_frontend.cpp b/clean/fsr/tests/test_frontend.cpp index 17d291e7..3dc9a98c 100644 --- a/clean/fsr/tests/test_frontend.cpp +++ b/clean/fsr/tests/test_frontend.cpp @@ -22,6 +22,7 @@ #include #include "../include/wronggpu_host_event.h" +#include "../../wgshared/include/wg_model_entries.h" #include "../src/config.h" #include "../src/ffx_describe.h" #include "../src/frontend.h" @@ -246,7 +247,7 @@ static bool g_asiHooked = false; // and it reports a successful hook static char g_asiModel = 0; // 0 (AMD), 'M', 'K' static std::vector g_asiShown; // Platform::asiShowModel calls static std::filesystem::path g_choiceRecord; // Platform::choiceRecord (a real file; empty: none) -static char g_asiPendingModel = 0; // Platform::asiPending (the plugin's unsaved click) +static std::string g_iniOnDisk; // Platform::readWronggpuIni (empty: not wired); not cleared by Reset // Fake shared settings (Platform::menu, settings_bridge.h in the DLL): values set "somewhere" (block / env / ini), // the writes of the menu's choices, whether this module is the writer, the folder sidecar's entry. @@ -290,7 +291,7 @@ static std::unique_ptr MakeFrontEnd(const Config& config) { if (g_asiPresent) p.asiPlugin = [](char* model) { if (model) *model = g_asiModel; return g_asiHooked; }; if (g_asiPresent) p.asiShowModel = [](char model) { g_asiShown.push_back(model); }; - if (g_asiPresent) p.asiPending = [] { return g_asiPendingModel; }; + if (!g_iniOnDisk.empty()) p.readWronggpuIni = [] { return g_iniOnDisk; }; p.choiceRecord = g_choiceRecord; p.compareApi = []() -> const OriginalApi* { return g_compareApi; }; p.backend = [](const Config&, std::string&) -> const WgUpscalerBackend* { return g_useBackend; }; @@ -386,7 +387,6 @@ static void Reset() { g_asiHooked = false; g_asiModel = 0; g_asiShown.clear(); - g_asiPendingModel = 0; g_createInfo = WgCreateInfo{}; g_compare = false; g_statuses.clear(); @@ -2668,13 +2668,14 @@ static void TestAsiPluginPresetK() { #endif } -// 0.6.5 (#213): the game's model choice record (model_choice_record.h) decides the WrongGPU model of a hosted create, on -// REAL files in a fresh folder under the temporary folder, through the front end: the upgrade migration (wronggpu.ini's -// model item, never the stored index); the index OptiScaler stores is never a choice (hooked route and custom slot); -// a player's selection in OptiScaler's list arrives as an event (HostSelected) and is recorded, also re-selecting the -// same entry after a plugin choice; each source winning in turn; AMD; corrupt, unreadable and exhausted records; a -// failed event write that runs for the session and is written at the next create (or dropped when superseded); the -// plugin's unsaved click; a game without a record. Plus the audit's case without any record (the launcher's model item). +// 0.6.5 (#213): the game's model choice record (model_choice_record.h) decides the WrongGPU model of a create, on REAL +// files in a fresh folder under the temporary folder, through the front end: the upgrade migration (wronggpu.ini's model +// item as it is on disk, read under the state lock; never the stored index); the index OptiScaler stores is never a +// choice (hooked route, custom slot, and when the record fails); a player's selection in OptiScaler's list arrives as an +// event (HostSelected): 1 when the model that runs changes (also re-selecting the same entry after a plugin choice), 0 +// when it does not, negative when it is not saved (busy, failed write, end of seq), which changes nothing; each source +// winning in turn; AMD; corrupt and unreadable records (the last choice of the session, else wronggpu.ini's item); the +// direct route; a game without a record. Plus the audit's case without any record (the launcher's model item). struct RecordFolder { std::filesystem::path dir; RecordFolder() { @@ -2706,39 +2707,47 @@ static void WriteRec(const std::filesystem::path& p, const std::string& text) { o << text; } -// One hosted create, OptiScaler's list naming `overrideId` (0: none). hooked: the plugin hooked with its entry `plugin` -// (0 AMD or a WrongGPU model); else the custom slot / FFX route without the plugin (the host's entry). `before` runs on -// the front end first (a host event). The provider the context runs ("" for AMD). -static std::string HostedCreate(const char* ini, char plugin, uint64_t overrideId, bool hooked = true, - const std::function& before = {}) { +// A front end for hosted creates: hooked (the plugin hooked, its entry `plugin`: 0 AMD or a WrongGPU model) or not (the +// custom slot / FFX route without the plugin). hosted false: the direct route. +static std::unique_ptr ChoiceFrontEnd(const char* ini, char plugin, bool hooked, bool hosted = true) { Reset(); g_resources[kOutput] = {dxgi::R16G16B16A16_FLOAT, 2560, 1440}; std::string warnings; Config c = ParseConfig(ini, &warnings); CHECK(warnings.empty()); - c.hosted = true; + c.hosted = hosted; c.upscaler = UpscalerChoice::Network; c.contextParkMs = 0; g_asiPresent = hooked; g_asiHooked = hooked; g_asiModel = plugin; - auto fe = MakeFrontEnd(c); - if (before) before(*fe); + return MakeFrontEnd(c); +} + +// One create on `fe`, the host's list naming `overrideId` (0: none); the provider the context runs ("" for AMD). +static std::string ChoiceCreate(FrontEnd& fe, uint64_t overrideId) { const size_t amd = g_amd.size(); UpscaleCreate create(FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE, overrideId != 0); create.version.versionId = overrideId; ffxContext ctx = nullptr; - CHECK(fe->CreateContext(&ctx, &create.upscale.header, kMemCb) == FFX_API_RETURN_OK && ctx); + CHECK(fe.CreateContext(&ctx, &create.upscale.header, kMemCb) == FFX_API_RETURN_OK && ctx); std::string provider; if (g_amd.size() == amd) { ffxQueryGetProviderVersion q{}; q.header.type = FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION; - if (fe->Query(&ctx, &q.header) == FFX_API_RETURN_OK && q.versionName) provider = q.versionName; + if (fe.Query(&ctx, &q.header) == FFX_API_RETURN_OK && q.versionName) provider = q.versionName; } - CHECK(fe->DestroyContext(&ctx, kMemCb) == FFX_API_RETURN_OK); + CHECK(fe.DestroyContext(&ctx, kMemCb) == FFX_API_RETURN_OK); return provider; } +static std::string HostedCreate(const char* ini, char plugin, uint64_t overrideId, bool hooked = true, + const std::function& before = {}) { + auto fe = ChoiceFrontEnd(ini, plugin, hooked); + if (before) before(*fe); + return ChoiceCreate(*fe, overrideId); +} + static void TestAsiChoiceRecord() { const bool present = g_asiPresent, hooked = g_asiHooked; const char saved = g_asiModel; @@ -2753,60 +2762,67 @@ static void TestAsiChoiceRecord() { const std::filesystem::path& rec = f.record(); std::string why; // The audit's case without a record (a front end without the state folder): the launcher's K / L item decides over the - // plugin's saved default entry (Model M). + // plugin's saved default entry (Model M); a host event there changes nothing (0: the host's entry decides) if (b) { const std::string ini = std::string("runtime_options = model=") + b + "\n"; CHECK(HostedCreate(ini.c_str(), 'M', kWrongGpuProviderVersionId) == name(b)); CHECK(CountLog("no model choice record; the launcher's model item") == 1); - // a host event without a record (no launcher state folder): it runs this session only - int32_t rc = 0; - CHECK(HostedCreate(ini.c_str(), 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name('M')); - CHECK(rc == WG_HOST_SELECTED_SESSION_ONLY && CountLog("selected in OptiScaler's upscaler list this session") == 1); + int32_t rc = 9; + CHECK(HostedCreate(ini.c_str(), 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name(b)); + CHECK(rc == WG_HOST_SELECTED_NOTHING_CHANGED); } g_choiceRecord = rec; if (b) { const std::string iniB = std::string("runtime_options = model=") + b + "\n"; const char* iniM = "runtime_options = model=M\n"; - // (1) upgrade: no record, wronggpu.ini says b, OptiScaler's box names Model M: the record is migrated from the model - // item (b, seq 1, source=launcher), never from the box; b runs - CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M')) == name(b)); + // (1) upgrade: no record; wronggpu.ini ON DISK says b (the configuration read at start said M), OptiScaler's box + // names Model M: the record is migrated from the file as it is now (b, seq 1, source=launcher), never from the box + g_iniOnDisk = iniB; + CHECK(HostedCreate(iniM, 'M', idOf('M')) == name(b)); + g_iniOnDisk.clear(); wgchoice::Record r = ReadRec(rec); CHECK(r.model == b && r.seq == 1 && r.source == wgchoice::Source::Launcher); - CHECK(lines(std::string("model choice: no record yet (an install from before 0.6.5): Model ") + b + " from wronggpu.ini's model item") == 1); + CHECK(lines(std::string("model choice: no record yet (an install from before 0.6.5): Model ") + b) == 1); CHECK(lines("selected in the host's upscaler list (the model choice record: the launcher, seq 1)") == 1); // (2) the stored index is never a choice: the box names M at every create, the record stays b, seq 1 CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M')) == name(b)); CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M')) == name(b)); CHECK(ReadRec(rec).seq == 1 && g_asiShown.size() == 1 && g_asiShown[0] == b); - // (3) the player selects Model M in OptiScaler's list: the event is recorded (seq 2, source=ffx); M runs - int32_t rc = 0; + // (3) the player selects Model M in OptiScaler's list: recorded (seq 2, source=ffx), 1 (M runs now instead of b) + int32_t rc = 9; CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name('M')); r = ReadRec(rec); CHECK(rc == WG_HOST_SELECTED_RECORDED && r.model == 'M' && r.seq == 2 && r.source == wgchoice::Source::Ffx); CHECK(lines("the player selected Model M in OptiScaler's upscaler list: recorded (seq 2, source=ffx)") == 1); - CHECK(lines(std::string("model choice conflict: wronggpu.ini's model item says Model ") + b) == 1); + CHECK(lines(std::string("model choice: wronggpu.ini's model item (the install's default) says Model ") + b) == 1); // (4) the player clicks b in the plugin's menu (the plugin writes seq 3, source=plugin); the box still names M: b runs wgchoice::Record after; CHECK(wgchoice::RecordChoice(rec, b, wgchoice::Source::Plugin, &after, &why) == wgchoice::Outcome::Written); CHECK(HostedCreate(iniB.c_str(), b, idOf('M')) == name(b)); - CHECK(ReadRec(rec).seq == 3); - // (5) the player selects the SAME entry (M) in OptiScaler's list again after the plugin's choice: it wins (seq 4) - CHECK(HostedCreate(iniB.c_str(), b, idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name('M')); - r = ReadRec(rec); - CHECK(rc == WG_HOST_SELECTED_RECORDED && r.model == 'M' && r.seq == 4 && r.source == wgchoice::Source::Ffx); - // (6) the launcher applies b (seq 5): b runs + // (5) the player selects the SAME entry (M) again after the plugin's choice: it wins (seq 4) and returns 1, so the + // host recreates the upscaler although its index did not change + { + auto fe = ChoiceFrontEnd(iniB.c_str(), b, true); + CHECK(ChoiceCreate(*fe, idOf('M')) == name(b)); // the session runs b + CHECK(fe->HostSelected(idOf('M')) == WG_HOST_SELECTED_RECORDED); + CHECK(ChoiceCreate(*fe, idOf('M')) == name('M')); + // ... and once more: recorded again (seq 5), but nothing changes in what runs: 0 + CHECK(fe->HostSelected(idOf('M')) == WG_HOST_SELECTED_NOTHING_CHANGED); + r = ReadRec(rec); + CHECK(r.model == 'M' && r.seq == 5 && r.source == wgchoice::Source::Ffx); + } + // (6) the launcher applies b (seq 6): b runs CHECK(wgchoice::RecordChoice(rec, b, wgchoice::Source::Launcher, &after, &why) == wgchoice::Outcome::Written); CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M')) == name(b)); // (7) a third model selected in the list (a build with K and L) if (c3) { CHECK(HostedCreate(iniM, b, idOf(b), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf(c3)); }) == name(c3)); - r = ReadRec(rec); - CHECK(r.model == c3 && r.seq == 6 && r.source == wgchoice::Source::Ffx); + CHECK(rc == WG_HOST_SELECTED_RECORDED && ReadRec(rec).model == c3 && ReadRec(rec).source == wgchoice::Source::Ffx); } - // (8) an AMD version selected in the list is no model choice; the plugin's AMD entry runs AMD; the record is untouched + // (8) an AMD version selected in the list is no model choice (0); the plugin's AMD entry runs AMD; record untouched const uint64_t s0 = ReadRec(rec).seq; CHECK(HostedCreate(iniM, 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(g_versionIds[0]); }) != ""); - CHECK(rc == WG_HOST_SELECTED_NOT_A_MODEL && ReadRec(rec).seq == s0); + CHECK(rc == WG_HOST_SELECTED_NOTHING_CHANGED && ReadRec(rec).seq == s0); CHECK(HostedCreate(iniM, 0, idOf('M')).empty()); CHECK(ReadRec(rec).seq == s0 && CountLog("OptiScaler plugin: AMD FSR selected in the host's upscaler list") == 1); // (9) the custom slot / FFX route without the plugin: the host's entry names M, the record says b: b runs @@ -2816,73 +2832,61 @@ static void TestAsiChoiceRecord() { // ... and a selection event there is recorded and runs CHECK(HostedCreate(iniM, 0, idOf(b), false, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name('M')); CHECK(rc == WG_HOST_SELECTED_RECORDED && ReadRec(rec).model == 'M'); + // (10) the direct route (not hosted, no entry): the record's model too + CHECK(wgchoice::RecordChoice(rec, b, wgchoice::Source::Launcher, &after, &why) == wgchoice::Outcome::Written); + { + auto fe = ChoiceFrontEnd(iniM, 0, false, /*hosted=*/false); + CHECK(ChoiceCreate(*fe, 0) == name(b)); + } #ifdef _WIN32 - // (10) a selection whose write fails (the record held open without delete sharing): it runs this session, said as an - // ERROR, and is written at the next create once the record is free - CHECK(wgchoice::RecordChoice(rec, 'M', wgchoice::Source::Launcher, &after, &why) == wgchoice::Outcome::Written); - const uint64_t s1 = after.seq; - HANDLE hold = CreateFileW(rec.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); - CHECK(hold != INVALID_HANDLE_VALUE); + // (11) the game's state lock held by another WrongGPU program for longer than the event waits: the selection is + // NOT saved (-1), nothing changes and nothing is kept; a create meanwhile runs the session's last choice (b), never + // the host's entry (M) { - Reset(); - g_resources[kOutput] = {dxgi::R16G16B16A16_FLOAT, 2560, 1440}; - std::string w; - Config c = ParseConfig(iniM, &w); - c.hosted = true; - c.upscaler = UpscalerChoice::Network; - c.contextParkMs = 0; - g_asiPresent = g_asiHooked = true; - g_asiModel = 'M'; - auto fe = MakeFrontEnd(c); - CHECK(fe->HostSelected(idOf(b)) == WG_HOST_SELECTED_PENDING); - CHECK(CountLog("is written at the next create") == 1 && ReadRec(rec).seq == s1); - auto create = [&] { - UpscaleCreate cr(FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE, true); - cr.version.versionId = idOf('M'); - ffxContext ctx = nullptr; - CHECK(fe->CreateContext(&ctx, &cr.upscale.header, kMemCb) == FFX_API_RETURN_OK && ctx); - ffxQueryGetProviderVersion q{}; - q.header.type = FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION; - std::string p; - if (fe->Query(&ctx, &q.header) == FFX_API_RETURN_OK && q.versionName) p = q.versionName; - CHECK(fe->DestroyContext(&ctx, kMemCb) == FFX_API_RETURN_OK); - return p; - }; - CHECK(create() == name(b)); // still held: runs this session - CHECK(CountLog("still cannot be written") == 1 && ReadRec(rec).seq == s1); - CloseHandle(hold); - CHECK(create() == name(b)); // free: written now - r = ReadRec(rec); - CHECK(r.model == b && r.seq == s1 + 1 && r.source == wgchoice::Source::Ffx && CountLog("written now") == 1); - // superseded: a selection that fails, then the launcher writes M; the pending one is dropped, M runs - hold = CreateFileW(rec.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); - CHECK(fe->HostSelected(idOf(b)) == WG_HOST_SELECTED_PENDING); - CloseHandle(hold); - CHECK(wgchoice::RecordChoice(rec, 'M', wgchoice::Source::Launcher, &after, &why) == wgchoice::Outcome::Written); - CHECK(create() == name('M')); - CHECK(CountLog("is dropped: a newer choice was recorded meanwhile") == 1 && ReadRec(rec).model == 'M'); + auto fe = ChoiceFrontEnd(iniM, 0, false); + CHECK(ChoiceCreate(*fe, idOf('M')) == name(b)); // the session read b + const std::string kept = [&] { std::ifstream i(rec, std::ios::binary); return std::string(std::istreambuf_iterator(i), {}); }(); + std::atomic held{false}, release{false}; + std::thread holder([&] { + wgstate::StateLock l(f.dir.wstring()); + held.store(l.held()); + while (!release.load()) Sleep(1); + }); + while (!held.load()) Sleep(1); + CHECK(fe->HostSelected(idOf('M')) == WG_HOST_SELECTED_NOT_SAVED); + CHECK(CountLog("but it was not saved: the game's state lock could not be taken in time") == 1); + CHECK(ChoiceCreate(*fe, idOf('M')) == name(b)); + CHECK(CountLog("the model choice record was busy; the last model choice read this session") == 1); + release.store(true); + holder.join(); + const std::string now = [&] { std::ifstream i(rec, std::ios::binary); return std::string(std::istreambuf_iterator(i), {}); }(); + CHECK(now == kept); + CHECK(ChoiceCreate(*fe, idOf('M')) == name(b)); // still b: the unsaved selection was not kept for later } - // (11) the plugin's click it could not write yet: it runs this session + // (12) a selection whose write fails (the record held open without delete sharing): not saved, nothing changes { - const uint64_t s2 = ReadRec(rec).seq; - CHECK(HostedCreate(iniM, b, idOf('M'), true, [&](FrontEnd&) { g_asiPendingModel = b; }) == name(b)); - g_asiPendingModel = 0; - CHECK(CountLog("the plugin's click this session, not saved yet") == 1 && ReadRec(rec).seq == s2); + auto fe = ChoiceFrontEnd(iniM, 0, false); + HANDLE hold = CreateFileW(rec.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + CHECK(hold != INVALID_HANDLE_VALUE); + const uint64_t s1 = ReadRec(rec).seq; + CHECK(fe->HostSelected(idOf('M')) == WG_HOST_SELECTED_NOT_SAVED); + CloseHandle(hold); + CHECK(ReadRec(rec).seq == s1 && ChoiceCreate(*fe, idOf('M')) == name(b)); } - // (12) a record another program holds open without sharing: not read, NEVER written over; the launcher's item decides - const std::string kept = ReadRec(rec).model == 'M' ? "M" : "?"; - hold = CreateFileW(rec.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + // (13) a record another program holds open without sharing: not read, NEVER written over. A fresh session uses + // wronggpu.ini's item (b), never the host's entry (M or the third model) + HANDLE hold = CreateFileW(rec.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); CHECK(hold != INVALID_HANDLE_VALUE); - CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M')) == name(b)); + CHECK(HostedCreate(iniB.c_str(), 0, idOf('M'), false) == name(b)); CHECK(CountLog("model choice: the record (wronggpu-setup\\model-choice.ini) cannot be read (") == 1); - CHECK(CountLog("(the model choice record cannot be read; the launcher's model item") == 1); + CHECK(CountLog("(the model choice record cannot be read; wronggpu.ini model=") == 1); CloseHandle(hold); - CHECK(kept == "M" && ReadRec(rec).model == 'M'); + CHECK(ReadRec(rec).model == b); #endif - // (13) a corrupt record (seq overflow): said once, treated as no choice (the launcher's item), not written over by a - // create; the next real choice replaces it + // (14) a corrupt record (seq overflow): said once, not used (a fresh session: wronggpu.ini's item, never the host's + // entry), not written over by a create; the next real choice replaces it WriteRec(rec, "model=L\nseq=18446744073709551616\nsource=launcher\n"); - CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M')) == name(b)); + CHECK(HostedCreate(iniB.c_str(), 0, idOf('M'), false) == name(b)); CHECK(CountLog("is corrupt (seq is not a number") == 1); wgchoice::ReadResult rr; ReadRec(rec, &rr); @@ -2890,7 +2894,7 @@ static void TestAsiChoiceRecord() { CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name('M')); r = ReadRec(rec); CHECK(rc == WG_HOST_SELECTED_RECORDED && r.model == 'M' && r.seq == 1 && r.source == wgchoice::Source::Ffx); - // (14) the end of the sequence numbers: the selection is refused loudly, the record unchanged + // (15) the end of the sequence numbers: the selection is refused loudly (-2), the record unchanged WriteRec(rec, std::string("model=") + b + "\nseq=18446744073709551615\nsource=plugin\n"); CHECK(HostedCreate(iniM, 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name(b)); r = ReadRec(rec); @@ -2907,6 +2911,40 @@ static void TestAsiChoiceRecord() { g_asiModel = saved; } +// The order of WrongGPU's model entries in the list the front end gives a host (ListVersions) is the one shared +// definition (wgshared wg_model_entries.h) the launcher writes OptiScaler's UpscalerIndex from: M, then K, then L, for this +// build's K / L flags. +static void TestModelEntryOrder() { + Reset(); + Config config; + config.hosted = true; + auto fe = MakeFrontEnd(config); + uint64_t count = 0; + ffxQueryDescGetVersions versions{}; + versions.header.type = FFX_API_QUERY_DESC_TYPE_GET_VERSIONS; + versions.createDescType = FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE; + versions.device = kDevice; + versions.outputCount = &count; + CHECK(fe->Query(nullptr, &versions.header) == FFX_API_RETURN_OK && count > 0); + std::vector ids(count); + std::vector names(count); + versions.versionIds = ids.data(); + versions.versionNames = names.data(); + CHECK(fe->Query(nullptr, &versions.header) == FFX_API_RETURN_OK); + const bool withK = ModelOfName("K") >= 0, withL = ModelOfName("L") >= 0; + int listed = 0; + for (char m : {'M', 'K', 'L'}) { + const int want = wgentries::ModelEntryIndex(m, withK, withL); + const int32_t row = ModelOfName(std::string(1, m)); + const WgEntryDef* sr = row >= 0 ? SrEntryOfModel(row) : nullptr; + CHECK((want < 0) == (sr == nullptr)); + if (!sr) continue; + ++listed; + CHECK(want < int(count) && ids[size_t(want)] == sr->id); + } + CHECK(listed == 1 + (withK ? 1 : 0) + (withL ? 1 : 0)); +} + // i15: WrongGPU's version-list entries come from the registry (clean/wgshared). i20 (owner 2026-10-31): only the SR // models; the RR modes are a box of their own in the RR plugin's menu tab. An entry sets the context's model and // writes sr_model; one folder per choice lists its one entry and applies it without an override; a module that is not @@ -3756,6 +3794,7 @@ int main() { TestAsiPluginNotHooked(); TestAsiPluginPresetK(); TestAsiChoiceRecord(); + TestModelEntryOrder(); { Config profile; const auto original = profile.BackendOptions(); diff --git a/clean/fsr/tests/test_model_choice_record.cpp b/clean/fsr/tests/test_model_choice_record.cpp index 729eb88c..3e55977d 100644 --- a/clean/fsr/tests/test_model_choice_record.cpp +++ b/clean/fsr/tests/test_model_choice_record.cpp @@ -1,12 +1,15 @@ // SPDX-License-Identifier: MIT // Unit tests of the game's model choice record (clean/fsr/src/model_choice_record.h) on REAL files in a fresh folder under -// the system temporary folder, and with REAL processes (this program started again as a writer, a reader or a lock -// holder that dies): the strict three-key format, seq order with each source winning in turn, the cross-process lock -// (concurrent writers lose no update, seq never goes back; an abandoned lock is taken over), the upgrade migration, -// corrupt and overflowing records, the end of the sequence numbers, a failed write and its retry, a stale temporary file. +// the system temporary folder, and with REAL processes (this program started again as a writer, a reader, a launcher +// apply, a lock holder, or a lock holder that dies): the strict three-key format, seq order with each source winning in +// turn, the game's state lock (wg_state.h: concurrent writers lose no update, seq never goes back; an abandoned lock is +// taken over; two path aliases of one folder are one lock), the upgrade migration (under the lock, against a launcher +// apply in another process), corrupt and overflowing records, the end of the sequence numbers, failures that change +// nothing (no queue), a stale temporary file. #include #include #include +#include #include #include #include @@ -57,13 +60,6 @@ void TestStrictFormat() { CHECK(Parses(FormatRecord(Record{'K', 42, Source::Plugin}), &r) && r.model == 'K' && r.seq == 42 && r.source == Source::Plugin); } -void TestLockName() { - const std::wstring a = LockName(L"C:\\Games\\X\\wronggpu-setup\\model-choice.ini"); - CHECK(a.rfind(L"Local\\WrongGPU-choice-", 0) == 0 && a.size() == std::wstring(L"Local\\WrongGPU-choice-").size() + 16); - CHECK(LockName(L"c:/games/x/WRONGGPU-SETUP/model-choice.ini") == a); // the same file however it is spelt - CHECK(LockName(L"C:\\Games\\Y\\wronggpu-setup\\model-choice.ini") != a); // another game: another lock -} - struct Folder { fs::path dir; explicit Folder(const char* name = "") { @@ -108,7 +104,7 @@ int TmpFiles(const Folder& f) { int n = 0; std::error_code ec; for (auto& e : fs::directory_iterator(f.dir / kStateFolder, ec)) - if (e.path().extension() == ".tmp") ++n; + if (wgstate::IsTempName(e.path().filename().wstring())) ++n; return n; } @@ -137,7 +133,7 @@ void TestChoicesInTurn() { CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::Written); // the same choice again: seq grows CHECK(Rec(f.record()).seq == 6); // a stale temporary file a crash left next to the record (and garbage in it): never read, writes still work - const fs::path stale = f.record().string() + ".999.0.0.tmp"; + const fs::path stale = f.record().wstring() + wgstate::kTempMark + L"999-1"; WriteRaw(stale, "model=K\nseq=999999"); CHECK(Rec(f.record()).seq == 6); CHECK(RecordChoice(f.record(), 'K', Source::Plugin, &after, &why) == Outcome::Written && Rec(f.record()).seq == 7); @@ -180,73 +176,74 @@ void TestMigration() { Record r; bool migrated = false; std::string why; + auto model = [](char m) { return [m] { return m; }; }; // an install from before 0.6.5 (no record): wronggpu.ini's model item, seq 1, source=launcher; the stamp files of the // earlier designs next to it are ignored WriteRaw(f.dir / kStateFolder / "wronggpu-ffx-choice.ini", "model=K\nchosen=99999999999\n"); - CHECK(LoadOrMigrateRecord(f.record(), 'L', &r, &migrated, &why) == ReadResult::Ok && migrated); + CHECK(LoadOrMigrateRecord(f.record(), model('L'), &r, &migrated, &why) == LoadResult::Ok && migrated); CHECK(r.model == 'L' && r.seq == 1 && r.source == Source::Launcher); r = Rec(f.record()); CHECK(r.model == 'L' && r.seq == 1 && r.source == Source::Launcher); - // a record now: returned as it is, nothing written + // a record now: returned as it is, nothing written, the model item not even read const std::string text = ReadRaw(f.record()); - CHECK(LoadOrMigrateRecord(f.record(), 'K', &r, &migrated, &why) == ReadResult::Ok && !migrated && r.model == 'L'); + bool asked = false; + CHECK(LoadOrMigrateRecord(f.record(), [&] { asked = true; return 'K'; }, &r, &migrated, &why) == LoadResult::Ok && !migrated && + r.model == 'L' && !asked); CHECK(ReadRaw(f.record()) == text); // no model item: Model M std::error_code ec; fs::remove(f.record(), ec); - CHECK(LoadOrMigrateRecord(f.record(), 0, &r, &migrated, &why) == ReadResult::Ok && migrated && r.model == 'M' && r.seq == 1); + CHECK(LoadOrMigrateRecord(f.record(), model(0), &r, &migrated, &why) == LoadResult::Ok && migrated && r.model == 'M' && r.seq == 1); // a corrupt record is not migrated over (it stays corrupt until a real choice replaces it) WriteRaw(f.record(), "model=L\n"); - CHECK(LoadOrMigrateRecord(f.record(), 'K', &r, &migrated, &why) == ReadResult::Corrupt && !migrated); + CHECK(LoadOrMigrateRecord(f.record(), model('K'), &r, &migrated, &why) == LoadResult::Corrupt && !migrated); CHECK(ReadRaw(f.record()) == "model=L\n"); fs::remove(f.dir / kStateFolder / "wronggpu-ffx-choice.ini", ec); } #ifdef _WIN32 -// A write that fails (the record held open without delete sharing, so it cannot be replaced) and its retry; a choice -// superseded while it waited; a lock another thread holds (NoLock); an unreadable record never written over. -void TestFailureAndRetry() { +// Failures change nothing and nothing is kept for later: a write that fails (the record held open without delete sharing, +// so it cannot be replaced), the game's state lock held by another thread (through another spelling of the game folder), +// an unreadable record (never written over). After each, the next choice is written normally from the record as it is. +void TestFailures() { Folder f; - Record after; + Record after, before; std::string why; CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::Written); // seq 1 + CHECK(RecordChoice(f.record(), 'K', Source::Plugin, &after, &why, &before) == Outcome::Written && before.model == 'L' && + before.seq == 1 && after.seq == 2); // the record replaced is reported HANDLE h = CreateFileW(f.record().c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); CHECK(h != INVALID_HANDLE_VALUE); - Pending p; - CHECK(RecordChoice(f.record(), 'K', Source::Plugin, &after, &why, &p) == Outcome::WriteFailed); - CHECK(p.active() && p.model == 'K' && p.baseKnown && p.baseSeq == 1 && !why.empty()); - CHECK(RetryPending(f.record(), &p, &after, &why) == Outcome::WriteFailed && p.active()); // still held: still pending - CloseHandle(h); - CHECK(Rec(f.record()).seq == 1 && Rec(f.record()).model == 'L'); // nothing changed while it failed - CHECK(RetryPending(f.record(), &p, &after, &why) == Outcome::Written && !p.active()); - Record r = Rec(f.record()); - CHECK(r.model == 'K' && r.seq == 2 && r.source == Source::Plugin); - // a pending choice superseded meanwhile (the launcher wrote after it): dropped, the newer choice stays - h = CreateFileW(f.record().c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); - CHECK(RecordChoice(f.record(), 'M', Source::Ffx, &after, &why, &p) == Outcome::WriteFailed && p.baseSeq == 2); + const std::string kept = ReadRaw(f.record()); + CHECK(RecordChoice(f.record(), 'M', Source::Ffx, &after, &why) == Outcome::WriteFailed && !why.empty()); CloseHandle(h); + CHECK(ReadRaw(f.record()) == kept); // nothing changed, nothing to be written later CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::Written && after.seq == 3); - CHECK(RetryPending(f.record(), &p, &after, &why) == Outcome::Superseded && !p.active()); - r = Rec(f.record()); - CHECK(r.model == 'L' && r.seq == 3 && r.source == Source::Launcher); - // the lock held by another thread: NoLock (base unknown), nothing written; once free the retry writes + // the game's state lock (wg_state.h, the lock settings.ini's writers take too) held by another thread, through the game + // folder spelt differently: NoLock within the wait, nothing written std::atomic held{false}, release{false}; std::thread holder([&] { - Lock l(f.record()); - held.store(l.ok()); + std::wstring other = f.dir.wstring(); + for (auto& c : other) c = c == L'\\' ? L'/' : wchar_t(towupper(c)); + wgstate::StateLock l(other); + held.store(l.held()); while (!release.load()) Sleep(1); }); while (!held.load()) Sleep(1); - CHECK(RecordChoice(f.record(), 'K', Source::Ffx, &after, &why, &p, 100) == Outcome::NoLock && p.active() && !p.baseKnown); - CHECK(Rec(f.record()).seq == 3); + CHECK(RecordChoice(f.record(), 'K', Source::Ffx, &after, &why, nullptr, 100) == Outcome::NoLock); + bool migrated = false; + Record r; + CHECK(LoadOrMigrateRecord(f.record(), [] { return 'M'; }, &r, &migrated, &why, 100) == LoadResult::NoLock); release.store(true); holder.join(); - CHECK(RetryPending(f.record(), &p, &after, &why) == Outcome::Written && Rec(f.record()).seq == 4 && Rec(f.record()).model == 'K'); + r = Rec(f.record()); + CHECK(r.model == 'L' && r.seq == 3); // a record held open without any sharing: Unreadable, never written over h = CreateFileW(f.record().c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); - CHECK(RecordChoice(f.record(), 'M', Source::Plugin, &after, &why, &p) == Outcome::Unreadable && p.active() && !p.baseKnown); + CHECK(RecordChoice(f.record(), 'M', Source::Plugin, &after, &why) == Outcome::Unreadable); + CHECK(LoadOrMigrateRecord(f.record(), [] { return 'M'; }, &r, &migrated, &why) == LoadResult::Unreadable); CloseHandle(h); - CHECK(Rec(f.record()).seq == 4 && Rec(f.record()).model == 'K'); + CHECK(Rec(f.record()).seq == 3 && Rec(f.record()).model == 'L'); CHECK(TmpFiles(f) == 0); } @@ -266,6 +263,15 @@ HANDLE Spawn(const std::wstring& args) { return pi.hProcess; } +HANDLE Spawn2(std::wstring cmd) { // another program's command line + STARTUPINFOW si{}; + si.cb = sizeof si; + PROCESS_INFORMATION pi{}; + if (!CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi)) return nullptr; + CloseHandle(pi.hThread); + return pi.hProcess; +} + DWORD Wait(HANDLE p) { WaitForSingleObject(p, 120000); DWORD code = 999; @@ -312,6 +318,90 @@ void TestAbandonedLock() { CHECK(Rec(f.record()).model == 'K'); } +// The upgrade migration reads wronggpu.ini's model item WHILE it holds the game's state lock, so a launcher apply (which +// holds the same lock across wronggpu.ini and the record) is wholly before or after it, in two REAL processes: +// (1) a launcher process takes the lock, writes wronggpu.ini (model=L) and dies before it writes the record: the waiting +// migration reads L, never the M it would have read before the lock; +// (2) a launcher process takes the lock, writes wronggpu.ini and then the record (L, seq 1): the waiting migration finds +// that record and writes nothing. +char IniModel(const fs::path& ini) { + const std::string text = ReadRaw(ini); + const size_t at = text.rfind("model="); + return at == std::string::npos || at + 6 >= text.size() ? 0 : text[at + 6]; +} + +void TestMigrationUnderLock() { + for (int crash = 1; crash >= 0; --crash) { + Folder f(crash ? "-mig1" : "-mig2"); + const fs::path ini = f.dir / "wronggpu.ini", signal = f.dir / "locked.txt"; + WriteRaw(ini, "[fsr]\r\nruntime_options = model=M\r\n"); + HANDLE p = Spawn(std::wstring(crash ? L"apply-and-die" : L"apply") + L" \"" + f.dir.wstring() + L"\""); + CHECK(p != nullptr); + for (int i = 0; i < 5000 && !fs::exists(signal); ++i) Sleep(1); // the launcher holds the lock now + CHECK(fs::exists(signal)); + CHECK(IniModel(ini) == 'M'); // read now, before the lock, it would still be M + Record r; + bool migrated = false; + std::string why; + CHECK(LoadOrMigrateRecord(f.record(), [&] { return IniModel(ini); }, &r, &migrated, &why, 10000) == LoadResult::Ok); + CHECK(r.model == 'L' && r.seq == 1 && r.source == Source::Launcher && migrated == (crash == 1)); + CHECK(Wait(p) == DWORD(crash ? 97 : 0)); + r = Rec(f.record()); + CHECK(r.model == 'L' && r.seq == 1); + std::error_code ec; + fs::remove(ini, ec); + fs::remove(signal, ec); + } +} + +// Two path aliases of one game folder (a directory junction, and the \\?\ form) name ONE lock: a process holding the +// game's state lock through the junction keeps a writer that uses the real path out. +void TestAliasesOneLock() { + Folder f("-alias"); + const std::wstring alias = f.dir.wstring() + L"-junction"; + RemoveDirectoryW(alias.c_str()); + HANDLE mk = Spawn2(L"cmd.exe /d /c mklink /J \"" + alias + L"\" \"" + f.dir.wstring() + L"\" >nul"); + CHECK(mk != nullptr && Wait(mk) == 0); + std::wstring a, b, c; + CHECK(wgstate::LockNameFor(f.dir.wstring(), &a) && wgstate::LockNameFor(alias, &b) && + wgstate::LockNameFor(L"\\\\?\\" + f.dir.wstring(), &c)); + CHECK(!a.empty() && a == b && a == c); + const fs::path signal = f.dir / "held.txt"; + HANDLE p = Spawn(L"hold \"" + alias + L"\" 1500"); + for (int i = 0; i < 5000 && !fs::exists(signal); ++i) Sleep(1); + CHECK(fs::exists(signal)); + Record after; + std::string why; + CHECK(RecordChoice(f.record(), 'K', Source::Plugin, &after, &why, nullptr, 200) == Outcome::NoLock); + CHECK(p != nullptr && Wait(p) == 0); + CHECK(RecordChoice(f.record(), 'K', Source::Plugin, &after, &why, nullptr, 2000) == Outcome::Written && after.seq == 1); + std::error_code ec; + fs::remove(signal, ec); + CHECK(RemoveDirectoryW(alias.c_str()) != 0); // the junction only; the folder stays + CHECK(fs::exists(f.record())); +} + +int ChildApply(const fs::path& gameDir, bool crash) { + const fs::path record = RecordPathIn(gameDir); + Lock lock(record); + if (!lock.ok()) return 1; + WriteRaw(gameDir / "locked.txt", "1"); + Sleep(300); + WriteRaw(gameDir / "wronggpu.ini", "[fsr]\r\nruntime_options = model=L\r\n"); + if (crash) TerminateProcess(GetCurrentProcess(), 97); // dies holding the lock, before the record + Record after; + std::string why; + return RecordChoiceUnlocked(record, 'L', Source::Launcher, &after, &why) == Outcome::Written ? 0 : 2; +} + +int ChildHold(const std::wstring& gameDir, int ms) { + wgstate::StateLock lock(gameDir); + if (!lock.held()) return 1; + WriteRaw(fs::path(gameDir) / "held.txt", "1"); + Sleep(ms); + return 0; +} + int ChildWriter(const fs::path& record, char model, const std::string& source, int count) { const Source s = source == "launcher" ? Source::Launcher : source == "ffx" ? Source::Ffx : Source::Plugin; uint64_t last = 0; @@ -327,6 +417,7 @@ int ChildWriter(const fs::path& record, char model, const std::string& source, i } if (after.seq <= last) ++bad; // seq went back or stood still for this writer last = after.seq; + Sleep(0); // let the other processes take the lock between two writes } return bad; } @@ -336,16 +427,19 @@ int ChildReader(const fs::path& record, uint64_t until) { int bad = 0; const ULONGLONG start = GetTickCount64(); while (last < until && GetTickCount64() - start < 100000) { - Lock lock(record, 20000); - if (!lock.ok()) return 100; - Record r; - std::string why; - const ReadResult rr = ReadRecordFile(record, &r, &why); - if (rr == ReadResult::Corrupt || rr == ReadResult::Unreadable) ++bad; - if (rr == ReadResult::Ok) { - if (r.seq < last) ++bad; - last = r.seq; + { + Lock lock(record, 20000); + if (!lock.ok()) return 100; + Record r; + std::string why; + const ReadResult rr = ReadRecordFile(record, &r, &why); + if (rr == ReadResult::Corrupt || rr == ReadResult::Unreadable) ++bad; + if (rr == ReadResult::Ok) { + if (r.seq < last) ++bad; + last = r.seq; + } } + Sleep(1); // a Windows mutex is not fair: a reader that takes it again at once could keep the writers out } return bad + (last < until ? 1000 : 0); } @@ -357,6 +451,9 @@ int main(int argc, char** argv) { #ifdef _WIN32 if (argc >= 6 && std::string(argv[1]) == "writer") return ChildWriter(argv[2], argv[3][0], argv[4], std::atoi(argv[5])); if (argc >= 4 && std::string(argv[1]) == "reader") return ChildReader(argv[2], std::strtoull(argv[3], nullptr, 10)); + if (argc >= 3 && std::string(argv[1]) == "apply") return ChildApply(argv[2], false); + if (argc >= 3 && std::string(argv[1]) == "apply-and-die") return ChildApply(argv[2], true); + if (argc >= 4 && std::string(argv[1]) == "hold") return ChildHold(fs::path(argv[2]).wstring(), std::atoi(argv[3])); if (argc >= 3 && std::string(argv[1]) == "lock-and-die") { Lock lock(argv[2]); if (!lock.ok()) return 1; @@ -367,14 +464,15 @@ int main(int argc, char** argv) { (void)argv; #endif TestStrictFormat(); - TestLockName(); TestChoicesInTurn(); TestCorruptAndEnd(); TestMigration(); #ifdef _WIN32 - TestFailureAndRetry(); + TestFailures(); TestConcurrentProcesses(); TestAbandonedLock(); + TestMigrationUnderLock(); + TestAliasesOneLock(); #endif std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; diff --git a/clean/installer/src/app/launcher_ui.cpp b/clean/installer/src/app/launcher_ui.cpp index 649553f5..7c2e1355 100644 --- a/clean/installer/src/app/launcher_ui.cpp +++ b/clean/installer/src/app/launcher_ui.cpp @@ -1004,6 +1004,7 @@ void StartNextQueued() { void OnApply() { if (PageWritesWait()) return; // one rule for every write of the page (its Apply says why) OpRequest r; r.op = Op::Apply; r.dir = v.cur.dir; r.hasProfile = true; r.profile = v.edit; + r.modelChosen = FindSetting("model") != nullptr; // Apply with a model shown is the player's model choice, even unchanged for (size_t i = 0; i < v.opti.editable.size() && i < v.optiValues.size(); ++i) if (v.optiValues[i] != v.opti.editable[i].value) r.optiEdits.push_back({v.opti.editable[i].section + "." + v.opti.editable[i].key, v.optiValues[i]}); for (auto& e : r.optiEdits) { // the values typed are checked before anything is written diff --git a/clean/installer/src/wg_core/launcher.cpp b/clean/installer/src/wg_core/launcher.cpp index d945fd6e..4e70c637 100644 --- a/clean/installer/src/wg_core/launcher.cpp +++ b/clean/installer/src/wg_core/launcher.cpp @@ -1042,8 +1042,17 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto if (warnings) warnings->push_back(w); } } - string winiBefore, winiAfter; // the model choice record (below) - char forcedEntry = 0; // the model whose entry OptiScaler.ini's UpscalerIndex is set to (after the record) + // The game's state lock (wg_state.h, held by the launcher, the front end and the plugins for every read-modify-write + // of the game's state) is held across wronggpu.ini, the model choice record and OptiScaler.ini's entry: the front end's + // upgrade migration, which reads wronggpu.ini's model item under the same lock, comes wholly before or after this. + // Not taken in time (the game is writing its state): nothing is applied. + const std::filesystem::path recordPath = Join(StateDir(dir), wgchoice::kRecordFile); + wgchoice::Lock lock(recordPath); + if (!lock.ok()) + Fail(L"Settings not applied: the game is saving WrongGPU's state right now (" + FromUtf8(wgchoice::OutcomeWords(wgchoice::Outcome::NoLock)) + + L"). Try again.", + EXIT_REFUSED); + char forcedEntry = 0; // the model whose entry OptiScaler.ini's UpscalerIndex is set to (after the record) auto renderFile = [&](const wchar_t* name, bool opti) { const wstring path = Join(dir, name); string in; @@ -1059,9 +1068,13 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto for (auto& n : kGameNotices) if (IEq(BaseName(m.exe), n.exe)) notes.push_back(n.notice); JournalChanges(m.inikeys, name, in, out); recordChanged = recordChanged || out != in; + } else { + // the model is never written into wronggpu.ini (it is the model choice record's): its model item stays as the + // install wrote it, the install's default + Profile qw = q; + if (FindSetting("model")) qw.v["model"] = EffectiveSettings(in, "")["model"]; + if (!RenderWronggpuIni(qw, in, out, &why)) Fail(L"Settings not applied: " + why, EXIT_USAGE); } - else if (!RenderWronggpuIni(q, in, out, &why)) Fail(L"Settings not applied: " + why, EXIT_USAGE); - else { winiBefore = in; winiAfter = out; } if (out == in && (had || out.empty())) return; // unchanged, or nothing to write into a missing file WriteFileAtomic(path, out.data(), out.size()); const wstring h = Sha256Bytes(out.data(), out.size()); @@ -1070,34 +1083,27 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto }; renderFile(L"wronggpu.ini", false); // The model choice record (clean/fsr/src/model_choice_record.h): the launcher's model choice, with the next seq, when the - // player explicitly applied a model (also the same one again) or the model the files run changed. Under the record's - // cross-process lock (the game's front end and menu plugin take it too): the record first, then OptiScaler.ini's - // UpscalerIndex set to that model's entry whatever it was (display only: the front end never takes the index for a - // choice, so a crash between the two leaves nothing wrong). A model the files cannot run yet, written as Model M - // above, is recorded as what runs: Model M. - const char modelBefore = ModelOfWronggpuIni(winiBefore), modelAfter = ModelOfWronggpuIni(winiAfter); - const bool modelChoice = modelChosen || modelBefore != modelAfter; - const char model = modelAfter ? modelAfter : 'M'; - { - std::unique_ptr lock; - if (modelChoice) { - lock = std::make_unique(Join(StateDir(dir), wgchoice::kRecordFile)); - if (!lock->ok()) { - const wstring w = L"The model choice record was not changed: " + FromUtf8(wgchoice::OutcomeWords(wgchoice::Outcome::NoLock)) + - L" (the game holds it). Apply the model again."; - LogLine(ctx, w); - notes.push_back(w); - if (warnings) warnings->push_back(w); - } else if (WriteLauncherModelChoice(ctx, dir, model, notes, warnings)) { - forcedEntry = model; + // player applied a model (Apply in the launcher, or `set model=`: always, also the same model again, so it + // wins over a newer choice made in the game), when the game has no record yet (from the profile), or when the + // launcher's own last choice can no longer run as recorded (a model whose data is not ready: Model M until it is). + // Then OptiScaler.ini's UpscalerIndex is set to that model's entry whatever it was (display only: the front end never + // takes the index for a choice, so a crash between the two leaves nothing wrong). + if (FindSetting("model")) { + const string want = q.get("model"); + const char model = want == "l" ? 'L' : want == "k" ? 'K' : 'M'; + wgchoice::Record cur; + std::string err; + const wgchoice::ReadResult rr = wgchoice::ReadRecordFile(recordPath, &cur, &err); + const bool write = modelChosen || rr == wgchoice::ReadResult::Missing || + (rr == wgchoice::ReadResult::Ok && cur.source == wgchoice::Source::Launcher && cur.model != model); + if (write && WriteLauncherModelChoice(ctx, dir, model, notes, warnings)) { + forcedEntry = model; #ifdef WRONGGPU_TESTING - // tests: the apply ends here, after the record and before OptiScaler.ini (a crash between the two) - if (EnvVar(L"WRONGGPU_TEST_STOP_AFTER_CHOICE_RECORD") == L"1") TerminateProcess(GetCurrentProcess(), 97); + // tests: the apply ends here, after the record and before OptiScaler.ini (a crash between the two) + if (EnvVar(L"WRONGGPU_TEST_STOP_AFTER_CHOICE_RECORD") == L"1") TerminateProcess(GetCurrentProcess(), 97); #endif - } } - if (HostedRecord(m)) renderFile(L"OptiScaler.ini", true); - if (forcedEntry && HostedRecord(m)) { // the menu plugin's AMD entry chosen earlier: the launcher's model choice is newer + if (forcedEntry && modelChosen && HostedRecord(m)) { // the menu plugin's AMD entry chosen earlier: this choice is newer const wstring asi = Join(dir, L"wronggpu-asi.ini"); string text; if (ReadAll(asi, text) && wgasi::ParseSelection(text) == wgasi::kModelAmd) { @@ -1107,6 +1113,7 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto } } } + if (HostedRecord(m)) renderFile(L"OptiScaler.ini", true); if (RecordHasRr(m)) { // Ray Reconstruction (rr.h): the RR plugin's settings file (RR stays off while its data is not ready) const wstring path = Join(dir, kRrSettings); string in; diff --git a/clean/installer/src/wg_core/launcher.h b/clean/installer/src/wg_core/launcher.h index c6b066ee..64d0c002 100644 --- a/clean/installer/src/wg_core/launcher.h +++ b/clean/installer/src/wg_core/launcher.h @@ -180,7 +180,7 @@ struct OpRequest { std::vector> movePluginsList, moveModsList; bool otherSetupOk = false; // 0.6.1: Clean up / Adopt of WrongGPU files another mod's setup uses, confirmed (--confirm-other-setup) bool hasProfile = false; // apply: this profile (else the game's profile.ini); install: the profile a new install starts with - bool modelChosen = false; // apply: the player explicitly applied the profile's model (set model=...): recorded + bool modelChosen = false; // apply: the player applied the profile's model (the launcher's Apply, set model=...): recorded Profile profile; // apply, the OptiScaler tab: edits of editable keys ("Section.Key", value); reset: the editable keys back to what the // install wrote (inikey journal, byte for byte); keep: values OptiScaler's menu saved over the launcher's are kept. diff --git a/clean/installer/src/wg_core/profile.h b/clean/installer/src/wg_core/profile.h index d0597934..63e888fc 100644 --- a/clean/installer/src/wg_core/profile.h +++ b/clean/installer/src/wg_core/profile.h @@ -5,6 +5,7 @@ // (a bad runtime value makes the runtime's create fail and AMD's FSR takes over). Written for this project. #pragma once #include "settings.h" +#include "../../../wgshared/include/wg_model_entries.h" namespace wg { @@ -51,16 +52,16 @@ bool SetSetting(Profile& p, const string& key, const string& value, wstring* why // The refusal of the model setting in a build without the Model L choice (WRONGGPU_MODEL_L off). inline const wchar_t* const kNoModelChoice = L"Model L isn't part of this build of WrongGPU: it comes with a release that runs Model L. The game stays on Model M."; -// The index of Model L's entry in the list of upscalers WrongGPU's front end gives OptiScaler (its UpscalerIndex): after -// Model M and, in a build with Preset K, Model K. +// The indexes of Model K's and Model L's entries in the list of upscalers WrongGPU's front end gives OptiScaler (its +// UpscalerIndex), from the one shared definition (clean/wgshared/include/wg_model_entries.h): Model M, then Model K (a +// build with Model K or Preset K: the front end of the same payload lists it), then Model L. #if WRONGGPU_PRESET_K || WRONGGPU_MODEL_K -inline const char* const kModelLEntryIndex = "2"; +inline constexpr bool kListsModelK = true; #else -inline const char* const kModelLEntryIndex = "1"; +inline constexpr bool kListsModelK = false; #endif -// Model K's entry (a build with the Model K choice, WRONGGPU_MODEL_K): right after Model M's, as the installer's Preset K -// start has always written it. -inline const char* const kModelKEntryIndex = "1"; +inline const char* const kModelKEntryIndex = wgentries::IndexText(wgentries::ModelEntryIndex('K', true, true)); +inline const char* const kModelLEntryIndex = wgentries::IndexText(wgentries::ModelEntryIndex('L', kListsModelK, true)); // ---- wronggpu.ini -------------------------------------------------------------------------------------------- // The runtime_options items in order (split at ';', trimmed, empty items dropped). diff --git a/clean/installer/tests/run_model_k_tests.py b/clean/installer/tests/run_model_k_tests.py index a74dea97..fec248bf 100644 --- a/clean/installer/tests/run_model_k_tests.py +++ b/clean/installer/tests/run_model_k_tests.py @@ -66,8 +66,8 @@ def test_choice(t): rc = t.run("model", "convert", "--preset=K", "--model=" + ksrc) t.check("Model K's data converted (model convert --preset=K)", rc == 0 and ml.holds(t.model_path("K", "model.wgcm"), k_case()), (rc, t.j)) rc = t.run("set", exe, "model=K") - w = read(wini).decode("utf-8", "replace") - t.check("set model=K: exit 0; wronggpu.ini's last model item is model=K", rc == 0 and suite_options_model(w) == "K", (rc, t.j.get("message"), w)) + t.check("set model=K: exit 0; wronggpu.ini byte for byte as the install wrote it (the model is the record's, never written there)", + rc == 0 and read(wini) == m_w, (rc, t.j.get("message"), read(wini)[-200:])) o = read(oini).decode("utf-8", "replace") t.check("...OptiScaler's UpscalerIndex names Model K's entry (1: right after Model M)", upscaler_index(o) == "1", o) t.check("...the record's hashes follow both files (the file-ownership rule: they are WrongGPU's writes)", @@ -94,11 +94,11 @@ def test_choice(t): rc = t.run("model", "convert", "--preset=L", "--model=" + lsrc) t.check("L control: Model L's data converted", rc == 0, (rc, t.j)) rc = t.run("set", exe, "model=L") - t.check("L control: set model=L writes model=L and index 2 (after Model K's entry)", - rc == 0 and suite_options_model(read(wini).decode("utf-8", "replace")) == "L" and upscaler_index(read(oini).decode("utf-8", "replace")) == "2", - (rc, t.j.get("message"), read(wini), read(oini))) + t.check("L control: set model=L records L and sets index 2 (after Model K's entry); wronggpu.ini unchanged", + rc == 0 and choice_record(b).get("model") == "L" and upscaler_index(read(oini).decode("utf-8", "replace")) == "2" and read(wini) == m_w, + (rc, t.j.get("message"), choice_record(b), read(oini))) rc = t.run("set", exe, "model=K") - t.check("L to K: model=K and index 1", rc == 0 and suite_options_model(read(wini).decode("utf-8", "replace")) == "K" and + t.check("L to K: record K and index 1", rc == 0 and choice_record(b).get("model") == "K" and upscaler_index(read(oini).decode("utf-8", "replace")) == "1", (rc, t.j.get("message"))) rc = t.run("set", exe, "model=L") rc2 = t.run("set", exe, "model=M") @@ -108,9 +108,9 @@ def test_choice(t): os.remove(os.path.join(t.lad, "WrongGPU", "model", "K", "model.wgcm")) rc = t.run("repair", exe, "--opti=" + opti, "--force") msgs = " ".join(t.j.get("warnings", []) + t.j.get("notes", [])) - t.check("repair of a game set to K without Model K's data: exit 0, the files say Model M, the player is told how to convert it", - rc == 0 and suite_options_model(read(wini).decode("utf-8", "replace")) == "M" and "Model K's data on this PC is not ready" in msgs and - "model convert --preset=K" in msgs, (rc, t.j.get("message"), msgs[:600])) + t.check("repair of a game set to K without Model K's data: exit 0, the record says Model M, the player is told how to convert it", + rc == 0 and choice_record(b).get("model") == "M" and "Model K's data on this PC is not ready" in msgs and + "model convert --preset=K" in msgs, (rc, t.j.get("message"), msgs[:600], choice_record(b))) t.check("...the choice stays in profile.ini (model=k)", b"model=k\r\n" in profile_text(b)) rc = t.run("uninstall", exe) # A build with Preset K seeds the plugin's own settings file wronggpu-asi.ini on every OptiScaler install; an uninstall leaves diff --git a/clean/installer/tests/run_model_l_tests.py b/clean/installer/tests/run_model_l_tests.py index 18975383..0c0f2d4d 100644 --- a/clean/installer/tests/run_model_l_tests.py +++ b/clean/installer/tests/run_model_l_tests.py @@ -282,8 +282,8 @@ def test_choice(t): rc = t.run("model", "convert", "--preset=L", "--model=" + lsrc) t.check("Model L's data converted (model convert --preset=L)", rc == 0, (rc, t.j)) rc = t.run("set", exe, "model=L") - w = read(wini).decode("utf-8", "replace") - t.check("set model=L: exit 0; wronggpu.ini's last model item is model=L", rc == 0 and suite_options_model(w) == "L", (rc, t.j.get("message"), w)) + t.check("set model=L: exit 0; wronggpu.ini byte for byte as the install wrote it (the model is the record's, never written there)", + rc == 0 and read(wini) == m_w, (rc, t.j.get("message"), read(wini)[-200:])) t.check("...OptiScaler's UpscalerIndex names Model L's entry (1: after Model M in a build without Preset K)", upscaler_index(read(oini).decode("utf-8", "replace")) == "1", read(oini).decode("utf-8", "replace")) t.check("...the record's hashes follow both files (the file-ownership rule: they are WrongGPU's writes)", @@ -296,7 +296,23 @@ def test_choice(t): rc = t.run("set", exe, "model=L") r2 = choice_record(b) t.check("set model=L again: the record's seq grows (the newest choice); wronggpu.ini and OptiScaler.ini unchanged", - rc == 0 and r2.get("model") == "L" and int(r2.get("seq", "0")) == int(r1.get("seq", "0")) + 1, (r1, r2)) + rc == 0 and r2.get("model") == "L" and int(r2.get("seq", "0")) == int(r1.get("seq", "0")) + 1 and read(wini) == m_w, (r1, r2)) + # an explicit model choice in the launcher (set model=..., or the launcher's Apply) wins over a NEWER choice made in the + # game even when the profile's model is unchanged; a launcher change of another setting does not touch the record + rec_path = os.path.join(b, "wronggpu-setup", "model-choice.ini") + newer = int(r2.get("seq", "0")) + 1 + write(rec_path, ("model=M\r\nseq=%d\r\nsource=plugin\r\n" % newer).encode("ascii")) + o_before = read(oini) + rc = t.run("set", exe, "fps_overlay=on") + t.check("set fps_overlay=on: the plugin's newer choice (M) stays the record", rc == 0 and choice_record(b) == {"model": "M", "seq": str(newer), "source": "plugin"}, + (rc, choice_record(b))) + rc = t.run("set", exe, "fps_overlay=keep") # ("keep" leaves the key as it is: the file goes back by hand, and + write(oini, o_before) # the next model choice rewrites it and its hash) + rc = t.run("set", exe, "model=L") + r2b = choice_record(b) + t.check("set model=L (the profile already says L) after the plugin's newer M: L is recorded with the next seq", + rc == 0 and r2b.get("model") == "L" and r2b.get("source") == "launcher" and int(r2b.get("seq", "0")) == newer + 1, r2b) + r2 = r2b rc = t.run("set", exe, "model=M") t.check("set model=M: wronggpu.ini and OptiScaler.ini back byte for byte as the install wrote them", rc == 0 and read(wini) == m_w and read(oini) == m_o, (rc, read(wini)[-200:], read(oini)[-200:])) @@ -343,9 +359,10 @@ def test_choice(t): os.remove(os.path.join(t.lad, "WrongGPU", "model", "L", "model.wgcm")) # (t.model is the case here, not the path helper) rc = t.run("repair", exe, "--opti=" + opti, "--force") msgs = " ".join(t.j.get("warnings", []) + t.j.get("notes", [])) - t.check("repair of a game set to L without Model L's data: exit 0, the files say Model M, the player is told how to convert it", - rc == 0 and suite_options_model(read(wini).decode("utf-8", "replace")) == "M" and "Model L's data on this PC is not ready" in msgs and - "model convert --preset=L" in msgs, (rc, t.j.get("message"), msgs[:600])) + t.check("repair of a game set to L without Model L's data: exit 0, the record says Model M (the launcher's own choice can't run)," + " the player is told how to convert it", + rc == 0 and choice_record(b).get("model") == "M" and choice_record(b).get("source") == "launcher" and + "Model L's data on this PC is not ready" in msgs and "model convert --preset=L" in msgs, (rc, t.j.get("message"), msgs[:600], choice_record(b))) t.check("...the choice stays in profile.ini (model=l)", b"model=l\r\n" in read(os.path.join(b, "wronggpu-setup", "profile.ini"))) rc = t.run("uninstall", exe) t.check("uninstall: the game folder byte for byte as before the install", rc == 0 and suite.snapshot(root) == before, (rc, suite.diff(before, suite.snapshot(root)))) diff --git a/clean/wgshared/include/wg_model_entries.h b/clean/wgshared/include/wg_model_entries.h new file mode 100644 index 00000000..b0966641 --- /dev/null +++ b/clean/wgshared/include/wg_model_entries.h @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: MIT +#pragma once +// The ONE definition of where WrongGPU's model entries are in the list of upscaler versions the front end gives a host +// (FFX_API_QUERY_DESC_TYPE_GET_VERSIONS: frontend.cpp ListVersions, from the registry's SR model rows). A host such as +// OptiScaler stores the player's entry as its position in that list (UpscalerIndex; OptiScaler shows the list sorted, but +// the index it stores is the position in the list the DLL returned), so this order is what the launcher writes: +// Model M first, then Model K (a build with Model K), then Model L (a build with Model L). +// The launcher (profile.h: kModelKEntryIndex / kModelLEntryIndex) and the front end use it; test_frontend +// (TestModelEntryOrder) fails when the list ListVersions returns and this order disagree, for each build's K / L flags. +// The index is for display only: which model runs is the model choice record's (clean/fsr/src/model_choice_record.h). + +namespace wgentries { + +// The position of `model`'s entry ('M', 'K', 'L') in a build with or without Model K and Model L; -1 when the build does +// not list that model. +constexpr int ModelEntryIndex(char model, bool withK, bool withL) { + return model == 'M' ? 0 : model == 'K' ? (withK ? 1 : -1) : model == 'L' ? (withL ? (withK ? 2 : 1) : -1) : -1; +} + +// The same as the decimal text an ini holds ("0", "1", "2"; nullptr for -1). +constexpr const char* IndexText(int index) { return index == 0 ? "0" : index == 1 ? "1" : index == 2 ? "2" : nullptr; } + +} // namespace wgentries From 8d048d7081847392e8e2faa9c639505d1810530d Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:38:24 -0500 Subject: [PATCH 09/15] Model choice: register as loaded before any state is read (wg_state.h) The front end and the menu plugin follow wg_state.h's loaded protocol (#226): each registers under the game's state lock before it reads or writes any state (LoadedRegistration), keeping its loaded marker open while loaded. When the registration fails (an uninstall, repair or update holds the lock), the record is neither read nor written that session: the front end runs wronggpu.ini's model item (else Model M) and a host selection returns "not saved"; a plugin click is not saved. Test: a front end that could not register reads and writes nothing and runs wronggpu.ini's item. Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/fsr/asi/wronggpu_asi.cpp | 17 +++++++++++++---- clean/fsr/src/dllmain.cpp | 13 +++++++++---- clean/fsr/src/frontend.cpp | 11 +++++++++++ clean/fsr/src/frontend.h | 3 +++ clean/fsr/tests/test_frontend.cpp | 15 +++++++++++++++ 5 files changed, 51 insertions(+), 8 deletions(-) diff --git a/clean/fsr/asi/wronggpu_asi.cpp b/clean/fsr/asi/wronggpu_asi.cpp index 0b4edb9c..fb7f9d99 100644 --- a/clean/fsr/asi/wronggpu_asi.cpp +++ b/clean/fsr/asi/wronggpu_asi.cpp @@ -113,8 +113,14 @@ std::wstring RecordPath() { // game's state lock (model_choice_record.h; waited for 1 second at most, on the menu thread). A click that cannot be // written is NOT kept: nothing changes, the menu says "not saved, try again" (SelectableThunkLogic) and the log says why. // At the end of the sequence numbers the click is refused, logged and said in the menu. +std::atomic g_stateOk{false}; // registered as loaded in the game (InitializeASI): the record may be written + wgasi::Save RecordModelChoice(char model) { const std::wstring path = RecordPath(); + if (!g_stateOk.load()) { + AsiLog::Get().Write(std::string("ERROR: model choice record: Model ") + model + " not saved: WrongGPU's state is not used this session"); + return wgasi::Save::NotSaved; + } wgchoice::Record after; std::string why; const wgchoice::Outcome o = wgchoice::RecordChoice(path, model, wgchoice::Source::Plugin, &after, &why, nullptr, 1000); @@ -323,10 +329,13 @@ extern "C" __declspec(dllexport) __declspec(noinline) void InitializeASI() { std::call_once(g_initOnce, [caller] { g_diagnostics.Begin(); AsiLog::Get().Write("InitializeASI"); - // While the plugin is loaded in the game it keeps WrongGPU's loaded marker of the game folder open (wg_state.h): - // the launcher refuses an uninstall, repair or update meanwhile. Never released: the OS drops it with the process. - static wgstate::LoadedMarker* marker = new wgstate::LoadedMarker(wgasi::PluginDataDir()); - if (!marker->held()) AsiLog::Get().Writef("the loaded marker could not be created (error %lu)", marker->error()); + // Before it reads or writes any state, the plugin registers as loaded in the game (wg_state.h's loaded protocol; + // its marker kept open while loaded, so the launcher refuses an uninstall, repair or update meanwhile; never + // released: the OS drops it with the process). Not registered in time: no record writes this session. + static wgstate::LoadedRegistration* registration = new wgstate::LoadedRegistration(wgasi::PluginDataDir()); + g_stateOk.store(registration->ok()); + if (!registration->ok()) + AsiLog::Get().Writef("WrongGPU's state is not used this session: %s (error %lu)", registration->why(), registration->error()); Hook(caller); g_diagnostics.Complete(); }); diff --git a/clean/fsr/src/dllmain.cpp b/clean/fsr/src/dllmain.cpp index 145d20e7..0af483ff 100644 --- a/clean/fsr/src/dllmain.cpp +++ b/clean/fsr/src/dllmain.cpp @@ -251,10 +251,15 @@ FrontEnd& Get() { wgchoice::RecordPathIn(slash == std::wstring::npos ? std::wstring(L".") : ini.substr(0, slash)); std::error_code ec; if (std::filesystem::is_directory(record.parent_path(), ec)) { // a launcher install: its state folder - // While this DLL is loaded the game keeps WrongGPU's loaded marker open (wg_state.h): the launcher refuses - // an uninstall, repair or update meanwhile. Never released: the OS drops it with the process. - static wgstate::LoadedMarker* marker = new wgstate::LoadedMarker(wgchoice::GameDirOf(record).wstring()); - if (!marker->held()) L().Write("model choice: the loaded marker could not be created (error %lu)", marker->error()); + // Before it reads any state, the front end registers as loaded in the game (wg_state.h's loaded protocol: + // under the state lock, its loaded marker kept open while the DLL is loaded, so the launcher refuses an + // uninstall, repair or update meanwhile; never released: the OS drops it with the process). Not registered + // in time (an uninstall, repair or update is running): no state this session, the defaults run. + static wgstate::LoadedRegistration* registration = new wgstate::LoadedRegistration(wgchoice::GameDirOf(record).wstring()); + if (!registration->ok()) { + L().Write("model choice: WrongGPU's state is not used this session: %s (error %lu)", registration->why(), registration->error()); + p.stateUnavailable = registration->why(); + } p.choiceRecord = record; p.readWronggpuIni = [ini] { // the upgrade migration reads wronggpu.ini's model item under the state lock std::string text; diff --git a/clean/fsr/src/frontend.cpp b/clean/fsr/src/frontend.cpp index bbc4ef2f..ef9dd175 100644 --- a/clean/fsr/src/frontend.cpp +++ b/clean/fsr/src/frontend.cpp @@ -1444,6 +1444,12 @@ char FrontEnd::ChooseModel(char plugin, char entry, const std::string& tag, std: *why = launcher ? std::string("no model choice record; wronggpu.ini model=") + launcher : std::string("no model choice record; the default"); return 'M'; } + if (!platform_.stateUnavailable.empty()) { + const char ini = LauncherModel(); + *why = "WrongGPU's state is not used this session (" + platform_.stateUnavailable + ")" + + (ini ? std::string("; wronggpu.ini model=") + ini : std::string("; the default")); + return ini ? ini : 'M'; + } std::lock_guard lock(choiceMutex_); // the record cannot be used now: the last record this session read or wrote, else wronggpu.ini's model item, else M // (never the host's stored entry) @@ -1505,6 +1511,11 @@ int32_t FrontEnd::HostSelected(uint64_t versionId) { "state folder): the host's entry decides"); return WG_HOST_SELECTED_NOTHING_CHANGED; } + if (!platform_.stateUnavailable.empty()) { + Log(tag + " ERROR: the player selected Model " + model + " in OptiScaler's upscaler list, but WrongGPU's state is not used this " + "session (" + platform_.stateUnavailable + "): not saved"); + return WG_HOST_SELECTED_NOT_SAVED; + } std::lock_guard lock(choiceMutex_); wgchoice::Record after, before; std::string err; diff --git a/clean/fsr/src/frontend.h b/clean/fsr/src/frontend.h index f7f6ac1c..10119d78 100644 --- a/clean/fsr/src/frontend.h +++ b/clean/fsr/src/frontend.h @@ -101,6 +101,9 @@ struct Platform { // wronggpu.ini's text as it is on disk now (the record's upgrade migration reads its model item while it holds the // game's state lock). Empty: the model item of the configuration read at start. std::function readWronggpuIni; + // Not empty: the front end could not register as loaded in the game (wg_state.h LoadedRegistration; the reason): the + // record is neither read nor written this session; wronggpu.ini's model item (else Model M) runs. + std::string stateUnavailable; // Registry options and the menu's choices (shared settings block). Empty members: defaults, nothing written. MenuSettings menu; }; diff --git a/clean/fsr/tests/test_frontend.cpp b/clean/fsr/tests/test_frontend.cpp index 3dc9a98c..bf8675ae 100644 --- a/clean/fsr/tests/test_frontend.cpp +++ b/clean/fsr/tests/test_frontend.cpp @@ -248,6 +248,7 @@ static char g_asiModel = 0; // 0 (AMD), 'M', 'K' static std::vector g_asiShown; // Platform::asiShowModel calls static std::filesystem::path g_choiceRecord; // Platform::choiceRecord (a real file; empty: none) static std::string g_iniOnDisk; // Platform::readWronggpuIni (empty: not wired); not cleared by Reset +static std::string g_stateUnavailable; // Platform::stateUnavailable (not registered as loaded); not cleared by Reset // Fake shared settings (Platform::menu, settings_bridge.h in the DLL): values set "somewhere" (block / env / ini), // the writes of the menu's choices, whether this module is the writer, the folder sidecar's entry. @@ -292,6 +293,7 @@ static std::unique_ptr MakeFrontEnd(const Config& config) { p.asiPlugin = [](char* model) { if (model) *model = g_asiModel; return g_asiHooked; }; if (g_asiPresent) p.asiShowModel = [](char model) { g_asiShown.push_back(model); }; if (!g_iniOnDisk.empty()) p.readWronggpuIni = [] { return g_iniOnDisk; }; + p.stateUnavailable = g_stateUnavailable; p.choiceRecord = g_choiceRecord; p.compareApi = []() -> const OriginalApi* { return g_compareApi; }; p.backend = [](const Config&, std::string&) -> const WgUpscalerBackend* { return g_useBackend; }; @@ -2900,6 +2902,19 @@ static void TestAsiChoiceRecord() { r = ReadRec(rec); CHECK(rc == WG_HOST_SELECTED_REFUSED && r.model == b && r.seq == UINT64_MAX); CHECK(CountLog("ERROR: the player selected Model M in OptiScaler's upscaler list: the record's sequence number is at its end") == 1); + // (16) the front end could not register as loaded in the game (wg_state.h: an uninstall, repair or update running): + // the record is neither read nor written this session; wronggpu.ini's item runs; a selection is not saved + WriteRec(rec, "model=M\nseq=3\nsource=launcher\n"); + g_stateUnavailable = "the game's state lock was not free in time"; + { + auto fe = ChoiceFrontEnd(iniB.c_str(), 0, false); + CHECK(ChoiceCreate(*fe, idOf('M')) == name(b)); + CHECK(CountLog("WrongGPU's state is not used this session (the game's state lock was not free in time); wronggpu.ini model=") == 1); + CHECK(fe->HostSelected(idOf('M')) == WG_HOST_SELECTED_NOT_SAVED); + } + g_stateUnavailable.clear(); + r = ReadRec(rec); + CHECK(r.model == 'M' && r.seq == 3); } else { // Model M only: the record is migrated (M, seq 1, launcher) and says what runs CHECK(HostedCreate("runtime_options = model=M\n", 'M', idOf('M')) == name('M')); From 36d8440d121c9fb9733fba065e4226d1087ecb06 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:43:03 -0500 Subject: [PATCH 10/15] Model choice record: the header says who writes it (the launcher's Apply and set, always) Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/fsr/src/model_choice_record.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/clean/fsr/src/model_choice_record.h b/clean/fsr/src/model_choice_record.h index 16bcb027..8dbb9024 100644 --- a/clean/fsr/src/model_choice_record.h +++ b/clean/fsr/src/model_choice_record.h @@ -6,11 +6,12 @@ // model runs, on every route; wronggpu.ini's model item is the install's default, which no WrongGPU program rewrites // after the install and which only seeds the record of a game that has none (the upgrade below). Three places write the // record, each only for an EVENT, a choice the player made: -// - the launcher, when it applies a model (`WrongGPU.exe set model=`, or a change of the model item); it then -// sets OptiScaler's UpscalerIndex to that model's entry, for display only; +// - the launcher, when the player applies a model (the launcher's Apply, or `WrongGPU.exe set model=`: always, +// also the same model again); it then sets OptiScaler's UpscalerIndex to that model's entry, for display only (and it +// seeds the record of a game without one from its profile); // - the front end, when OptiScaler tells it that the player selected one of WrongGPU's entries in its upscaler list -// during the session (the WrongGPU edition of OptiScaler calls WrongGpuHostSelectedV1 in the front-end DLL); the -// stored index OptiScaler passes at a create is never taken for a choice; +// (the WrongGPU edition of OptiScaler calls WrongGpuHostSelectedV1 in the front-end DLL); the stored index OptiScaler +// passes at a create is never taken for a choice; // - the WrongGPU menu plugin (clean/fsr/asi), when the player clicks one of its model entries. // "Most recent" is the highest sequence number. Every read-modify-write (read, seq + 1, write) runs under the game's // state lock (wgstate::StateLock, one named mutex per game folder, shared by every WrongGPU program and by settings.ini's From 4d7fa3a7efecbc2d1afd9cb85c057c3f2a250be8 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:49:26 -0500 Subject: [PATCH 11/15] Model choice record: wg_state.h's WriteResult (its words in the reason) Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/fsr/src/model_choice_record.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/clean/fsr/src/model_choice_record.h b/clean/fsr/src/model_choice_record.h index 8dbb9024..02ee5ff5 100644 --- a/clean/fsr/src/model_choice_record.h +++ b/clean/fsr/src/model_choice_record.h @@ -179,12 +179,13 @@ inline ReadResult ReadRecordFile(const std::filesystem::path& path, Record* out, // up to `attempts` times, 20 ms apart. false with *why. Call it under the record's Lock. inline bool WriteRecordFile(const std::filesystem::path& path, const Record& r, std::string* why, int attempts = 3) { const std::string text = FormatRecord(r); - DWORD err = 0; + wgstate::WriteResult w; for (int i = 0; i < attempts; ++i) { - if (wgstate::WriteAtomic(path.wstring(), text, &err)) return true; + w = wgstate::WriteAtomic(path.wstring(), text); + if (w.ok) return true; if (i + 1 < attempts) Sleep(20); } - if (why) *why = "cannot replace the record (Windows error " + std::to_string(err) + ")"; + if (why) *why = "cannot replace the record: " + w.words(); return false; } From 2ad053b398a4367e0934b5eb62f5caf1703e48ac Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:57:10 -0500 Subject: [PATCH 12/15] Model choice: the game side registers nothing (the loaded marker is dropped) Design change from the wg_state.h re-check: whether a game is using WrongGPU is decided by the launcher opening WrongGPU's binaries in the game folder exclusively, so the front end and the menu plugin no longer register as loaded or hold a marker. The record keeps wg_state.h's state lock and atomic write. The record test's reader reports a read another program briefly refused (a virus scanner looking at the new file) instead of failing on it; a corrupt record or seq going back still fails, and every reader and writer failure is printed. Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/fsr/asi/README.md | 3 +-- clean/fsr/asi/wronggpu_asi.cpp | 13 ------------- clean/fsr/src/dllmain.cpp | 9 --------- clean/fsr/src/frontend.cpp | 11 ----------- clean/fsr/src/frontend.h | 3 --- clean/fsr/tests/test_frontend.cpp | 15 --------------- clean/fsr/tests/test_model_choice_record.cpp | 16 ++++++++++++---- 7 files changed, 13 insertions(+), 57 deletions(-) diff --git a/clean/fsr/asi/README.md b/clean/fsr/asi/README.md index 3743daba..a38cfac7 100644 --- a/clean/fsr/asi/README.md +++ b/clean/fsr/asi/README.md @@ -35,8 +35,7 @@ named mutex per game folder, from its volume and file identity, shared with ever A click that cannot be saved in time changes nothing: its entry says "not saved, try again" and nothing is kept for later. When the record cannot be read, is corrupt or busy at a create, the front end runs the last choice it read this session, else wronggpu.ini's model item, else Model M. Without a record (no launcher state folder) the launcher's Model K / L item -decides, else the plugin's saved entry, else Model M. While the game has the plugin loaded it keeps WrongGPU's loaded -marker open, so the launcher does not uninstall, repair or update it meanwhile. The front end logs the model and which +decides, else the plugin's saved entry, else Model M. The front end logs the model and which choice decided and tells the plugin which model runs (`WrongGpuAsiShowModelV1`), so the menu marks that entry. Model L's own entry ("WrongGPU Model L") is in the menu of a build with `WG_MODEL_L`; a model the front end was built without runs as Model M, with a note in the log. diff --git a/clean/fsr/asi/wronggpu_asi.cpp b/clean/fsr/asi/wronggpu_asi.cpp index fb7f9d99..34430675 100644 --- a/clean/fsr/asi/wronggpu_asi.cpp +++ b/clean/fsr/asi/wronggpu_asi.cpp @@ -113,14 +113,8 @@ std::wstring RecordPath() { // game's state lock (model_choice_record.h; waited for 1 second at most, on the menu thread). A click that cannot be // written is NOT kept: nothing changes, the menu says "not saved, try again" (SelectableThunkLogic) and the log says why. // At the end of the sequence numbers the click is refused, logged and said in the menu. -std::atomic g_stateOk{false}; // registered as loaded in the game (InitializeASI): the record may be written - wgasi::Save RecordModelChoice(char model) { const std::wstring path = RecordPath(); - if (!g_stateOk.load()) { - AsiLog::Get().Write(std::string("ERROR: model choice record: Model ") + model + " not saved: WrongGPU's state is not used this session"); - return wgasi::Save::NotSaved; - } wgchoice::Record after; std::string why; const wgchoice::Outcome o = wgchoice::RecordChoice(path, model, wgchoice::Source::Plugin, &after, &why, nullptr, 1000); @@ -329,13 +323,6 @@ extern "C" __declspec(dllexport) __declspec(noinline) void InitializeASI() { std::call_once(g_initOnce, [caller] { g_diagnostics.Begin(); AsiLog::Get().Write("InitializeASI"); - // Before it reads or writes any state, the plugin registers as loaded in the game (wg_state.h's loaded protocol; - // its marker kept open while loaded, so the launcher refuses an uninstall, repair or update meanwhile; never - // released: the OS drops it with the process). Not registered in time: no record writes this session. - static wgstate::LoadedRegistration* registration = new wgstate::LoadedRegistration(wgasi::PluginDataDir()); - g_stateOk.store(registration->ok()); - if (!registration->ok()) - AsiLog::Get().Writef("WrongGPU's state is not used this session: %s (error %lu)", registration->why(), registration->error()); Hook(caller); g_diagnostics.Complete(); }); diff --git a/clean/fsr/src/dllmain.cpp b/clean/fsr/src/dllmain.cpp index 0af483ff..8425b131 100644 --- a/clean/fsr/src/dllmain.cpp +++ b/clean/fsr/src/dllmain.cpp @@ -251,15 +251,6 @@ FrontEnd& Get() { wgchoice::RecordPathIn(slash == std::wstring::npos ? std::wstring(L".") : ini.substr(0, slash)); std::error_code ec; if (std::filesystem::is_directory(record.parent_path(), ec)) { // a launcher install: its state folder - // Before it reads any state, the front end registers as loaded in the game (wg_state.h's loaded protocol: - // under the state lock, its loaded marker kept open while the DLL is loaded, so the launcher refuses an - // uninstall, repair or update meanwhile; never released: the OS drops it with the process). Not registered - // in time (an uninstall, repair or update is running): no state this session, the defaults run. - static wgstate::LoadedRegistration* registration = new wgstate::LoadedRegistration(wgchoice::GameDirOf(record).wstring()); - if (!registration->ok()) { - L().Write("model choice: WrongGPU's state is not used this session: %s (error %lu)", registration->why(), registration->error()); - p.stateUnavailable = registration->why(); - } p.choiceRecord = record; p.readWronggpuIni = [ini] { // the upgrade migration reads wronggpu.ini's model item under the state lock std::string text; diff --git a/clean/fsr/src/frontend.cpp b/clean/fsr/src/frontend.cpp index ef9dd175..bbc4ef2f 100644 --- a/clean/fsr/src/frontend.cpp +++ b/clean/fsr/src/frontend.cpp @@ -1444,12 +1444,6 @@ char FrontEnd::ChooseModel(char plugin, char entry, const std::string& tag, std: *why = launcher ? std::string("no model choice record; wronggpu.ini model=") + launcher : std::string("no model choice record; the default"); return 'M'; } - if (!platform_.stateUnavailable.empty()) { - const char ini = LauncherModel(); - *why = "WrongGPU's state is not used this session (" + platform_.stateUnavailable + ")" + - (ini ? std::string("; wronggpu.ini model=") + ini : std::string("; the default")); - return ini ? ini : 'M'; - } std::lock_guard lock(choiceMutex_); // the record cannot be used now: the last record this session read or wrote, else wronggpu.ini's model item, else M // (never the host's stored entry) @@ -1511,11 +1505,6 @@ int32_t FrontEnd::HostSelected(uint64_t versionId) { "state folder): the host's entry decides"); return WG_HOST_SELECTED_NOTHING_CHANGED; } - if (!platform_.stateUnavailable.empty()) { - Log(tag + " ERROR: the player selected Model " + model + " in OptiScaler's upscaler list, but WrongGPU's state is not used this " - "session (" + platform_.stateUnavailable + "): not saved"); - return WG_HOST_SELECTED_NOT_SAVED; - } std::lock_guard lock(choiceMutex_); wgchoice::Record after, before; std::string err; diff --git a/clean/fsr/src/frontend.h b/clean/fsr/src/frontend.h index 10119d78..f7f6ac1c 100644 --- a/clean/fsr/src/frontend.h +++ b/clean/fsr/src/frontend.h @@ -101,9 +101,6 @@ struct Platform { // wronggpu.ini's text as it is on disk now (the record's upgrade migration reads its model item while it holds the // game's state lock). Empty: the model item of the configuration read at start. std::function readWronggpuIni; - // Not empty: the front end could not register as loaded in the game (wg_state.h LoadedRegistration; the reason): the - // record is neither read nor written this session; wronggpu.ini's model item (else Model M) runs. - std::string stateUnavailable; // Registry options and the menu's choices (shared settings block). Empty members: defaults, nothing written. MenuSettings menu; }; diff --git a/clean/fsr/tests/test_frontend.cpp b/clean/fsr/tests/test_frontend.cpp index bf8675ae..3dc9a98c 100644 --- a/clean/fsr/tests/test_frontend.cpp +++ b/clean/fsr/tests/test_frontend.cpp @@ -248,7 +248,6 @@ static char g_asiModel = 0; // 0 (AMD), 'M', 'K' static std::vector g_asiShown; // Platform::asiShowModel calls static std::filesystem::path g_choiceRecord; // Platform::choiceRecord (a real file; empty: none) static std::string g_iniOnDisk; // Platform::readWronggpuIni (empty: not wired); not cleared by Reset -static std::string g_stateUnavailable; // Platform::stateUnavailable (not registered as loaded); not cleared by Reset // Fake shared settings (Platform::menu, settings_bridge.h in the DLL): values set "somewhere" (block / env / ini), // the writes of the menu's choices, whether this module is the writer, the folder sidecar's entry. @@ -293,7 +292,6 @@ static std::unique_ptr MakeFrontEnd(const Config& config) { p.asiPlugin = [](char* model) { if (model) *model = g_asiModel; return g_asiHooked; }; if (g_asiPresent) p.asiShowModel = [](char model) { g_asiShown.push_back(model); }; if (!g_iniOnDisk.empty()) p.readWronggpuIni = [] { return g_iniOnDisk; }; - p.stateUnavailable = g_stateUnavailable; p.choiceRecord = g_choiceRecord; p.compareApi = []() -> const OriginalApi* { return g_compareApi; }; p.backend = [](const Config&, std::string&) -> const WgUpscalerBackend* { return g_useBackend; }; @@ -2902,19 +2900,6 @@ static void TestAsiChoiceRecord() { r = ReadRec(rec); CHECK(rc == WG_HOST_SELECTED_REFUSED && r.model == b && r.seq == UINT64_MAX); CHECK(CountLog("ERROR: the player selected Model M in OptiScaler's upscaler list: the record's sequence number is at its end") == 1); - // (16) the front end could not register as loaded in the game (wg_state.h: an uninstall, repair or update running): - // the record is neither read nor written this session; wronggpu.ini's item runs; a selection is not saved - WriteRec(rec, "model=M\nseq=3\nsource=launcher\n"); - g_stateUnavailable = "the game's state lock was not free in time"; - { - auto fe = ChoiceFrontEnd(iniB.c_str(), 0, false); - CHECK(ChoiceCreate(*fe, idOf('M')) == name(b)); - CHECK(CountLog("WrongGPU's state is not used this session (the game's state lock was not free in time); wronggpu.ini model=") == 1); - CHECK(fe->HostSelected(idOf('M')) == WG_HOST_SELECTED_NOT_SAVED); - } - g_stateUnavailable.clear(); - r = ReadRec(rec); - CHECK(r.model == 'M' && r.seq == 3); } else { // Model M only: the record is migrated (M, seq 1, launcher) and says what runs CHECK(HostedCreate("runtime_options = model=M\n", 'M', idOf('M')) == name('M')); diff --git a/clean/fsr/tests/test_model_choice_record.cpp b/clean/fsr/tests/test_model_choice_record.cpp index 3e55977d..dcf92896 100644 --- a/clean/fsr/tests/test_model_choice_record.cpp +++ b/clean/fsr/tests/test_model_choice_record.cpp @@ -299,7 +299,9 @@ void TestConcurrentProcesses() { if (w && Wait(w) != 0) ++failed; } CHECK(failed == 0); - CHECK(reader != nullptr && Wait(reader) == 0); + const DWORD readerCode = reader ? Wait(reader) : 999; + if (readerCode != 0) std::printf("reader exit %lu\n", static_cast(readerCode)); + CHECK(readerCode == 0); Record r = Rec(f.record()); CHECK(r.seq == uint64_t(kWriters * kWrites)); // no lost update std::printf("concurrent processes: %d writers x %d writes, final seq %llu\n", kWriters, kWrites, static_cast(r.seq)); @@ -429,13 +431,19 @@ int ChildReader(const fs::path& record, uint64_t until) { while (last < until && GetTickCount64() - start < 100000) { { Lock lock(record, 20000); - if (!lock.ok()) return 100; + if (!lock.ok()) { std::printf("reader: lock not taken\n"); return 100; } Record r; std::string why; const ReadResult rr = ReadRecordFile(record, &r, &why); - if (rr == ReadResult::Corrupt || rr == ReadResult::Unreadable) ++bad; + // a partial or corrupt record would be a failure; a read another program (a virus scanner looking at the new + // file) briefly refused is not, and is only reported + if (rr == ReadResult::Corrupt) { + ++bad; + std::printf("reader: corrupt (%s)\n", why.c_str()); + } + if (rr == ReadResult::Unreadable) std::printf("reader: one read refused (%s)\n", why.c_str()); if (rr == ReadResult::Ok) { - if (r.seq < last) ++bad; + if (r.seq < last) { ++bad; std::printf("reader: seq went back %llu -> %llu\n", (unsigned long long)last, (unsigned long long)r.seq); } last = r.seq; } } From b0645d89898ae089de721f35d42b2c3564303c1b Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:30:08 -0500 Subject: [PATCH 13/15] Model choice: compare with the running model, record route always, Apply leaves wronggpu.ini Review of #213 (fifth round): - The host event compares the selection with the model the active context runs, not with the earlier record: it returns 1 whenever the selection differs from what runs (also when a launcher Apply changed the record while the game is open), so the host recreates. - The front end always takes the model choice route. Without the state folder (wronggpu-setup), or when it cannot be checked: the session's last choice, else wronggpu.ini's model item, else Model M. The host's stored entry and the plugin's saved entry never choose the model; the legacy host-entry route is removed. An event that cannot be saved returns "not saved". - Apply does not rewrite wronggpu.ini at all (the settings it applied there move to wronggpu-setup\settings.ini with #224). A missing or unreadable OptiScaler.ini: the record is still written and the player is told "OptiScaler's list couldn't be updated; the model choice is saved". - The launcher window's Apply builds its request in GuiApplyRequest (core); `set ... --gui-apply` runs that same request in test builds. Tests: running K, the launcher records M, the player selects the shown M: 1 and M runs; no state folder: wronggpu.ini's item on the hooked route and the custom slot, never the entry, and a selection is not saved; the launcher's Apply of an unchanged model wins over a newer choice made in OptiScaler's list; OptiScaler.ini missing; the upgrade migration (the record tool in its own process) against the REAL launcher apply holding the lock (test hook). The earlier tests that relied on an entry choosing the model now expect the model choice route's model. Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/fsr/src/dllmain.cpp | 30 +++-- clean/fsr/src/frontend.cpp | 111 ++++++++++--------- clean/fsr/src/frontend.h | 15 ++- clean/fsr/tests/test_frontend.cpp | 86 ++++++++------ clean/fsr/tests/test_model_choice_record.cpp | 13 +++ clean/installer/src/app/cli.cpp | 6 + clean/installer/src/app/launcher_ui.cpp | 3 +- clean/installer/src/wg_core/launcher.cpp | 70 ++++++++---- clean/installer/src/wg_core/launcher.h | 4 + clean/installer/tests/run_model_l_tests.py | 56 +++++++++- 10 files changed, 256 insertions(+), 138 deletions(-) diff --git a/clean/fsr/src/dllmain.cpp b/clean/fsr/src/dllmain.cpp index 8425b131..491f4f82 100644 --- a/clean/fsr/src/dllmain.cpp +++ b/clean/fsr/src/dllmain.cpp @@ -241,28 +241,24 @@ FrontEnd& Get() { p.asiPlugin = [](char* model) { return QueryAsiPlugin(model); }; p.asiShowModel = [](char model) { ShowAsiModel(model); }; } - // The game's model choice record (model_choice_record.h, in the game's WrongGPU state folder next to wronggpu.ini) - // decides the WrongGPU model on every route; the plugin writes its menu's model clicks there too. Without the - // state folder (no launcher install): no record, as before. + // The game's model choice record (model_choice_record.h, in the game's WrongGPU state folder wronggpu-setup next to + // wronggpu.ini) decides the WrongGPU model on every route; the plugin writes its menu's model clicks there too. + // Always set: without the state folder the front end runs the session's last choice, wronggpu.ini's model item or + // Model M, never the host's stored index (FrontEnd::ChooseModel). { const std::wstring ini = Place().ini; const size_t slash = ini.find_last_of(L"\\/"); const std::filesystem::path record = wgchoice::RecordPathIn(slash == std::wstring::npos ? std::wstring(L".") : ini.substr(0, slash)); - std::error_code ec; - if (std::filesystem::is_directory(record.parent_path(), ec)) { // a launcher install: its state folder - p.choiceRecord = record; - p.readWronggpuIni = [ini] { // the upgrade migration reads wronggpu.ini's model item under the state lock - std::string text; - wgstate::ReadBytes(ini, &text); - return text; - }; - if (g_hosted) { - SetAsiChoiceRecord(record.wstring()); - SetHostIniPollModels(false); // the host's stored index is no model choice (the record decides) - } - } else { - L().Write("model choice: no launcher state folder next to wronggpu.ini: no model choice record (the model item decides)"); + p.choiceRecord = record; + p.readWronggpuIni = [ini] { // the upgrade migration reads wronggpu.ini's model item under the state lock + std::string text; + wgstate::ReadBytes(ini, &text); + return text; + }; + if (g_hosted) { + SetAsiChoiceRecord(record.wstring()); + SetHostIniPollModels(false); // the host's stored index is no model choice (the record decides) } } p.menu = Menu(); diff --git a/clean/fsr/src/frontend.cpp b/clean/fsr/src/frontend.cpp index bbc4ef2f..cd159cdd 100644 --- a/clean/fsr/src/frontend.cpp +++ b/clean/fsr/src/frontend.cpp @@ -579,7 +579,7 @@ ffxReturnCode_t FrontEnd::CreateUpscale(ffxContext* context, ffxCreateContextDes bool forceAmd = false; if (asiHooked) { std::string why; - char model = asiModel != 0 ? ChooseModel(asiModel, 0, tag, &why) : 0; + char model = asiModel != 0 ? ChooseModel(tag, &why) : 0; if (asiModel != 0) { const int32_t m = ModelOfName(std::string(1, model)); const WgEntryDef* sr = m >= 0 ? SrEntryOfModel(m) : nullptr; @@ -645,6 +645,7 @@ ffxReturnCode_t FrontEnd::CreateUpscale(ffxContext* context, ffxCreateContextDes const std::string name = "amd:upscale#" + std::to_string(nextId_++); std::lock_guard lock(mutex_); forwarded_[*context] = Forwarded{name, 0, api, status, true}; + runningModel_.store(0); // AMD's upscaler runs } Log(tag + " -> " + RcName(rc) + " (the host chose AMD's upscaler version " + Hex(chosen) + "; forwarded) context=" + Name(context)); @@ -655,12 +656,13 @@ ffxReturnCode_t FrontEnd::CreateUpscale(ffxContext* context, ffxCreateContextDes } u->hasOverride = false; // WrongGPU's own id means nothing to AMD's DLL (fallback, comparison) } - // No entry chose the model (direct route, no override, an id WrongGPU did not list): with a model choice record (a - // launcher install) the record's model (ChooseModel); else sr_model when it is set in the shared block, the - // environment or wronggpu.ini; otherwise runtime_options / the runtime's default as before. - if (!forceAmd && !u->selectedModel && !u->modelOption && !platform_.choiceRecord.empty()) { + // No entry named a model (no override, an id WrongGPU did not list, or the direct route): hosted, or with a model choice + // record path (the DLL always sets one), the model choice route (ChooseModel); else (tests of the direct route) sr_model + // when it is set in the shared block, the environment or wronggpu.ini; otherwise runtime_options / the runtime's + // default as before. + if (!forceAmd && !u->selectedModel && !u->modelOption && (config_.hosted || !platform_.choiceRecord.empty())) { std::string why; - const int32_t model = ModelOfName(std::string(1, ChooseModel(0, 0, tag, &why))); + const int32_t model = ModelOfName(std::string(1, ChooseModel(tag, &why))); if (const WgEntryDef* sr = model >= 0 ? SrEntryOfModel(model) : nullptr) { u->selectedModel = kWgModelRows[model].name[0]; u->modelOption = kWgModelRows[model].runtime_option; @@ -889,6 +891,8 @@ ffxReturnCode_t FrontEnd::CreateUpscale(ffxContext* context, ffxCreateContextDes std::lock_guard lock(mutex_); own_[u] = true; } + // the model the active context runs (HostSelected compares a selection with it): none while it runs AMD's upscaler + runningModel_.store(u->mode == UpscaleContext::Mode::Amd && !u->pending ? char(0) : u->selectedModel); *context = u; Log(tag + " -> OK context=" + Name(context) + (u->mode == UpscaleContext::Mode::Amd ? " amd=" + Pointer(u->amd) : "")); return FFX_API_RETURN_OK; @@ -1424,29 +1428,10 @@ char FrontEnd::WronggpuIniModel() const { return wgchoice::IsModel(m) ? m : 0; } -char FrontEnd::ChooseModel(char plugin, char entry, const std::string& tag, std::string* why) { - const std::filesystem::path& path = platform_.choiceRecord; - if (path.empty()) { - // no launcher state folder (a hand install): as before 0.6.5 - const char launcher = LauncherModel(); - if (wgchoice::IsModel(entry)) { - *why = "no model choice record; the host's entry"; - return entry; - } - if (launcher == 'K' || launcher == 'L') { - *why = std::string("no model choice record; the launcher's model item, wronggpu.ini model=") + launcher; - return launcher; - } - if (wgchoice::IsModel(plugin)) { - *why = "no model choice record; the plugin's saved entry"; - return plugin; - } - *why = launcher ? std::string("no model choice record; wronggpu.ini model=") + launcher : std::string("no model choice record; the default"); - return 'M'; - } +char FrontEnd::ChooseModel(const std::string& tag, std::string* why) { std::lock_guard lock(choiceMutex_); - // the record cannot be used now: the last record this session read or wrote, else wronggpu.ini's model item, else M - // (never the host's stored entry) + // the record cannot be used now (no state folder, unreadable, corrupt, busy): the last record this session read or + // wrote, else wronggpu.ini's model item, else Model M; never the host's stored entry auto fallback = [&](const std::string& reason) { if (wgchoice::IsModel(lastChoice_)) { *why = reason + "; the last model choice read this session"; @@ -1456,6 +1441,15 @@ char FrontEnd::ChooseModel(char plugin, char entry, const std::string& tag, std: *why = ini ? reason + "; wronggpu.ini model=" + ini : reason + "; the default"; return ini ? ini : 'M'; }; + const std::filesystem::path& path = platform_.choiceRecord; + DWORD dirErr = 0; + const wgstate::PathState dir = path.empty() ? wgstate::PathState::Missing : wgstate::DirectoryState(path.parent_path().wstring(), &dirErr); + if (dir != wgstate::PathState::Present) { + LogOnce(tag, dir == wgstate::PathState::Missing + ? std::string("model choice: no WrongGPU state folder (wronggpu-setup) for this game: no model choice record") + : "model choice: the WrongGPU state folder (wronggpu-setup) cannot be checked (error " + std::to_string(dirErr) + ")"); + return fallback(dir == wgstate::PathState::Missing ? "no WrongGPU state folder" : "the WrongGPU state folder cannot be checked"); + } wgchoice::Record rec; bool migrated = false; std::string err; @@ -1499,22 +1493,29 @@ int32_t FrontEnd::HostSelected(uint64_t versionId) { return WG_HOST_SELECTED_NOTHING_CHANGED; } const char model = kWgModelRows[e->value].name[0]; - if (platform_.choiceRecord.empty()) { - // no launcher state folder: no record to write; the host's entry decides at the next create (as before 0.6.5) - Log(tag + " the player selected Model " + model + " in OptiScaler's upscaler list; no model choice record (no launcher " - "state folder): the host's entry decides"); - return WG_HOST_SELECTED_NOTHING_CHANGED; + const char running = runningModel_.load(); + const std::filesystem::path& path = platform_.choiceRecord; + DWORD dirErr = 0; + if (path.empty() || wgstate::DirectoryState(path.parent_path().wstring(), &dirErr) != wgstate::PathState::Present) { + // no record to write: not saved, nothing changes (the host's index is never a choice) + Log(tag + " ERROR: the player selected Model " + model + " in OptiScaler's upscaler list, but it was not saved: no WrongGPU " + "state folder (wronggpu-setup) for this game" + (dirErr ? " (error " + std::to_string(dirErr) + ")" : std::string()) + + ". Nothing changes; apply the model in the WrongGPU launcher."); + return WG_HOST_SELECTED_NOT_SAVED; } std::lock_guard lock(choiceMutex_); - wgchoice::Record after, before; + wgchoice::Record after; std::string err; - const wgchoice::Outcome o = wgchoice::RecordChoice(platform_.choiceRecord, model, wgchoice::Source::Ffx, &after, &err, &before); + const wgchoice::Outcome o = wgchoice::RecordChoice(path, model, wgchoice::Source::Ffx, &after, &err); if (o == wgchoice::Outcome::Written) { - const char was = wgchoice::IsModel(before.model) ? before.model : lastChoice_; lastChoice_ = model; + // 1 when the selected model is not what the active context runs (also when the record changed underneath, a + // launcher Apply while the game is open): the host recreates the upscaler, which then runs the record's model Log(tag + " the player selected Model " + model + " in OptiScaler's upscaler list: recorded (seq " + std::to_string(after.seq) + - ", source=ffx)" + (err.empty() ? "" : "; " + err)); - return was == model ? WG_HOST_SELECTED_NOTHING_CHANGED : WG_HOST_SELECTED_RECORDED; + ", source=ffx)" + (err.empty() ? "" : "; " + err) + + (running == model ? "; it already runs" : std::string("; it runs after the upscaler is recreated (now running: ") + + (wgchoice::IsModel(running) ? std::string("Model ") + running : std::string("no WrongGPU model")) + ")")); + return running == model ? WG_HOST_SELECTED_NOTHING_CHANGED : WG_HOST_SELECTED_RECORDED; } if (o == wgchoice::Outcome::SeqExhausted) { Log(tag + " ERROR: the player selected Model " + model + " in OptiScaler's upscaler list: " + wgchoice::OutcomeWords(o) + @@ -1531,26 +1532,28 @@ void FrontEnd::ApplyEntry(const WgEntryDef& e, UpscaleContext& u, const std::str std::string described; if (model < 0 && ConfiguredModel(&model, &described)) Log(tag + " settings: " + described + " (the SR context's model)"); - // With a model choice record (a launcher install), the entry the host passes at a create is the index its ini stores, - // not a choice: the record decides the SR context's model (ChooseModel; a player's selection in the host's list - // reaches the record as an event, HostSelected). One folder per choice keeps its folder's model. + // The entry the host passes at a create is the index its ini stores, never a choice: the model choice record decides + // the SR context's model (ChooseModel: the record, or when it cannot be used the session's last choice, wronggpu.ini's + // model item, Model M; a player's selection in the host's list reaches the record as an event, HostSelected). One + // folder per choice keeps its folder's model. const WgEntryDef* shown = &e; // the entry written to the shared settings and logged - if (config_.hosted && !platform_.choiceRecord.empty() && std::strcmp(source, "folder") != 0) { + if (config_.hosted && std::strcmp(source, "folder") != 0) { std::string why; const char entry = model >= 0 && model < WG_SR_MODEL_COUNT ? kWgModelRows[model].name[0] : 0; - const char chosen = ChooseModel(0, entry, tag, &why); - const int32_t m = ModelOfName(std::string(1, chosen)); - if (m >= 0 && SrEntryOfModel(m)) { - if (m != model) - Log(tag + " model choice: the host's entry names " + (entry ? std::string("Model ") + entry : std::string("no model")) + - "; Model " + chosen + " runs (" + why + "; an entry the host stores is not a choice)"); - else - Log(tag + " model choice: Model " + chosen + " (" + why + ")"); - model = m; - if (e.slot == WG_OPT_SR_MODEL) shown = SrEntryOfModel(m); - } else { - LogOnce(tag, std::string("note: model choice: Model ") + chosen + " is not part of this build of the front end; the host's entry is used"); + char chosen = ChooseModel(tag, &why); + int32_t m = ModelOfName(std::string(1, chosen)); + if (m < 0 || !SrEntryOfModel(m)) { + LogOnce(tag, std::string("note: model choice: Model ") + chosen + " is not part of this build of the front end; Model M is used"); + chosen = 'M'; + m = ModelOfName("M"); } + if (m != model) + Log(tag + " model choice: the host's entry names " + (entry ? std::string("Model ") + entry : std::string("no model")) + + "; Model " + chosen + " runs (" + why + "; an entry the host stores is not a choice)"); + else + Log(tag + " model choice: Model " + chosen + " (" + why + ")"); + model = m; + if (e.slot == WG_OPT_SR_MODEL) shown = SrEntryOfModel(m); } if (const WgEntryDef* sr = model >= 0 ? SrEntryOfModel(model) : nullptr) { u.selectedModel = kWgModelRows[model].name[0]; diff --git a/clean/fsr/src/frontend.h b/clean/fsr/src/frontend.h index f7f6ac1c..1ca81fec 100644 --- a/clean/fsr/src/frontend.h +++ b/clean/fsr/src/frontend.h @@ -221,14 +221,12 @@ class FrontEnd { bool ConfiguredModel(int32_t* model, std::string* described); // The model the launcher's wronggpu.ini names (the last model item of runtime_options: 'M', 'K', 'L'), else 0. char LauncherModel() const; - // The WrongGPU model a create runs. With a record path (a launcher install, model_choice_record.h): the record's - // model (a game without one gets one from wronggpu.ini's model item, read under the game's state lock, else Model - // M: LoadOrMigrateRecord); when the record cannot be read, is corrupt or its lock is not taken in time: the last - // record this session read or wrote (lastChoice_), else wronggpu.ini's model item, else Model M; NEVER the host's - // stored entry. Without a record path (no launcher state folder: a hand install, as before 0.6.5): the host's entry - // (`entry`, 0 for none), else the launcher's model item when it names Model K or L, else the plugin's saved WrongGPU - // entry (`plugin`), else Model M. *why: which choice decided, for the log. - char ChooseModel(char plugin, char entry, const std::string& tag, std::string* why); + // The WrongGPU model a create runs: the model choice record's (model_choice_record.h; a game without one gets one from + // wronggpu.ini's model item, read under the game's state lock, else Model M: LoadOrMigrateRecord). When the record + // cannot be used (no state folder or one that cannot be checked, unreadable, corrupt, its lock not taken in time): the + // last record this session read or wrote (lastChoice_), else wronggpu.ini's model item, else Model M. NEVER the host's + // stored entry, NEVER the plugin's saved entry. *why: which choice decided, for the log. + char ChooseModel(const std::string& tag, std::string* why); // wronggpu.ini's model item as it is on disk now (readWronggpuIni), else as read at start ('M', 'K', 'L' or 0). char WronggpuIniModel() const; // `line` logged once per session (after `tag`). @@ -295,6 +293,7 @@ class FrontEnd { std::map modelLogged_; // ApplyModelDir: each distinct choice logged once (mutex_) std::mutex choiceMutex_; // ChooseModel / HostSelected: lastChoice_ char lastChoice_ = 0; // the model of the last record read or written this session + std::atomic runningModel_{0}; // the model the last created context runs (0: none / AMD's upscaler) std::atomic reentered_{0}; // calls refused because they re-entered this front end on one thread std::mutex parkMutex_; // guards the three below; held while a parked context is destroyed UpscaleContext* parked_ = nullptr; diff --git a/clean/fsr/tests/test_frontend.cpp b/clean/fsr/tests/test_frontend.cpp index 3dc9a98c..fe16ffe6 100644 --- a/clean/fsr/tests/test_frontend.cpp +++ b/clean/fsr/tests/test_frontend.cpp @@ -1966,12 +1966,15 @@ static void TestRuntimeProviderName() { g_resources[kOutput] = {dxgi::R16G16B16A16_FLOAT, 2560, 1440}; Config c; c.hosted = true; - // Deliberately configure the opposite default: the in-game choice must win. - c.runtimeOptions = std::string("model=") + (model[0] == 'M' ? "K" : "M"); + // The host's stored entry deliberately names ANOTHER model: it is no choice (0.6.5 #213); the model choice route + // decides (no state folder here: wronggpu.ini's model item). + c.runtimeOptions = std::string("model=") + model; auto f = MakeFrontEnd(c); UpscaleCreate create(FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE, true); - create.version.versionId = model[0] == 'K' ? kWrongGpuKProviderVersionId - : model[0] == 'L' ? kWrongGpuLProviderVersionId : kWrongGpuProviderVersionId; + create.version.versionId = model[0] == 'M' ? (WRONGGPU_MODEL_L ? kWrongGpuLProviderVersionId : WRONGGPU_MODEL_K ? kWrongGpuKProviderVersionId + : kWrongGpuProviderVersionId) + : kWrongGpuProviderVersionId; + const uint64_t modelId = model[0] == 'K' ? kWrongGpuKProviderVersionId : model[0] == 'L' ? kWrongGpuLProviderVersionId : kWrongGpuProviderVersionId; ffxContext ctx = nullptr; CHECK(f->CreateContext(&ctx, &create.upscale.header, kMemCb) == FFX_API_RETURN_OK); auto frame = MakeDispatch(); @@ -1981,7 +1984,7 @@ static void TestRuntimeProviderName() { CHECK(f->Query(&ctx, &q.header) == FFX_API_RETURN_OK); const std::string expected = std::string("WrongGPU Model ") + model; CHECK(q.versionName && expected == q.versionName); - CHECK(q.versionId == create.version.versionId); + CHECK(q.versionId == modelId); CHECK(std::string(g_createInfo.options).rfind(std::string("model=") + model) == std::string(g_createInfo.options).size() - 7); CHECK(!g_statuses.empty() && g_statuses.back().upscaler.find(expected) != std::string::npos); // After a frame failure, version queries must report the actual AMD fallback. @@ -2338,17 +2341,18 @@ static void TestHostVersionHandling() { CHECK(std::strcmp(names[0], "WrongGPU Model M##3.1.0") == 0); CHECK(WRONGGPU_MODEL_K == 0 || std::strcmp(names[1], "WrongGPU Model K##3.1.0") == 0); CHECK(WRONGGPU_MODEL_L == 0 || std::strcmp(names[kOwn - 1], "WrongGPU Model L##3.1.0") == 0); - // The selection still works by id, and a context's own provider name stays the label alone (the last SR model). + // A context's own provider name stays the label alone. The host's stored entry (the last SR model) is no choice: with no + // record and no model item, Model M runs. const uint64_t lastModel = WRONGGPU_MODEL_L ? kWrongGpuLProviderVersionId : WRONGGPU_MODEL_K ? kWrongGpuKProviderVersionId : kWrongGpuProviderVersionId; - const char* const lastName = WRONGGPU_MODEL_L ? "WrongGPU Model L" : WRONGGPU_MODEL_K ? "WrongGPU Model K" : "WrongGPU Model M"; + const char* const lastName = "WrongGPU Model M"; UpscaleCreate own(FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE, /*withOverride=*/true); own.version.versionId = lastModel; ffxContext ctx = nullptr; CHECK(fe->CreateContext(&ctx, &own.upscale.header, kMemCb) == FFX_API_RETURN_OK && fe->OwnContextCount() == 1); ffxQueryGetProviderVersion provider{}; provider.header.type = FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION; - CHECK(fe->Query(&ctx, &provider.header) == FFX_API_RETURN_OK && provider.versionId == lastModel && provider.versionName && + CHECK(fe->Query(&ctx, &provider.header) == FFX_API_RETURN_OK && provider.versionId == kWrongGpuProviderVersionId && provider.versionName && std::strcmp(provider.versionName, lastName) == 0); CHECK(fe->DestroyContext(&ctx, kMemCb) == FFX_API_RETURN_OK); @@ -2561,12 +2565,10 @@ static void TestAsiPluginHooked() { ownRun(kWrongGpuProviderVersionId, "WrongGPU Model M", kWrongGpuProviderVersionId); ownRun(g_versionIds[0], "WrongGPU Model M", kWrongGpuProviderVersionId); ownRun(0, "WrongGPU Model M", kWrongGpuProviderVersionId); + // The plugin's saved WrongGPU model is no model choice (0.6.5 #213: the model choice record decides; none here, no model + // item: Model M). g_asiModel = 'K'; -#if WRONGGPU_MODEL_K - ownRun(kWrongGpuProviderVersionId, "WrongGPU Model K", kWrongGpuKProviderVersionId); -#else - ownRun(kWrongGpuProviderVersionId, "WrongGPU Model M", kWrongGpuProviderVersionId); // no Model K in this build -#endif + ownRun(kWrongGpuProviderVersionId, "WrongGPU Model M", kWrongGpuProviderVersionId); // The host's FSR 3.X(/4) entry: AMD upscales. g_asiModel = 0; @@ -2761,15 +2763,21 @@ static void TestAsiChoiceRecord() { RecordFolder f; const std::filesystem::path& rec = f.record(); std::string why; - // The audit's case without a record (a front end without the state folder): the launcher's K / L item decides over the - // plugin's saved default entry (Model M); a host event there changes nothing (0: the host's entry decides) + // No state folder (a hand install, or one that cannot be found): the record route all the same: the session's last + // choice, else wronggpu.ini's model item (the audit's case: L / K over the plugin's saved default entry, Model M), else + // Model M; NEVER the host's entry (the box names M, on the hooked route and on the custom slot). A selection there is + // not saved (-1) and changes nothing. if (b) { const std::string ini = std::string("runtime_options = model=") + b + "\n"; CHECK(HostedCreate(ini.c_str(), 'M', kWrongGpuProviderVersionId) == name(b)); - CHECK(CountLog("no model choice record; the launcher's model item") == 1); + CHECK(CountLog("model choice: no WrongGPU state folder (wronggpu-setup) for this game") == 1); + CHECK(CountLog((std::string("(no WrongGPU state folder; wronggpu.ini model=") + b + ")").c_str()) == 1); + CHECK(HostedCreate(ini.c_str(), 0, idOf('M'), false) == name(b)); // the custom slot: the stored M is no choice int32_t rc = 9; CHECK(HostedCreate(ini.c_str(), 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name(b)); - CHECK(rc == WG_HOST_SELECTED_NOTHING_CHANGED); + CHECK(rc == WG_HOST_SELECTED_NOT_SAVED); + CHECK(CountLog("but it was not saved: no WrongGPU state folder (wronggpu-setup) for this game") == 1); + CHECK(HostedCreate("runtime_options = timing_log=1\n", 'M', idOf(b), false) == name('M')); // no model item: Model M } g_choiceRecord = rec; if (b) { @@ -2811,7 +2819,20 @@ static void TestAsiChoiceRecord() { r = ReadRec(rec); CHECK(r.model == 'M' && r.seq == 5 && r.source == wgchoice::Source::Ffx); } - // (6) the launcher applies b (seq 6): b runs + // (5b) the record changed underneath (a launcher Apply while the game is open): the session runs b, the launcher + // records M, the player selects M (the box already shows it): 1, so the host recreates, and M runs + { + wgchoice::Record after0; + CHECK(wgchoice::RecordChoice(rec, b, wgchoice::Source::Launcher, &after0, &why) == wgchoice::Outcome::Written); + auto fe = ChoiceFrontEnd(iniB.c_str(), 0, false); + CHECK(ChoiceCreate(*fe, idOf('M')) == name(b)); // runs b (the box names M) + CHECK(wgchoice::RecordChoice(rec, 'M', wgchoice::Source::Launcher, &after0, &why) == wgchoice::Outcome::Written); + CHECK(fe->HostSelected(idOf('M')) == WG_HOST_SELECTED_RECORDED); + CHECK(CountLog((std::string("it runs after the upscaler is recreated (now running: Model ") + b + ")").c_str()) == 1); + CHECK(ChoiceCreate(*fe, idOf('M')) == name('M')); + CHECK(fe->HostSelected(idOf('M')) == WG_HOST_SELECTED_NOTHING_CHANGED); // M runs now: nothing to recreate + } + // (6) the launcher applies b: b runs CHECK(wgchoice::RecordChoice(rec, b, wgchoice::Source::Launcher, &after, &why) == wgchoice::Outcome::Written); CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M')) == name(b)); // (7) a third model selected in the list (a build with K and L) @@ -3007,20 +3028,21 @@ static void TestRegistryEntries() { std::get<1>(g_menuWrites[0]) == WG_SR_MODEL_M && std::get<2>(g_menuWrites[0]) == "menu"); CHECK(CountLog("the host chose WrongGPU Model M (0x5747000000000001): settings: sr_model=M (menu)") == 1); #if WRONGGPU_MODEL_K - // Model K chosen: sr_model=K written, the context runs Model K. - CHECK(run(kWrongGpuKProviderVersionId, true) == "WrongGPU Model K"); - CHECK(g_menuWrites.size() == 2 && std::get<0>(g_menuWrites[1]) == WG_OPT_SR_MODEL && std::get<1>(g_menuWrites[1]) == WG_SR_MODEL_K); - CHECK(g_createOptions.size() >= 8 && g_createOptions.compare(g_createOptions.size() - 8, 8, ";model=K") == 0); - CHECK(g_menuValues[WG_OPT_SR_MODEL] == WG_SR_MODEL_K); - // No override at all (the host passes none): sr_model as configured (K), nothing written. - CHECK(run(0, false) == "WrongGPU Model K" && g_menuWrites.size() == 2); - CHECK(CountLog("settings: sr_model=K (ini)") >= 1); + // Model K's entry: the host's stored entry is no choice (0.6.5 #213): the model choice route decides (no state folder + // and no model item here: Model M); sr_model=M written, the context runs Model M, the log names both. + CHECK(run(kWrongGpuKProviderVersionId, true) == "WrongGPU Model M"); + CHECK(g_menuWrites.size() == 2 && std::get<0>(g_menuWrites[1]) == WG_OPT_SR_MODEL && std::get<1>(g_menuWrites[1]) == WG_SR_MODEL_M); + CHECK(g_createOptions.size() >= 8 && g_createOptions.compare(g_createOptions.size() - 8, 8, ";model=M") == 0); + CHECK(CountLog("model choice: the host's entry names Model K; Model M runs") == 1); + // No override at all (the host passes none): the same route, nothing written. + CHECK(run(0, false) == "WrongGPU Model M" && g_menuWrites.size() == 2); #endif - // Every entry the registry has: its option = its value, and nothing writes rr_mode (the RR plugin's box owns it). + // Every entry the registry has: the model choice route's model (here Model M) is written, whatever the entry names, + // and nothing writes rr_mode (the RR plugin's box owns it). for (int i = 0; i < kOwn; ++i) { const WgEntryDef* e = OwnEntry(i); - CHECK(!run(e->id, true).empty()); - CHECK(!g_menuWrites.empty() && std::get<0>(g_menuWrites.back()) == e->slot && std::get<1>(g_menuWrites.back()) == e->value); + CHECK(run(e->id, true) == "WrongGPU Model M"); + CHECK(!g_menuWrites.empty() && std::get<0>(g_menuWrites.back()) == WG_OPT_SR_MODEL && std::get<1>(g_menuWrites.back()) == WG_SR_MODEL_M); CHECK(CountLog((std::string("the host chose ") + EntryProviderName(*e) + " (").c_str()) >= 1); } for (const auto& w : g_menuWrites) CHECK(std::get<0>(w) != WG_OPT_RR_MODE); @@ -3223,15 +3245,15 @@ static void TestCustomSlotFailedCreate() { CHECK(CountLog("this failure is remembered for the session") == 1); CHECK(CountLog("no context, the host's own upscaler takes over") == 1); CHECK(CountLog("custom slot: create ") == 4 && CountLog("custom slot: create 10 since the failure") == 1); - // Another model is something new: one attempt of its own. + // Another entry (Model K's) is no other model (0.6.5 #213: the stored entry is no choice): the same upscaler with the + // same options, so the remembered failure stands and nothing is tried again. #if WRONGGPU_MODEL_K { UpscaleCreate k(FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE, true); k.version.versionId = kWrongGpuKProviderVersionId; ffxContext ctx = nullptr; CHECK(fe->CreateContext(&ctx, &k.upscale.header, nullptr) == FFX_API_RETURN_ERROR_RUNTIME_ERROR && !ctx); - CHECK(g_createCalls == 2 && CountLog("this failure is remembered for the session") == 2); - CHECK(fe->CreateContext(&ctx, &k.upscale.header, nullptr) == FFX_API_RETURN_ERROR_RUNTIME_ERROR && g_createCalls == 2); + CHECK(g_createCalls == 1); } #endif // A working upscaler (the model was there) in a fresh session: created, hooks after the create. diff --git a/clean/fsr/tests/test_model_choice_record.cpp b/clean/fsr/tests/test_model_choice_record.cpp index dcf92896..ee53cec3 100644 --- a/clean/fsr/tests/test_model_choice_record.cpp +++ b/clean/fsr/tests/test_model_choice_record.cpp @@ -396,6 +396,18 @@ int ChildApply(const fs::path& gameDir, bool crash) { return RecordChoiceUnlocked(record, 'L', Source::Launcher, &after, &why) == Outcome::Written ? 0 : 2; } +// The front end's upgrade migration for the game in gameDir, run by the launcher's end-to-end test against a REAL launcher +// apply in another process (run_model_l_tests.py): reads wronggpu.ini's model item under the state lock; prints the result. +int ChildMigrate(const fs::path& gameDir) { + Record r; + bool migrated = false; + std::string why; + const LoadResult lr = LoadOrMigrateRecord(RecordPathIn(gameDir), [&] { return IniModel(gameDir / "wronggpu.ini"); }, &r, &migrated, &why, 20000); + std::printf("migrate: %s model=%c seq=%llu migrated=%d\n", lr == LoadResult::Ok ? "ok" : "failed", lr == LoadResult::Ok ? r.model : '-', + static_cast(r.seq), migrated ? 1 : 0); + return lr == LoadResult::Ok ? 0 : 1; +} + int ChildHold(const std::wstring& gameDir, int ms) { wgstate::StateLock lock(gameDir); if (!lock.held()) return 1; @@ -459,6 +471,7 @@ int main(int argc, char** argv) { #ifdef _WIN32 if (argc >= 6 && std::string(argv[1]) == "writer") return ChildWriter(argv[2], argv[3][0], argv[4], std::atoi(argv[5])); if (argc >= 4 && std::string(argv[1]) == "reader") return ChildReader(argv[2], std::strtoull(argv[3], nullptr, 10)); + if (argc >= 3 && std::string(argv[1]) == "migrate") return ChildMigrate(argv[2]); if (argc >= 3 && std::string(argv[1]) == "apply") return ChildApply(argv[2], false); if (argc >= 3 && std::string(argv[1]) == "apply-and-die") return ChildApply(argv[2], true); if (argc >= 4 && std::string(argv[1]) == "hold") return ChildHold(fs::path(argv[2]).wstring(), std::atoi(argv[3])); diff --git a/clean/installer/src/app/cli.cpp b/clean/installer/src/app/cli.cpp index 72d81bd6..a5ac7068 100644 --- a/clean/installer/src/app/cli.cpp +++ b/clean/installer/src/app/cli.cpp @@ -841,6 +841,12 @@ int Verb(const wstring& verb, const Args& a, Output& o) { OpLogBegin(); OpRequest r; r.op = Op::Apply; r.dir = dir; r.hasProfile = true; r.profile = p; r.optiEdits = optiEdits; r.modelChosen = modelGiven; // set model=: the player's explicit model choice, stamped (also the same model) +#ifdef WRONGGPU_TESTING + if (a.has(L"gui-apply")) { // tests: the request the launcher window's Apply makes (GuiApplyRequest), the same code + r = GuiApplyRequest(dir, p); + r.optiEdits = optiEdits; + } +#endif Ui ui; ui.step = [](int, int, const wstring&) {}; ui.log = [](const wstring& s) { LogLine(g.ctx, s); }; const OpResult res = RunOp(g.ctx, r, ui); OpLogEnd(); diff --git a/clean/installer/src/app/launcher_ui.cpp b/clean/installer/src/app/launcher_ui.cpp index 7c2e1355..de1db130 100644 --- a/clean/installer/src/app/launcher_ui.cpp +++ b/clean/installer/src/app/launcher_ui.cpp @@ -1003,8 +1003,7 @@ void StartNextQueued() { // (WM_APP_OPDONE), never lost. void OnApply() { if (PageWritesWait()) return; // one rule for every write of the page (its Apply says why) - OpRequest r; r.op = Op::Apply; r.dir = v.cur.dir; r.hasProfile = true; r.profile = v.edit; - r.modelChosen = FindSetting("model") != nullptr; // Apply with a model shown is the player's model choice, even unchanged + OpRequest r = GuiApplyRequest(v.cur.dir, v.edit); // the model shown is the player's model choice, even unchanged for (size_t i = 0; i < v.opti.editable.size() && i < v.optiValues.size(); ++i) if (v.optiValues[i] != v.opti.editable[i].value) r.optiEdits.push_back({v.opti.editable[i].section + "." + v.opti.editable[i].key, v.optiValues[i]}); for (auto& e : r.optiEdits) { // the values typed are checked before anything is written diff --git a/clean/installer/src/wg_core/launcher.cpp b/clean/installer/src/wg_core/launcher.cpp index 4e70c637..71273a76 100644 --- a/clean/installer/src/wg_core/launcher.cpp +++ b/clean/installer/src/wg_core/launcher.cpp @@ -1011,6 +1011,16 @@ bool WriteLauncherModelChoice(Context& ctx, const wstring& dir, char model, std: return true; } +OpRequest GuiApplyRequest(const wstring& dir, const Profile& edit) { + OpRequest r; + r.op = Op::Apply; + r.dir = dir; + r.hasProfile = true; + r.profile = edit; + r.modelChosen = FindSetting("model") != nullptr; // Apply with a model shown is the player's model choice, even unchanged + return r; +} + Profile GameProfile(const wstring& dir) { Profile p; if (!LoadProfile(ProfilePath(dir), p)) { @@ -1043,8 +1053,9 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto } } // The game's state lock (wg_state.h, held by the launcher, the front end and the plugins for every read-modify-write - // of the game's state) is held across wronggpu.ini, the model choice record and OptiScaler.ini's entry: the front end's - // upgrade migration, which reads wronggpu.ini's model item under the same lock, comes wholly before or after this. + // of the game's state) is held across the model choice record and OptiScaler.ini's entry (and the state folder's other + // settings): the front end's upgrade migration, which reads wronggpu.ini's model item under the same lock, comes wholly + // before or after this. // Not taken in time (the game is writing its state): nothing is applied. const std::filesystem::path recordPath = Join(StateDir(dir), wgchoice::kRecordFile); wgchoice::Lock lock(recordPath); @@ -1053,35 +1064,37 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto L"). Try again.", EXIT_REFUSED); char forcedEntry = 0; // the model whose entry OptiScaler.ini's UpscalerIndex is set to (after the record) - auto renderFile = [&](const wchar_t* name, bool opti) { + // wronggpu.ini is never rewritten here: it is the install's defaults and the player's file (the settings the launcher + // changes go to the game's WrongGPU state folder, wronggpu-setup: the model choice record below, settings.ini) + auto renderOpti = [&]() { + const wchar_t* name = L"OptiScaler.ini"; const wstring path = Join(dir, name); string in; - const bool had = ReadAll(path, in); - if (opti && !had) return; // OptiScaler.ini: only an existing file (ours) is changed - string out; wstring why; - if (opti) { - RenderOptiIni(q, in, out, ¬es); - if (forcedEntry) out = SetOptiModelEntry(out, forcedEntry); - bool wrote = false; - out = RenderGameOptiKeys(p, m.exe, out, m.inikeys, notes, &wrote); - if (wrote) - for (auto& n : kGameNotices) if (IEq(BaseName(m.exe), n.exe)) notes.push_back(n.notice); - JournalChanges(m.inikeys, name, in, out); - recordChanged = recordChanged || out != in; - } else { - // the model is never written into wronggpu.ini (it is the model choice record's): its model item stays as the - // install wrote it, the install's default - Profile qw = q; - if (FindSetting("model")) qw.v["model"] = EffectiveSettings(in, "")["model"]; - if (!RenderWronggpuIni(qw, in, out, &why)) Fail(L"Settings not applied: " + why, EXIT_USAGE); + if (!ReadAll(path, in)) { // missing or unreadable: never created here; a model choice saved without it is said + if (forcedEntry) { + const wstring w = L"OptiScaler's list couldn't be updated; the model choice is saved (" + wstring(name) + + (IsFile(path) ? L" could not be read)." : L" is missing)."); + LogLine(ctx, w); + notes.push_back(w); + if (warnings) warnings->push_back(w); + } + return; } - if (out == in && (had || out.empty())) return; // unchanged, or nothing to write into a missing file + string out; + RenderOptiIni(q, in, out, ¬es); + if (forcedEntry) out = SetOptiModelEntry(out, forcedEntry); + bool wrote = false; + out = RenderGameOptiKeys(p, m.exe, out, m.inikeys, notes, &wrote); + if (wrote) + for (auto& n : kGameNotices) if (IEq(BaseName(m.exe), n.exe)) notes.push_back(n.notice); + JournalChanges(m.inikeys, name, in, out); + recordChanged = recordChanged || out != in; + if (out == in) return; WriteFileAtomic(path, out.data(), out.size()); const wstring h = Sha256Bytes(out.data(), out.size()); for (auto& e : m.e) if (e.action == L"copy" && IEq(e.rel, name) && e.inst != h) { e.inst = h; recordChanged = true; } notes.push_back(wstring(name) + L" written"); }; - renderFile(L"wronggpu.ini", false); // The model choice record (clean/fsr/src/model_choice_record.h): the launcher's model choice, with the next seq, when the // player applied a model (Apply in the launcher, or `set model=`: always, also the same model again, so it // wins over a newer choice made in the game), when the game has no record yet (from the profile), or when the @@ -1094,6 +1107,15 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto wgchoice::Record cur; std::string err; const wgchoice::ReadResult rr = wgchoice::ReadRecordFile(recordPath, &cur, &err); +#ifdef WRONGGPU_TESTING + // tests: "|": the apply says it holds the lock (the record read, nothing written yet) and waits, so a + // test can start the front end's upgrade migration in another process exactly now + if (const wstring pause = EnvVar(L"WRONGGPU_TEST_PAUSE_IN_CHOICE_LOCK"); !pause.empty() && pause.find(L'|') != wstring::npos) { + const wstring sig = pause.substr(0, pause.find(L'|')); + WriteFileAtomic(sig, "1", 1); + Sleep(DWORD(_wtoi(pause.substr(pause.find(L'|') + 1).c_str()))); + } +#endif const bool write = modelChosen || rr == wgchoice::ReadResult::Missing || (rr == wgchoice::ReadResult::Ok && cur.source == wgchoice::Source::Launcher && cur.model != model); if (write && WriteLauncherModelChoice(ctx, dir, model, notes, warnings)) { @@ -1113,7 +1135,7 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto } } } - if (HostedRecord(m)) renderFile(L"OptiScaler.ini", true); + if (HostedRecord(m)) renderOpti(); if (RecordHasRr(m)) { // Ray Reconstruction (rr.h): the RR plugin's settings file (RR stays off while its data is not ready) const wstring path = Join(dir, kRrSettings); string in; diff --git a/clean/installer/src/wg_core/launcher.h b/clean/installer/src/wg_core/launcher.h index 64d0c002..193798f0 100644 --- a/clean/installer/src/wg_core/launcher.h +++ b/clean/installer/src/wg_core/launcher.h @@ -218,6 +218,10 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto // The launcher's model choice into the game's model choice record (wronggpu-setup\model-choice.ini), with the next seq, // source=launcher. Call it holding the record's lock (wgchoice::Lock). false: not written (said in the notes and warnings). bool WriteLauncherModelChoice(Context& ctx, const wstring& dir, char model, std::vector& notes, std::vector* warnings); +// The request of the launcher window's Apply (launcher_ui.cpp OnApply calls it; the OptiScaler tab's edits are added there): +// the profile shown, applied, with the model shown as the player's model choice (modelChosen) whenever the build has the +// model setting, also when it is unchanged. `set ... --gui-apply` (a WRONGGPU_TESTING build) runs it for the tests. +OpRequest GuiApplyRequest(const wstring& dir, const Profile& edit); Profile GameProfile(const wstring& dir); // profile.ini, else the profile its wronggpu.ini implies // The OptiScaler tab: reset / keep / edits of OpRequest written into the installed OptiScaler.ini with the inikey // journal in the record. Nothing to do: no change. diff --git a/clean/installer/tests/run_model_l_tests.py b/clean/installer/tests/run_model_l_tests.py index 0c0f2d4d..59245900 100644 --- a/clean/installer/tests/run_model_l_tests.py +++ b/clean/installer/tests/run_model_l_tests.py @@ -25,6 +25,7 @@ import shutil import subprocess import sys +import time os.environ["WRONGGPU_TESTING"] = "1" HERE = os.path.dirname(os.path.abspath(__file__)) @@ -254,6 +255,9 @@ def choice_record(b): return r +RECORD_TOOL = None # --record-tool + + def test_choice(t): """The launcher's Model L choice (a build with WRONGGPU_MODEL_L on and the test map): set model=L/M on an installed game. L only with Model L's data on this PC; it writes wronggpu.ini's model item and OptiScaler's UpscalerIndex, the @@ -312,7 +316,16 @@ def test_choice(t): r2b = choice_record(b) t.check("set model=L (the profile already says L) after the plugin's newer M: L is recorded with the next seq", rc == 0 and r2b.get("model") == "L" and r2b.get("source") == "launcher" and int(r2b.get("seq", "0")) == newer + 1, r2b) - r2 = r2b + # the launcher window's Apply (the request its button makes, GuiApplyRequest, run by `set ... --gui-apply`): the model + # shown is a choice even unchanged, so it wins over a newer choice made in the game + newer = int(r2b.get("seq", "0")) + 1 + write(rec_path, ("model=M\r\nseq=%d\r\nsource=ffx\r\n" % newer).encode("ascii")) + rc = t.run("set", exe, "fps_overlay=keep", "--gui-apply") + r2c = choice_record(b) + t.check("the launcher's Apply with the unchanged model L after a newer choice in OptiScaler's list (M): L is recorded with the next seq", + rc == 0 and r2c.get("model") == "L" and r2c.get("source") == "launcher" and int(r2c.get("seq", "0")) == newer + 1 and read(wini) == m_w, + (rc, r2c)) + r2 = r2c rc = t.run("set", exe, "model=M") t.check("set model=M: wronggpu.ini and OptiScaler.ini back byte for byte as the install wrote them", rc == 0 and read(wini) == m_w and read(oini) == m_o, (rc, read(wini)[-200:], read(oini)[-200:])) @@ -354,6 +367,43 @@ def test_choice(t): rc == 0 and read(wini) == m_w and upscaler_index(read(oini).decode("utf-8", "replace")) == "0" and sorted(read(oini).split(b"\r\n")) == sorted(m_o.split(b"\r\n")), (rc, read(wini) == m_w, set(read(oini).split(b"\r\n")) ^ set(m_o.split(b"\r\n")), read(wini)[-200:])) + # OptiScaler.ini missing: the model choice is still saved, and the player is told OptiScaler's list could not be updated + os.replace(oini, oini + ".away") + r7 = choice_record(b) + rc = t.run("set", exe, "model=L") + msgs = " ".join(t.j.get("warnings", []) + t.j.get("notes", [])) + t.check("set model=L without OptiScaler.ini: exit 0, the record has L with the next seq, and it says OptiScaler's list couldn't be updated", + rc == 0 and choice_record(b).get("model") == "L" and int(choice_record(b).get("seq", "0")) == int(r7.get("seq", "0")) + 1 and + "OptiScaler's list couldn't be updated; the model choice is saved" in msgs and not os.path.exists(oini), (rc, msgs[:400], choice_record(b))) + os.replace(oini + ".away", oini) + rc = t.run("set", exe, "model=M") + t.check("...set model=M with OptiScaler.ini back: its entry is Model M's (0)", rc == 0 and upscaler_index(read(oini).decode("utf-8", "replace")) == "0", rc) + # the front end's upgrade migration (no record yet) against a REAL launcher apply in another process: the launcher holds the + # game's state lock (test hook: it pauses after reading the record, before writing it); the migration, started then, waits + # for the lock and finds the launcher's record (L), so it writes nothing (without the lock it would have written M first) + if RECORD_TOOL: + os.remove(rec_path) + sig = os.path.join(t.work, "choice-lock.signal") + if os.path.exists(sig): + os.remove(sig) + if os.path.exists(t.out): + os.remove(t.out) + env = dict(t.env, WRONGGPU_TEST_PAUSE_IN_CHOICE_LOCK=sig + "|1500") + cmd = [t.exe, "set", exe, "model=L", "--noscan", "--log=" + t.log, "--out=" + t.out, "--data=" + os.path.join(t.work, "data")] + launcher = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + for _ in range(500): + if os.path.exists(sig): + break + time.sleep(0.01) + mig = subprocess.run([RECORD_TOOL, "migrate", b], env=t.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60) + lrc = launcher.wait(timeout=120) + out = mig.stdout.decode("utf-8", "replace").strip() + rr = choice_record(b) + t.check("migration against a real launcher apply holding the lock: the launcher records L (seq 1), the migration waits and writes nothing", + os.path.exists(sig) and lrc == 0 and mig.returncode == 0 and out == "migrate: ok model=L seq=1 migrated=0" and + rr == {"model": "L", "seq": "1", "source": "launcher"}, (lrc, mig.returncode, out, rr)) + else: + print(" (the migration race against a real launcher apply: no --record-tool given, not run)") # a game saved on L whose data goes away: a repair keeps the player's choice, the files say Model M with a warning rc = t.run("set", exe, "model=L") os.remove(os.path.join(t.lad, "WrongGPU", "model", "L", "model.wgcm")) # (t.model is the case here, not the path helper) @@ -409,7 +459,11 @@ def main(): ap.add_argument("--reference-launcher", help="WrongGPU.exe of the base branch (same payload and test map)") ap.add_argument("--launcher-choice", help="WrongGPU.exe built with -DWRONGGPU_MODEL_L=ON and the test map (the model choice)") ap.add_argument("--work", default=os.path.join(HERE, "..", "build-tests", "model-l")) + ap.add_argument("--record-tool", help="clean/fsr's test_model_choice_record.exe: the front end's upgrade migration in its own " + "process, for the race against a real launcher apply (skipped without it)") a = ap.parse_args() + global RECORD_TOOL + RECORD_TOOL = os.path.abspath(a.record_tool) if a.record_tool else None if a.write_test_map: write(a.write_test_map, map_bytes(l_case())) print("test map: " + a.write_test_map) From 9a2788a122db2b53797995a16fd43866f2c15233 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:13:06 -0500 Subject: [PATCH 14/15] CI: check OptiScaler WrongGPU edition's copy of wg_model_entries.h tools/ci/check_vendored_model_entries.py fails when clean/wgshared/include/wg_model_entries.h no longer has its pinned SHA-256, or when the fork's copy (OptiScaler/include/wronggpu/wg_model_entries.h at the pinned fork commit, fetched from GitHub) is not byte-identical to it. The version box stores the player's entry as a position in WrongGPU's version list, so the two copies must never differ. Run in the "Licence and line endings" job. Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- .github/workflows/ci.yml | 2 + tools/ci/check_vendored_model_entries.py | 60 ++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 tools/ci/check_vendored_model_entries.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dcd8b556..351aaf0f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,6 +26,8 @@ jobs: python-version: "3.12" - name: Line endings run: python tools/ci/check_line_endings.py + - name: Vendored model entry order (OptiScaler WrongGPU edition) + run: python tools/ci/check_vendored_model_entries.py - name: Licence (REUSE) run: | $PSNativeCommandUseErrorActionPreference = $true diff --git a/tools/ci/check_vendored_model_entries.py b/tools/ci/check_vendored_model_entries.py new file mode 100644 index 00000000..65b18579 --- /dev/null +++ b/tools/ci/check_vendored_model_entries.py @@ -0,0 +1,60 @@ +# SPDX-License-Identifier: MIT +"""Vendored-copy check (CI): OptiScaler WrongGPU edition holds a byte-identical copy of +clean/wgshared/include/wg_model_entries.h (the order of WrongGPU's model entries in the version list its FFX DLL gives a +host; OptiScaler stores the player's entry as a position in that list). The two must never differ. + +This check fails when + - clean/wgshared/include/wg_model_entries.h no longer has the SHA-256 pinned below (a change to the order needs the + fork's copy updated first, then FORK_COMMIT and HEADER_SHA256 here), or + - the fork's copy at FORK_COMMIT is not byte-identical to it (fetched from GitHub; --offline skips this part). +Run from the repository root: python tools/ci/check_vendored_model_entries.py [--offline] +""" +import hashlib +import subprocess +import sys +import urllib.request +from pathlib import Path + +HEADER = 'clean/wgshared/include/wg_model_entries.h' +HEADER_SHA256 = 'dbc42cf67378a610c35935829683f3928a98e83f1bfb49b53e1f36152da9ab4f' +FORK_REPO = 'phantoslayer21/OptiScaler' +FORK_COMMIT = 'f31d091df2989f70c1e4ab296942de69240af227' +FORK_PATH = 'OptiScaler/include/wronggpu/wg_model_entries.h' + + +def sha256(data): + return hashlib.sha256(data).hexdigest() + + +def main(argv): + root = Path(subprocess.check_output(['git', 'rev-parse', '--show-toplevel'], text=True).strip()) + ours = (root / HEADER).read_bytes() + problems = [] + + if sha256(ours) != HEADER_SHA256: + problems.append('%s has SHA-256 %s, pinned %s: update the fork\'s copy (%s), then FORK_COMMIT and ' + 'HEADER_SHA256 in this script' % (HEADER, sha256(ours), HEADER_SHA256, FORK_PATH)) + + if '--offline' not in argv: + url = 'https://raw.githubusercontent.com/%s/%s/%s' % (FORK_REPO, FORK_COMMIT, FORK_PATH) + try: + with urllib.request.urlopen(url, timeout=60) as r: + theirs = r.read() + except OSError as e: + problems.append('could not fetch the fork\'s copy (%s): %s' % (url, e)) + else: + if theirs != ours: + problems.append('the fork\'s copy at %s (SHA-256 %s) differs from %s (SHA-256 %s)' + % (FORK_COMMIT[:12], sha256(theirs), HEADER, sha256(ours))) + + for p in problems: + print('FAIL: ' + p) + if problems: + return 1 + print('vendored wg_model_entries.h: %s matches the pin%s' % (HEADER, '' if '--offline' in argv else + ' and the fork\'s copy at ' + FORK_COMMIT[:12])) + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) From 62dc5df05599b586d62a73161b39ebed751c49bd Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:46:37 -0500 Subject: [PATCH 15/15] Model choice: the player's files stay the player's; a partial apply says what was applied - model-choice.ini is written in place through #224's state-file updater (wg_state.h UpdateStateFile, the settings.ini updater generalised for any state file of the folder): only the record's three key lines change; comments, other lines and line ends stay; the stamp is put back only when the file was WrongGPU's and unedited (or new), so an edited or player-made record stays unstamped and the uninstall keeps it. A record that is not a valid record is never replaced: the choice is refused with one log line (the front end returns "refused", the plugin's entry says so, the launcher warns) and the model that runs stays. Tests: edited, player-made, corrupt. - wronggpu-asi.ini: the launcher's Apply changes only its selection line (wgasi::WithSelection) and keeps every other byte; a file whose bytes were WrongGPU's (the install record's hash) stays WrongGPU's under its new hash, the player's stays the player's. Tests: unit, and the Model L suite with a player's file (comments, selection=amd). - dllmain.cpp / win_util.h: the callables that keep a string of the configuration (model places, AMD's DLL, the comparison DLL) are named classes, not lambdas capturing the string by copy. - A partial apply: when the RR write fails after other settings were written, the message lists exactly what was applied and what was not (no "settings not applied" after some were), and the install record keeps the hashes of the files WrongGPU changed. Test: the launcher suite's RR group with the write failure injected (WRONGGPU_TEST_FAIL_RR_STATE, testing builds only). Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/fsr/asi/asi_thunk.h | 30 ++++- clean/fsr/asi/wronggpu_asi.cpp | 6 +- clean/fsr/src/dllmain.cpp | 69 ++++++---- clean/fsr/src/frontend.cpp | 5 + clean/fsr/src/model_choice_record.h | 119 ++++++++++++------ clean/fsr/src/win_util.h | 9 +- clean/fsr/tests/test_asi_thunk.cpp | 10 ++ clean/fsr/tests/test_frontend.cpp | 18 ++- clean/fsr/tests/test_model_choice_record.cpp | 58 +++++++-- clean/installer/src/wg_core/launcher.cpp | 43 ++++++- .../tests/launcher_partial_apply_cases.py | 26 ++++ clean/installer/tests/run_launcher_tests.py | 1 + clean/installer/tests/run_model_l_tests.py | 16 +++ clean/wgshared/include/wg_state.h | 24 ++-- 14 files changed, 339 insertions(+), 95 deletions(-) create mode 100644 clean/installer/tests/launcher_partial_apply_cases.py diff --git a/clean/fsr/asi/asi_thunk.h b/clean/fsr/asi/asi_thunk.h index 6c101d3f..2b6710f1 100644 --- a/clean/fsr/asi/asi_thunk.h +++ b/clean/fsr/asi/asi_thunk.h @@ -161,10 +161,36 @@ inline char ParseSelection(const std::string& text) { return kDefaultModel; } +inline const char* SelectionValue(char model) { + return model == kModelAmd ? "amd" : model == kModelK ? "wronggpu-k" : model == kModelL ? "wronggpu-l" : "wronggpu"; +} + inline std::string FormatSelection(char model) { - const char* v = model == kModelAmd ? "amd" : model == kModelK ? "wronggpu-k" : model == kModelL ? "wronggpu-l" : "wronggpu"; return std::string("; WrongGPU OptiScaler plugin: the entry last selected in OptiScaler's upscaler list\r\n") + - "; (wronggpu, wronggpu-k, wronggpu-l or amd). Deleting this file selects WrongGPU.\r\nselection=" + v + "\r\n"; + "; (wronggpu, wronggpu-k, wronggpu-l or amd). Deleting this file selects WrongGPU.\r\nselection=" + SelectionValue(model) + "\r\n"; +} + +// `text` with its selection set to `model`, every other byte kept: the line ParseSelection reads (the first one that is +// "selection=..." once spaces are ignored) becomes "selection=" and keeps its own line end; a file without one gets +// the line at its end (with the file's first line end, CRLF when it has none; a last line without a line end gets one). +inline std::string WithSelection(const std::string& text, char model) { + const std::string want = std::string("selection=") + SelectionValue(model); + size_t at = 0; + while (at < text.size()) { + size_t end = text.find('\n', at); + const size_t next = end == std::string::npos ? text.size() : end + 1; + if (end == std::string::npos) end = text.size(); + size_t stop = end; + if (stop > at && text[stop - 1] == '\r') --stop; // the line end ("\r\n" or "\n") stays + std::string line; + for (size_t i = at; i < stop; ++i) + if (!std::isspace(static_cast(text[i]))) line += char(std::tolower(static_cast(text[i]))); + if (line.rfind("selection=", 0) == 0) return text.substr(0, at) + want + text.substr(stop); + at = next; + } + const size_t lf = text.find('\n'); + const std::string eol = lf != std::string::npos && lf > 0 && text[lf - 1] == '\r' ? "\r\n" : lf != std::string::npos ? "\n" : "\r\n"; + return text + (text.empty() || text.back() == '\n' ? "" : eol) + want + eol; } } // namespace wgasi diff --git a/clean/fsr/asi/wronggpu_asi.cpp b/clean/fsr/asi/wronggpu_asi.cpp index 34430675..cf6bfe8c 100644 --- a/clean/fsr/asi/wronggpu_asi.cpp +++ b/clean/fsr/asi/wronggpu_asi.cpp @@ -125,8 +125,10 @@ wgasi::Save RecordModelChoice(char model) { } AsiLog::Get().Write(std::string("ERROR: model choice record ") + wgasi::Utf8(path) + ": Model " + model + " not saved (" + wgchoice::OutcomeWords(o) + (why.empty() ? "" : ": " + why) + "); nothing changed" + - (o == wgchoice::Outcome::SeqExhausted ? ". Delete the record or apply the model in the launcher." : ", try again")); - return o == wgchoice::Outcome::SeqExhausted ? wgasi::Save::Refused : wgasi::Save::NotSaved; + (o == wgchoice::Outcome::SeqExhausted ? ". Delete the record or apply the model in the launcher." + : o == wgchoice::Outcome::Corrupt ? "" // (OutcomeWords says to fix or delete the file) + : ", try again")); + return o == wgchoice::Outcome::SeqExhausted || o == wgchoice::Outcome::Corrupt ? wgasi::Save::Refused : wgasi::Save::NotSaved; } extern "C" bool WgSelectableThunk(const char* label, bool selected, int flags, const void* size) { diff --git a/clean/fsr/src/dllmain.cpp b/clean/fsr/src/dllmain.cpp index 06e34da7..9dcb7790 100644 --- a/clean/fsr/src/dllmain.cpp +++ b/clean/fsr/src/dllmain.cpp @@ -151,6 +151,48 @@ bool StartTimer(uint32_t ms, std::function fn) { return true; } +// The callables Get() gives the front end that keep a string of the configuration. Named classes, not lambdas that +// capture the string by copy: with MSVC's /Zc:lambda (on with /permissive-, as in CI) a lambda whose capture copy throws +// (std::bad_alloc) terminates the process instead of unwinding; the same copy in a class constructor unwinds normally +// (async_create.h DeviceRelease). +// +// Where the converted model is looked for (config.h ModelPlace): wronggpu.ini [fsr] model_dir, the game's data folder, +// then the runtime's own default. +struct ModelPlacesOf { + std::string modelDir; + explicit ModelPlacesOf(const std::string& d) : modelDir(d) {} + std::vector operator()() const { + std::vector places; + const std::wstring data = Place().dataDir; + if (!modelDir.empty()) { + std::wstring dir = Widen(modelDir); + const bool absolute = dir.size() > 1 && (dir[1] == L':' || (dir[0] == L'\\' && dir[1] == L'\\')); + if (!absolute) dir = data + L"\\" + dir; + places.push_back({Narrow(dir), "wronggpu.ini model_dir", false}); + } + wchar_t exe[MAX_PATH] = {}; + const DWORD n = GetModuleFileNameW(nullptr, exe, MAX_PATH); + std::wstring exeDir(exe, n); + exeDir = exeDir.substr(0, exeDir.find_last_of(L"\\/") == std::wstring::npos ? 0 : exeDir.find_last_of(L"\\/")); + const std::wstring gameData = exeDir + L"\\WrongGPU"; + places.push_back({Narrow(gameData + L"\\model"), "the game's data folder", false}); + if (_wcsicmp(data.c_str(), gameData.c_str()) != 0) places.push_back({Narrow(data + L"\\model"), "the data folder (WG_DATA_DIR)", false}); + wchar_t local[MAX_PATH] = {}; + const DWORD m = GetEnvironmentVariableW(L"LOCALAPPDATA", local, MAX_PATH); + if (m > 0 && m < MAX_PATH) places.push_back({Narrow(std::wstring(local, m) + L"\\WrongGPU\\model"), "%LOCALAPPDATA%", true}); + return places; + } +}; +// AMD's upscaler for fallbacks and the version list: the DLL next to this one, else the comparison DLL. +struct OriginalOrCompare { + std::string dll; + explicit OriginalOrCompare(const std::string& d) : dll(d) {} + const OriginalApi* operator()() const { + if (const OriginalApi* o = LoadOriginal()) return o; + return CompareApi(dll); + } +}; + FrontEnd& Get() { std::call_once(g_initOnce, [] { // Shared settings first (clean/wgshared): data folder, wronggpu.ini, the shared block (this DLL writes it when @@ -202,27 +244,7 @@ FrontEnd& Get() { // Where the converted model is looked for (config.h ModelPlace): wronggpu.ini [fsr] model_dir, the game's data // folder, then the runtime's own default. Files a game reads must be in places the game's process sees: the // installer's %LOCALAPPDATA% copy can be private to another app's container. - p.modelPlaces = [modelDir = config.modelDir] { - std::vector places; - const std::wstring data = Place().dataDir; - if (!modelDir.empty()) { - std::wstring dir = Widen(modelDir); - const bool absolute = dir.size() > 1 && (dir[1] == L':' || (dir[0] == L'\\' && dir[1] == L'\\')); - if (!absolute) dir = data + L"\\" + dir; - places.push_back({Narrow(dir), "wronggpu.ini model_dir", false}); - } - wchar_t exe[MAX_PATH] = {}; - const DWORD n = GetModuleFileNameW(nullptr, exe, MAX_PATH); - std::wstring exeDir(exe, n); - exeDir = exeDir.substr(0, exeDir.find_last_of(L"\\/") == std::wstring::npos ? 0 : exeDir.find_last_of(L"\\/")); - const std::wstring gameData = exeDir + L"\\WrongGPU"; - places.push_back({Narrow(gameData + L"\\model"), "the game's data folder", false}); - if (_wcsicmp(data.c_str(), gameData.c_str()) != 0) places.push_back({Narrow(data + L"\\model"), "the data folder (WG_DATA_DIR)", false}); - wchar_t local[MAX_PATH] = {}; - const DWORD m = GetEnvironmentVariableW(L"LOCALAPPDATA", local, MAX_PATH); - if (m > 0 && m < MAX_PATH) places.push_back({Narrow(std::wstring(local, m) + L"\\WrongGPU\\model"), "%LOCALAPPDATA%", true}); - return places; - }; + p.modelPlaces = ModelPlacesOf(config.modelDir); p.fileExists = [](const std::string& path) { const DWORD a = GetFileAttributesW(Widen(path).c_str()); return a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY); @@ -244,10 +266,7 @@ FrontEnd& Get() { // host's way in and would route the call back to this DLL (config.h Config::customSlot). p.original = []() -> const OriginalApi* { return LoadOriginal(); }; } else { - p.original = [dll]() -> const OriginalApi* { - if (const OriginalApi* o = LoadOriginal()) return o; - return CompareApi(dll); - }; + p.original = OriginalOrCompare(dll); } // If WrongGPU.asi has hooked OptiScaler's menu, its entry says WrongGPU or AMD, and the game's model choice // record (model_choice_record.h, next to wronggpu.ini) says which WrongGPU model. Absent or not hooked: hosted diff --git a/clean/fsr/src/frontend.cpp b/clean/fsr/src/frontend.cpp index 79bf2979..79c2df9a 100644 --- a/clean/fsr/src/frontend.cpp +++ b/clean/fsr/src/frontend.cpp @@ -1576,6 +1576,11 @@ int32_t FrontEnd::HostSelected(uint64_t versionId) { ". Delete wronggpu-setup\\model-choice.ini or apply the model in the launcher."); return WG_HOST_SELECTED_REFUSED; } + if (o == wgchoice::Outcome::Corrupt) { // never replaced: the model that runs stays + Log(tag + " ERROR: the player selected Model " + model + " in OptiScaler's upscaler list: " + wgchoice::OutcomeWords(o) + + (err.empty() ? "" : " (" + err + ")") + ". Nothing changes."); + return WG_HOST_SELECTED_REFUSED; + } Log(tag + " ERROR: the player selected Model " + model + " in OptiScaler's upscaler list, but it was not saved: " + wgchoice::OutcomeWords(o) + (err.empty() ? "" : " (" + err + ")") + ". Nothing changes; select it again."); return WG_HOST_SELECTED_NOT_SAVED; diff --git a/clean/fsr/src/model_choice_record.h b/clean/fsr/src/model_choice_record.h index 4ba2ae2f..a3ad5ed4 100644 --- a/clean/fsr/src/model_choice_record.h +++ b/clean/fsr/src/model_choice_record.h @@ -23,7 +23,9 @@ // seq=<1..18446744073709551615> (decimal digits only, overflow refused) // source= // each key exactly once, no other key, no spaces around '='; the last line is WrongGPU's stamp (a comment, -// wg_state.h Stamped) when the install has an id. Writes: wgstate::WriteStamped (a temporary file in the same +// wg_state.h Stamped) when the file is WrongGPU's and unedited and the install has an id. Writes: in place through +// wgstate::UpdateStateFile (only the three keys' lines change; a corrupt record is never replaced; an edited or +// player-made record stays the player's, unstamped; RecordChoiceUnlocked), a temporary file in the same // folder, written and flushed, then MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH), every step checked), tried up to 3 // times. Readers take the lock too, so a reader never sees part of a record. A temporary file a crash left behind is // never read. @@ -123,10 +125,13 @@ inline bool ParseRecord(const std::string& text, Record* out, std::string* why) return true; } +// The comment a new record starts with. +constexpr const char* kRecordHeader = + "; WrongGPU: the model chosen last for this game, by the launcher, OptiScaler's upscaler list (ffx) or the\r\n" + "; WrongGPU menu plugin. The highest seq is the most recent choice. Written by WrongGPU; do not edit.\r\n"; + inline std::string FormatRecord(const Record& r) { - return std::string("; WrongGPU: the model chosen last for this game, by the launcher, OptiScaler's upscaler list (ffx) or the\r\n" - "; WrongGPU menu plugin. The highest seq is the most recent choice. Written by WrongGPU; do not edit.\r\n") + - "model=" + r.model + "\r\nseq=" + std::to_string(r.seq) + "\r\nsource=" + SourceName(r.source) + "\r\n"; + return std::string(kRecordHeader) + "model=" + r.model + "\r\nseq=" + std::to_string(r.seq) + "\r\nsource=" + SourceName(r.source) + "\r\n"; } // ---- the lock ------------------------------------------------------------------------------------------------------- @@ -175,26 +180,9 @@ inline ReadResult ReadRecordFile(const std::filesystem::path& path, Record* out, return ParseRecord(text, out, why) ? ReadResult::Ok : ReadResult::Corrupt; } -// The atomic replace of the record (wgstate::WriteStamped: WriteAtomic with WrongGPU's stamp line for this file and the -// game's install id, so the launcher's uninstall knows the record as WrongGPU's; an install without an id: no stamp. A -// temporary file in the same folder, flushed, then MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH), every step checked; the -// temporary file deleted when a step fails), tried up to `attempts` times, 20 ms apart. false with *why. Call it under -// the record's Lock. (The stamp is a comment line: ParseRecord skips it.) -inline bool WriteRecordFile(const std::filesystem::path& path, const Record& r, std::string* why, int attempts = 3) { - const std::string text = FormatRecord(r); - wgstate::WriteResult w; - for (int i = 0; i < attempts; ++i) { - w = wgstate::WriteStamped(GameDirOf(path).wstring(), path.wstring(), text); - if (w.ok) return true; - if (i + 1 < attempts) Sleep(20); - } - if (why) *why = "cannot replace the record: " + w.words(); - return false; -} - // ---- the operations, each one read-modify-write under the lock ------------------------------------------------------ -enum class Outcome { Written, NoLock, Unreadable, SeqExhausted, WriteFailed }; +enum class Outcome { Written, NoLock, Unreadable, SeqExhausted, WriteFailed, Corrupt }; inline const char* OutcomeWords(Outcome o) { switch (o) { @@ -203,33 +191,80 @@ inline const char* OutcomeWords(Outcome o) { case Outcome::Unreadable: return "the record cannot be read (not written over)"; case Outcome::SeqExhausted: return "the record's sequence number is at its end (18446744073709551615): choice refused"; case Outcome::WriteFailed: return "the record could not be written"; + case Outcome::Corrupt: + return "the record (wronggpu-setup\\model-choice.ini) is not a valid record, so it is left as it is and the choice is " + "refused (fix the file or delete it)"; } return "?"; } -// A choice of `model` by `source`: read the record and write seq + 1 (seq 1 without a record, or over a corrupt one, -// which *why then names). *after: the record written; *before: the record it replaced (model 0 when there was none or it -// was corrupt). Any failure leaves the record as it was and nothing is kept for later: the caller says "not saved". Call -// it holding the game's state lock (RecordChoice takes it). +// A choice of `model` by `source`: the record's model, seq + 1 (seq 1 without a record) and source, written IN PLACE through +// wgstate::UpdateStateFile (#224's rule for the game's state files): the file is held from the read to the replace, only +// the three keys' lines change, every other line (the player's comments, blank lines) and every line end stay, and the +// stamp is put back only when the file was WrongGPU's and unedited (its valid stamp) or new; an edited or player-made +// record stays unstamped, the player's, and an uninstall keeps it. A record that is not a valid record (corrupt, or text +// WrongGPU cannot keep) is never replaced: Corrupt (*why says what is wrong), and the caller keeps the model that runs. +// *after: the record written; *before: the record it replaced (model 0 when there was none). Any failure leaves the file +// as it was and nothing is kept for later: the caller says "not saved". A failed write is tried up to 3 times. Call it +// holding the game's state lock (RecordChoice takes it; the lock is recursive on one thread). inline Outcome RecordChoiceUnlocked(const std::filesystem::path& path, char model, Source source, Record* after, std::string* why, Record* before = nullptr) { - Record cur; + if (before) *before = Record{0, 0, Source::Launcher}; + Outcome result = Outcome::Written; + Record next{model, 1, source}; std::string err; - const ReadResult rr = ReadRecordFile(path, &cur, &err); - if (before) *before = rr == ReadResult::Ok ? cur : Record{0, 0, Source::Launcher}; - if (rr == ReadResult::Unreadable) { - if (why) *why = err; - return Outcome::Unreadable; + wgstate::SetOutcome o; + for (int attempt = 0; attempt < 3; ++attempt) { + result = Outcome::Written; + err.clear(); + o = wgstate::UpdateStateFile( + GameDirOf(path).wstring(), kRecordFile, + [&](const wgstate::Settings& now, std::vector>* changes) { + Record cur; + bool had = false; + if (now.present) { // (the strict record rules on the file as read, its valid stamp already off) + if (!ParseRecord(wgstate::RenderSettings(now), &cur, &err)) { result = Outcome::Corrupt; return; } + had = true; + if (before) *before = cur; + if (cur.seq == UINT64_MAX) { result = Outcome::SeqExhausted; return; } + } + next = Record{model, had ? cur.seq + 1 : 1, source}; + changes->push_back({"model", std::string(1, model)}); + changes->push_back({"seq", std::to_string(next.seq)}); + changes->push_back({"source", SourceName(source)}); + }, + 1000, kRecordHeader); + const bool writeFailed = o.result == wgstate::SetResult::WriteFailed || (o.result == wgstate::SetResult::AccessDenied && o.write.error); + if (!writeFailed || result != Outcome::Written) break; + Sleep(20); } - if (rr == ReadResult::Corrupt && why) *why = "a corrupt record was replaced (" + err + ")"; - if (rr == ReadResult::Ok && cur.seq == UINT64_MAX) return Outcome::SeqExhausted; - const Record next{model, rr == ReadResult::Ok ? cur.seq + 1 : 1, source}; - if (!WriteRecordFile(path, next, &err)) { - if (why) *why = err; + switch (o.result) { + case wgstate::SetResult::Ok: + if (result != Outcome::Written) { + if (why && !err.empty()) *why = err; + return result; + } + if (after) *after = next; + return Outcome::Written; + case wgstate::SetResult::Unparseable: + if (why) *why = o.why; + return Outcome::Corrupt; + case wgstate::SetResult::Busy: + case wgstate::SetResult::LockDenied: + if (why) *why = o.words(); + return Outcome::NoLock; + case wgstate::SetResult::AccessDenied: + if (why) *why = o.words(); + return o.write.error ? Outcome::WriteFailed : Outcome::Unreadable; // (denied at the replace: a write that failed) + case wgstate::SetResult::Unreadable: + case wgstate::SetResult::NoStateFolder: + case wgstate::SetResult::StateFolderUnknown: + if (why) *why = o.words(); + return Outcome::Unreadable; + default: + if (why) *why = o.words(); return Outcome::WriteFailed; } - if (after) *after = next; - return Outcome::Written; } inline Outcome RecordChoice(const std::filesystem::path& path, char model, Source source, Record* after, std::string* why, @@ -260,8 +295,10 @@ inline LoadResult LoadOrMigrateRecord(const std::filesystem::path& path, Launche if (rr == ReadResult::Corrupt) return LoadResult::Corrupt; if (rr == ReadResult::Unreadable) return LoadResult::Unreadable; const char m = launcherModel(); - const Record first{IsModel(m) ? m : 'M', 1, Source::Launcher}; - if (!WriteRecordFile(path, first, why)) return LoadResult::Missing; + Record first; + const Outcome wo = RecordChoiceUnlocked(path, IsModel(m) ? m : 'M', Source::Launcher, &first, why); + if (wo == Outcome::Corrupt) return LoadResult::Corrupt; // (a file that appeared meanwhile is the player's: left as it is) + if (wo != Outcome::Written) return LoadResult::Missing; *out = first; if (migrated) *migrated = true; return LoadResult::Ok; diff --git a/clean/fsr/src/win_util.h b/clean/fsr/src/win_util.h index 7f5f64fa..d7d42cea 100644 --- a/clean/fsr/src/win_util.h +++ b/clean/fsr/src/win_util.h @@ -71,6 +71,13 @@ const WgUpscalerBackend* StandInForFallback(const wgfsr::Config& config); // and checked (CheckProviderModule). Logs the choice, or "FSR 4 / AMD versions not available: ..." when none is usable // (null then). const wgfsr::OriginalApi* CompareApi(const std::string& path); +// CompareApi of a path kept by copy: a named class, not a lambda capturing the string (MSVC /Zc:lambda: a throwing capture +// copy terminates instead of unwinding; async_create.h DeviceRelease). +struct CompareApiOf { + std::string path; + explicit CompareApiOf(const std::string& p) : path(p) {} + const wgfsr::OriginalApi* operator()() const { return CompareApi(path); } +}; // Whether `m`, got from LoadLibrary of `requested`, is that AMD FidelityFX API DLL: not WrongGPU's own module or a copy // of it, the file that was asked for (a host's LoadLibrary hook can hand out OptiScaler's or WrongGPU's module for an // AMD file name), the FidelityFX API exports, none of which jumps into a module that is not AMD's (a host's hook). @@ -105,7 +112,7 @@ void AddSplitServices(PlatformT& p, const wgfsr::Config& config) { }; p.gpuTimer = &OverlayGpuTimer; p.compareAmd = &OverlayCompareAmd; - p.compareApi = [dll = config.compareDll] { return CompareApi(dll); }; + p.compareApi = CompareApiOf(config.compareDll); // (a named class: no lambda copies the path, as in dllmain.cpp) p.services = &SplitServices; p.noteDispatch = &NoteDispatch; p.standIn = &StandInForFallback; diff --git a/clean/fsr/tests/test_asi_thunk.cpp b/clean/fsr/tests/test_asi_thunk.cpp index 11d030f0..2cb6ff97 100644 --- a/clean/fsr/tests/test_asi_thunk.cpp +++ b/clean/fsr/tests/test_asi_thunk.cpp @@ -160,6 +160,16 @@ void TestSelectionFile() { CHECK(ParseSelection(FormatSelection(kModelM)) == kModelM); CHECK(FormatSelection(kModelM).find("selection=wronggpu\r\n") != std::string::npos); CHECK(ParseSelection("selection=wronggpu-l") == (WRONGGPU_MODEL_L ? kModelL : kModelM)); + // WithSelection: only the selection line ParseSelection reads changes; every other byte stays (the player's comments, + // a later selection line ParseSelection never reads, line ends, a last line without one) + const std::string mine = "# my notes: AMD for screenshots\r\n\r\n Selection = AMD \r\n; keep\nselection=wronggpu-k\n# end"; + CHECK(WithSelection(mine, kModelM) == "# my notes: AMD for screenshots\r\n\r\nselection=wronggpu\r\n; keep\nselection=wronggpu-k\n# end"); + CHECK(ParseSelection(WithSelection(mine, kModelM)) == kModelM); + CHECK(WithSelection("selection=amd", kModelM) == "selection=wronggpu"); // no line end: none added + CHECK(WithSelection("; only a comment\n", kModelM) == "; only a comment\nselection=wronggpu\n"); // none there: appended + CHECK(WithSelection("; no line end", kModelAmd) == "; no line end\r\nselection=amd\r\n"); + CHECK(WithSelection("", kModelM) == "selection=wronggpu\r\n"); + CHECK(WithSelection(FormatSelection(kModelAmd), kModelM) == FormatSelection(kModelM)); // WrongGPU's own file } // A click records the model and reports it; the menu marks the model the front end reported (ShownModel) until the diff --git a/clean/fsr/tests/test_frontend.cpp b/clean/fsr/tests/test_frontend.cpp index 4ce0b9d0..f15b109f 100644 --- a/clean/fsr/tests/test_frontend.cpp +++ b/clean/fsr/tests/test_frontend.cpp @@ -3245,16 +3245,26 @@ static void TestAsiChoiceRecord() { CHECK(ReadRec(rec).model == b); #endif // (14) a corrupt record (seq overflow): said once, not used (a fresh session: wronggpu.ini's item, never the host's - // entry), not written over by a create; the next real choice replaces it - WriteRec(rec, "model=L\nseq=18446744073709551616\nsource=launcher\n"); + // entry), not written over by a create; NOR by a choice: the selection is refused (-2) with one log line, the file + // keeps its bytes (the player's to fix or delete) and the model that runs stays (b) + const std::string corrupt = "model=L\nseq=18446744073709551616\nsource=launcher\n"; + WriteRec(rec, corrupt); CHECK(HostedCreate(iniB.c_str(), 0, idOf('M'), false) == name(b)); CHECK(CountLog("is corrupt (seq is not a number") == 1); wgchoice::ReadResult rr; ReadRec(rec, &rr); CHECK(rr == wgchoice::ReadResult::Corrupt); - CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name('M')); + CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name(b)); + CHECK(rc == WG_HOST_SELECTED_REFUSED); + CHECK(CountLog("in OptiScaler's upscaler list: the record (wronggpu-setup\\model-choice.ini) is not a valid record") == 1); + { + std::ifstream i(rec, std::ios::binary); + CHECK(std::string(std::istreambuf_iterator(i), {}) == corrupt); + } + WriteRec(rec, "model=M\nseq=1\nsource=ffx\n"); // the player fixes the file: the next choice is saved again + CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf(b)); }) == name(b)); r = ReadRec(rec); - CHECK(rc == WG_HOST_SELECTED_RECORDED && r.model == 'M' && r.seq == 1 && r.source == wgchoice::Source::Ffx); + CHECK(rc == WG_HOST_SELECTED_RECORDED && r.model == b && r.seq == 2 && r.source == wgchoice::Source::Ffx); // (15) the end of the sequence numbers: the selection is refused loudly (-2), the record unchanged WriteRec(rec, std::string("model=") + b + "\nseq=18446744073709551615\nsource=plugin\n"); CHECK(HostedCreate(iniM, 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name(b)); diff --git a/clean/fsr/tests/test_model_choice_record.cpp b/clean/fsr/tests/test_model_choice_record.cpp index d1f889db..a904c667 100644 --- a/clean/fsr/tests/test_model_choice_record.cpp +++ b/clean/fsr/tests/test_model_choice_record.cpp @@ -132,9 +132,14 @@ void TestStampedRecord() { CHECK(RecordChoice(f.record(), 'K', Source::Ffx, &after, &why) == Outcome::Written && after.seq == 2); CHECK(wgstate::ReadBytes(f.record().wstring(), &bytes) && wgstate::StampedByWrongGPU(bytes, "model-choice.ini", id)); CHECK(ReadRecordFile(f.record(), &r, &why) == ReadResult::Ok && r.model == 'K' && r.seq == 2 && r.source == Source::Ffx); - // without an install id (no install record): written without a stamp, as before + // without an install id (no install record): nothing is stamped (the earlier stamp line is no longer valid and stays as a + // comment, as #224's updater keeps any line that is not a valid stamp); a new record without an id: no stamp line at all fs::remove(f.dir / kStateFolder / "install.record"); CHECK(RecordChoice(f.record(), 'M', Source::Plugin, &after, &why) == Outcome::Written); + CHECK(wgstate::ReadBytes(f.record().wstring(), &bytes) && !wgstate::StampedByWrongGPU(bytes, "model-choice.ini", id)); + CHECK(ReadRecordFile(f.record(), &r, &why) == ReadResult::Ok && r.model == 'M' && r.seq == 3); + fs::remove(f.record()); + CHECK(RecordChoice(f.record(), 'K', Source::Launcher, &after, &why) == Outcome::Written && after.seq == 1); CHECK(wgstate::ReadBytes(f.record().wstring(), &bytes) && bytes.find(wgstate::kStampPrefix) == std::string::npos); } @@ -177,21 +182,59 @@ void TestChoicesInTurn() { CHECK(TmpFiles(f) == 0); // no temporary file is left behind by the writes } +// #224's rule for the game's state files: a choice changes only the record's three key lines, in place. A record WrongGPU +// wrote and nobody changed keeps WrongGPU's stamp; one the player edited (a comment added to a stamped record) or made +// (no stamp) keeps every other byte (comments, blank lines, line ends) and stays UNSTAMPED, the player's, which the +// launcher's uninstall keeps. +void TestPlayerFiles() { + Folder f("player"); + const std::string id = "00112233445566778899aabbccddeeff"; + { + std::ofstream o(f.dir / kStateFolder / "install.record", std::ios::binary); + o << "WRONGGPU-RECORD 2\r\ninstall-id\t" << id << "\r\n"; + } + Record after, r; + std::string why, bytes; + // WrongGPU's own record: re-stamped + CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::Written); + CHECK(wgstate::ReadBytes(f.record().wstring(), &bytes) && wgstate::StampedByWrongGPU(bytes, "model-choice.ini", id)); + // edited: the player adds a comment line to the stamped record; the next choice keeps it, writes K, no stamp + WriteRaw(f.record(), "; my note: keep L for this game\r\n" + bytes); + CHECK(RecordChoice(f.record(), 'K', Source::Ffx, &after, &why) == Outcome::Written && after.seq == 2); + CHECK(wgstate::ReadBytes(f.record().wstring(), &bytes)); + CHECK(bytes.rfind("; my note: keep L for this game\r\n", 0) == 0); + CHECK(bytes.find("model=K\r\nseq=2\r\nsource=ffx\r\n") != std::string::npos); + CHECK(!wgstate::StampedByWrongGPU(bytes, "model-choice.ini", id)); + CHECK(ReadRecordFile(f.record(), &r, &why) == ReadResult::Ok && r.model == 'K' && r.seq == 2); + // and it stays the player's on the choice after that (still no stamp) + CHECK(RecordChoice(f.record(), 'M', Source::Plugin, &after, &why) == Outcome::Written && after.seq == 3); + CHECK(wgstate::ReadBytes(f.record().wstring(), &bytes) && !wgstate::StampedByWrongGPU(bytes, "model-choice.ini", id)); + CHECK(bytes.rfind("; my note: keep L for this game\r\n", 0) == 0); + // player-made: LF line ends, a blank line, comments around the keys, keys in another order, no stamp + const std::string mine = "# mine\n\nsource=launcher\n; the model:\nmodel=L\nseq=40\n# end\n"; + WriteRaw(f.record(), mine); + CHECK(RecordChoice(f.record(), 'K', Source::Ffx, &after, &why) == Outcome::Written && after.seq == 41); + CHECK(ReadRaw(f.record()) == "# mine\n\nsource=ffx\n; the model:\nmodel=K\nseq=41\n# end\n"); + CHECK(wgstate::ReadBytes(f.record().wstring(), &bytes) && !wgstate::StampedByWrongGPU(bytes, "model-choice.ini", id)); + CHECK(TmpFiles(f) == 0); +} + void TestCorruptAndEnd() { Folder f; Record r, after; std::string why; - // corrupt and overflowing records: Corrupt, never a partial choice; the next choice replaces them whole (seq 1) + // corrupt and overflowing records (and text WrongGPU cannot keep: a NUL): Corrupt, never a partial choice, and NEVER + // replaced: a choice is refused with what is wrong, the file keeps its bytes (the player's to fix or delete) for (const std::string& bad : {Valid("L", "18446744073709551616"), std::string("model=L\nseq=3\n"), std::string(4096, 'x'), - Valid() + "ffx=L\r\n"}) { + Valid() + "ffx=L\r\n", std::string("model=L\0\nseq=3\nsource=ffx\n", 26)}) { WriteRaw(f.record(), bad); CHECK(ReadRecordFile(f.record(), &r, &why) == ReadResult::Corrupt); why.clear(); - CHECK(RecordChoice(f.record(), 'M', Source::Ffx, &after, &why) == Outcome::Written && after.seq == 1); - CHECK(why.find("corrupt") != std::string::npos); - r = Rec(f.record()); - CHECK(r.model == 'M' && r.seq == 1 && r.source == Source::Ffx); + CHECK(RecordChoice(f.record(), 'M', Source::Ffx, &after, &why) == Outcome::Corrupt); + CHECK(!why.empty()); + CHECK(ReadRaw(f.record()) == bad); } + CHECK(std::string(OutcomeWords(Outcome::Corrupt)).find("left as it is") != std::string::npos); // the end of the sequence numbers: refused loudly (SeqExhausted), the record unchanged, never wrapped to 0 WriteRaw(f.record(), Valid("K", "18446744073709551615", "plugin")); const std::string before = ReadRaw(f.record()); @@ -517,6 +560,7 @@ int main(int argc, char** argv) { TestStrictFormat(); TestChoicesInTurn(); TestStampedRecord(); + TestPlayerFiles(); TestCorruptAndEnd(); TestMigration(); #ifdef _WIN32 diff --git a/clean/installer/src/wg_core/launcher.cpp b/clean/installer/src/wg_core/launcher.cpp index 7d507a60..6cea53f6 100644 --- a/clean/installer/src/wg_core/launcher.cpp +++ b/clean/installer/src/wg_core/launcher.cpp @@ -1110,6 +1110,9 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto L"). Try again.", EXIT_REFUSED); char forcedEntry = 0; // the model whose entry OptiScaler.ini's UpscalerIndex is set to (after the record) + // What this apply has written so far, for a failure after some of it: the message then says exactly what was applied + // and what was not (no rollback: each piece is whole on its own). + std::vector applied, notApplied; // wronggpu.ini is never rewritten here: it is the install's defaults and the player's file (the settings the launcher // changes go to the game's WrongGPU state folder, wronggpu-setup: the model choice record below, settings.ini) auto renderOpti = [&]() { @@ -1140,6 +1143,7 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto const wstring h = Sha256Bytes(out.data(), out.size()); for (auto& e : m.e) if (e.action == L"copy" && IEq(e.rel, name) && e.inst != h) { e.inst = h; recordChanged = true; } notes.push_back(wstring(name) + L" written"); + applied.push_back(L"OptiScaler's list (OptiScaler.ini)"); }; // #219: the front end's settings go into the game's state folder (wg_state.h), which the front end reads over wronggpu.ini: // wronggpu.ini holds the install's defaults, is the player's to edit, and is never rewritten after the install. (The model @@ -1150,7 +1154,10 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto if (!RenderWronggpuIni(q, "", unused, &why)) Fail(L"Settings not applied: " + why, EXIT_USAGE); // (validates every setting) const int w = WriteStateKeys(ctx, dir, FrontEndStateKeys(q), &why); if (w < 0) Fail(L"Settings not applied: " + why, EXIT_REFUSED); - if (w > 0) notes.push_back(Join(wgstate::kStateFolder, wgstate::kSettingsFile) + L" written"); + if (w > 0) { + notes.push_back(Join(wgstate::kStateFolder, wgstate::kSettingsFile) + L" written"); + applied.push_back(L"the upscaler settings (" + Join(wgstate::kStateFolder, wgstate::kSettingsFile) + L")"); + } } // The model choice record (clean/fsr/src/model_choice_record.h): the launcher's model choice, with the next seq, when the // player applied a model (Apply in the launcher, or `set model=`: always, also the same model again, so it @@ -1175,7 +1182,9 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto #endif const bool write = modelChosen || rr == wgchoice::ReadResult::Missing || (rr == wgchoice::ReadResult::Ok && cur.source == wgchoice::Source::Launcher && cur.model != model); - if (write && WriteLauncherModelChoice(ctx, dir, model, notes, warnings)) { + const bool recorded = write && WriteLauncherModelChoice(ctx, dir, model, notes, warnings); + if (write) (recorded ? applied : notApplied).push_back(wstring(L"the model choice (Model ") + wchar_t(model) + L")"); + if (recorded) { forcedEntry = model; #ifdef WRONGGPU_TESTING // tests: the apply ends here, after the record and before OptiScaler.ini (a crash between the two) @@ -1186,8 +1195,16 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto const wstring asi = Join(dir, L"wronggpu-asi.ini"); string text; if (ReadAll(asi, text) && wgasi::ParseSelection(text) == wgasi::kModelAmd) { - const string fresh = wgasi::FormatSelection(model); + // only the selection line changes (the player's comments and every other byte stay); ownership stays as + // recorded: a file whose bytes were WrongGPU's (the record's hash) stays WrongGPU's under its new hash, a + // file the player made or changed stays the player's (the record is not touched for it) + const string fresh = wgasi::WithSelection(text, model); + const wstring was = Sha256Bytes(text.data(), text.size()); WriteFileAtomic(asi, fresh.data(), fresh.size()); + const wstring h = Sha256Bytes(fresh.data(), fresh.size()); + for (auto& e : m.e) + if (e.action == L"copy" && IEq(e.rel, L"wronggpu-asi.ini") && IEq(e.inst, was)) { e.inst = h; recordChanged = true; } + applied.push_back(L"OptiScaler's list back on WrongGPU (wronggpu-asi.ini)"); notes.push_back(L"wronggpu-asi.ini: WrongGPU selected again in OptiScaler's list (the launcher's model choice is newer than AMD's FSR there)"); } } @@ -1196,8 +1213,24 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto if (RecordHasRr(m)) { // Ray Reconstruction (rr.h): into the game's state folder (RR stays off while its data is not ready); // WrongGPU\wronggpu.ini (the install's defaults, the player's to edit) is never rewritten wstring why; - const int w = WriteRrState(ctx, dir, p, RrDataValid(ctx), &why, hadBefore ? &prevMode : nullptr); - if (w < 0) Fail(L"Settings not applied: " + why, EXIT_REFUSED); + int w; +#ifdef WRONGGPU_TESTING + // tests: the RR write fails after the upscaler settings (and the model choice) were written (a partial apply) + if (EnvVar(L"WRONGGPU_TEST_FAIL_RR_STATE") == L"1") { w = -1; why = L"the settings file could not be written (test)"; } else +#endif + w = WriteRrState(ctx, dir, p, RrDataValid(ctx), &why, hadBefore ? &prevMode : nullptr); + if (w < 0) { + notApplied.push_back(L"the Ray Reconstruction settings (" + why + L")"); + if (applied.empty()) Fail(L"Settings not applied: " + why, EXIT_REFUSED); + // the files this apply changed stay known as WrongGPU's (record hashes, owned files); the profile is not saved + if (recordChanged) SaveRecord(RecordPath(dir), m); + WriteOwnedFiles(dir, m); + wstring a, n; + for (auto& x : applied) a += (a.empty() ? L"" : L"; ") + x; + for (auto& x : notApplied) n += (n.empty() ? L"" : L"; ") + x; + LogLine(ctx, L"settings applied in part to " + dir + L": applied: " + a + L"; not applied: " + n); + Fail(L"Settings applied in part. Applied: " + a + L". Not applied: " + n + L". Apply again once that is fixed.", EXIT_REFUSED); + } if (w > 0) notes.push_back(Join(wgstate::kStateFolder, wgstate::kSettingsFile) + L" written (Ray Reconstruction)"); } if (RrConfigGameFor(m.exe)) { // Borderlands 4, Hogwarts Legacy: the game's Engine.ini follows rr_config_fix (rrconfig.h) diff --git a/clean/installer/tests/launcher_partial_apply_cases.py b/clean/installer/tests/launcher_partial_apply_cases.py new file mode 100644 index 00000000..77f52799 --- /dev/null +++ b/clean/installer/tests/launcher_partial_apply_cases.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: MIT +"""A partial apply, for run_launcher_tests.py's RR group, which calls run() in its place with a game that has RR installed +(this file keeps that suite below the 256 KB source limit, as launcher_state_cases.py does). + +The RR write fails (the test seam WRONGGPU_TEST_FAIL_RR_STATE of a WRONGGPU_TESTING build) after the upscaler settings were +saved: the apply is refused, and its message says exactly what was applied (the upscaler settings) and what was not (the RR +settings), never "not applied" for what was. The RR settings stay as they were. The same apply without the fault succeeds. +Written for this project.""" + + +def run(t, exe, b, rr_ini, state_kv): + rr_before, sg_before = rr_ini(b), state_kv(b).get("sparkle_guard") + flip = "off" if sg_before == "on" else "on" + t.env["WRONGGPU_TEST_FAIL_RR_STATE"] = "1" + try: + rc = t.run("set", exe, "sparkle_guard=" + flip, "rr_mode=fast") + finally: + del t.env["WRONGGPU_TEST_FAIL_RR_STATE"] + err = t.j.get("error") or t.j.get("message", "") # (an operation's refusal is its message) + t.check("a partial apply (the RR write fails after the upscaler settings were saved): refused (exit 2); the message lists the " + "upscaler settings as applied and the RR settings as not applied; the RR settings unchanged", + rc == 2 and err.startswith("Settings applied in part.") and "Applied: the upscaler settings" in err and + "Not applied: the Ray Reconstruction settings" in err and "Settings not applied" not in err and + state_kv(b).get("sparkle_guard") == flip and rr_ini(b) == rr_before, (rc, err, rr_ini(b))) + rc = t.run("set", exe, "sparkle_guard=" + (sg_before or "off"), "rr_mode=" + rr_before.get("rr_mode", "accurate")) + t.check("...the same apply without the fault: exit 0", rc == 0, (rc, t.j.get("error"))) diff --git a/clean/installer/tests/run_launcher_tests.py b/clean/installer/tests/run_launcher_tests.py index 129b4b64..cebd7b6c 100644 --- a/clean/installer/tests/run_launcher_tests.py +++ b/clean/installer/tests/run_launcher_tests.py @@ -1181,6 +1181,7 @@ def test_rr(t, opti, synth_f): st = t.j.get("settings", {}) t.check("get: the RR settings, profile and file agree; no outside edits", rc == 0 and st.get("rr_mode", {}).get("profile") == "accurate" and st.get("rr_mode", {}).get("file") == "accurate" and st.get("rr_enabled", {}).get("profile") == "on" and not t.j.get("outside_edits"), (st, t.j.get("outside_edits"))) + __import__("launcher_partial_apply_cases").run(t, exe, b, rr_ini, state_kv) # a partial apply (RR write fails) # rc5 (owner 2026-11-05: Fast is the default): a player's rr_mode=accurate survives Repair and Update, never rewritten rc = t.run("repair", exe, "--opti=" + opti, "--noscan", "--force", "--experimental") rcg = t.run("get", exe) diff --git a/clean/installer/tests/run_model_l_tests.py b/clean/installer/tests/run_model_l_tests.py index b144a876..d9df4fdd 100644 --- a/clean/installer/tests/run_model_l_tests.py +++ b/clean/installer/tests/run_model_l_tests.py @@ -329,6 +329,22 @@ def test_choice(t): rc == 0 and r2c.get("model") == "L" and r2c.get("source") == "launcher" and int(r2c.get("seq", "0")) == newer + 1 and read(wini) == m_w, (rc, r2c)) r2 = r2c + # the menu plugin's file as the player made it, with comments, on AMD (selection=amd): an explicit model choice changes + # only its selection line (every other byte stays) and does not claim it (its ownership stays as recorded) + asi = os.path.join(b, "wronggpu-asi.ini") + had_asi, asi_owner = os.path.exists(asi), recorded_hash(b, "wronggpu-asi.ini") + asi_was = read(asi) if had_asi else None + write(asi, b"# mine: AMD for screenshots\r\n Selection = AMD \r\n; keep this\n") + rc = t.run("set", exe, "model=L") + t.check("set model=L over the player's wronggpu-asi.ini on AMD: only its selection line changes (to Model L), the player's " + "comments and line ends stay, its ownership in the install record unchanged", + rc == 0 and read(asi) == b"# mine: AMD for screenshots\r\nselection=wronggpu-l\r\n; keep this\n" and + recorded_hash(b, "wronggpu-asi.ini") == asi_owner, (rc, read(asi), asi_owner, recorded_hash(b, "wronggpu-asi.ini"))) + if had_asi: + write(asi, asi_was) # (as the install left it) + else: + os.remove(asi) # (the player's file: the uninstall below would rightly keep it) + r2 = choice_record(b) rc = t.run("set", exe, "model=M") t.check("set model=M: wronggpu.ini and OptiScaler.ini back byte for byte as the install wrote them", rc == 0 and read(wini) == m_w and read(oini) == m_o, (rc, read(wini)[-200:], read(oini)[-200:])) diff --git a/clean/wgshared/include/wg_state.h b/clean/wgshared/include/wg_state.h index 31aebd24..8fc60083 100644 --- a/clean/wgshared/include/wg_state.h +++ b/clean/wgshared/include/wg_state.h @@ -674,13 +674,14 @@ inline Settings ParseSettings(const std::string& in) { } return s; } -// The file's text: a new file (nothing read) starts with a comment saying what it is; a read one keeps its BOM and every line -// with its own line end, the changed keys rewritten and new keys at the end. No stamp (UpdateSettings adds it when the file is -// WrongGPU's). -inline std::string RenderSettings(const Settings& s) { +// The file's text: a new file (nothing read) starts with a comment saying what it is (newFileHeader: complete lines; null: +// settings.ini's); a read one keeps its BOM and every line with its own line end, the changed keys rewritten and new keys at +// the end. No stamp (UpdateStateFile adds it when the file is WrongGPU's). +inline std::string RenderSettings(const Settings& s, const char* newFileHeader = nullptr) { std::string out = s.bom ? "\xEF\xBB\xBF" : ""; if (!s.present && s.lines.empty()) { - out += "; WrongGPU: settings chosen in the launcher or in a WrongGPU menu in the game (they take precedence over wronggpu.ini)\r\n"; + out += newFileHeader ? newFileHeader + : "; WrongGPU: settings chosen in the launcher or in a WrongGPU menu in the game (they take precedence over wronggpu.ini)\r\n"; for (const auto& p : s.kv) out += p.first + "=" + p.second + "\r\n"; return out; } @@ -780,7 +781,11 @@ using SettingsDecision = std::function kMaxStateBytes) { o.write.error = ERROR_FILE_TOO_LARGE; return fail(SetResult::WriteFailed, ERROR_FILE_TOO_LARGE); } @@ -868,6 +873,9 @@ inline SetOutcome UpdateSettings(const std::wstring& gameDir, const SettingsDeci o.written = true; return o; } +inline SetOutcome UpdateSettings(const std::wstring& gameDir, const SettingsDecision& decide, DWORD waitMs = kDefaultWaitMs) { + return UpdateStateFile(gameDir, kSettingsFile, decide, waitMs, nullptr); +} // UpdateSettings with fixed changes (a key already at its value is not written again). inline SetOutcome SetSettings(const std::wstring& gameDir, const std::vector>& changes, DWORD waitMs = kDefaultWaitMs) { for (const auto& c : changes)