From e6a4c3e84e585fc8c120131f3a1b8ff86b75f35b Mon Sep 17 00:00:00 2001 From: FakeMichau <49685661+FakeMichau@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:36:19 +0200 Subject: [PATCH] Plugin api Slopped. Ability for plugins to register a tab, use the config file and log. --- OptiScaler/Config.cpp | 41 ++ OptiScaler/Config.h | 6 + OptiScaler/OptiScaler.vcxproj | 3 + OptiScaler/OptiScaler.vcxproj.filters | 12 + OptiScaler/dllmain.cpp | 10 + OptiScaler/menu/menu_common.cpp | 56 ++- OptiScaler/plugins/PluginApi.cpp | 601 +++++++++++++++++++++++++ OptiScaler/plugins/PluginApi.h | 26 ++ plugin_sdk/README.md | 53 +++ plugin_sdk/optiscaler_plugin.h | 154 +++++++ plugin_sdk/sample/.gitignore | 3 + plugin_sdk/sample/SamplePlugin.cpp | 216 +++++++++ plugin_sdk/sample/SamplePlugin.vcxproj | 80 ++++ 13 files changed, 1253 insertions(+), 8 deletions(-) create mode 100644 OptiScaler/plugins/PluginApi.cpp create mode 100644 OptiScaler/plugins/PluginApi.h create mode 100644 plugin_sdk/README.md create mode 100644 plugin_sdk/optiscaler_plugin.h create mode 100644 plugin_sdk/sample/.gitignore create mode 100644 plugin_sdk/sample/SamplePlugin.cpp create mode 100644 plugin_sdk/sample/SamplePlugin.vcxproj diff --git a/OptiScaler/Config.cpp b/OptiScaler/Config.cpp index 5b40cc70..0cfae531 100644 --- a/OptiScaler/Config.cpp +++ b/OptiScaler/Config.cpp @@ -11,6 +11,9 @@ static CSimpleIniA ini; +// Plugins can read and write the ini from their own threads +static std::recursive_mutex iniMutex; + static inline int64_t GetTicks() { LARGE_INTEGER ticks; @@ -47,6 +50,8 @@ Config::Config() bool Config::Reload(std::filesystem::path iniPath) { + std::lock_guard lock(iniMutex); + auto pathWStr = iniPath.wstring(); LOG_INFO("Trying to load ini from: {0}", wstring_to_string(pathWStr)); @@ -1298,6 +1303,8 @@ bool Config::ApplyOverlaySettings(std::string_view text) bool Config::SaveIni() { + std::lock_guard lock(iniMutex); + // Upscalers { auto SaveUpscaler = [&](const char* key, auto& upscalerSetting) @@ -2083,6 +2090,8 @@ bool Config::SaveIni() bool Config::SaveXeFG() { + std::lock_guard lock(iniMutex); + ini.SetValue("XeFG", "DepthInverted", GetBoolValue(Instance()->FGXeFGDepthInverted.value_for_config()).c_str()); ini.SetValue("XeFG", "JitteredMV", GetBoolValue(Instance()->FGXeFGJitteredMV.value_for_config()).c_str()); ini.SetValue("XeFG", "HighResMV", GetBoolValue(Instance()->FGXeFGHighResMV.value_for_config()).c_str()); @@ -2093,6 +2102,38 @@ bool Config::SaveXeFG() return ini.SaveFile(absoluteFileName.wstring().c_str()) >= 0; } +std::optional Config::GetRawValue(const char* section, const char* key) +{ + std::lock_guard lock(iniMutex); + + const char* value = ini.GetValue(section, key, nullptr); + if (value == nullptr) + return std::nullopt; + + return std::string(value); +} + +void Config::SetRawValue(const char* section, const char* key, const char* value) +{ + std::lock_guard lock(iniMutex); + ini.SetValue(section, key, value); +} + +void Config::DeleteRawValue(const char* section, const char* key) +{ + std::lock_guard lock(iniMutex); + ini.Delete(section, key, true); +} + +bool Config::SaveRawValues() +{ + std::lock_guard lock(iniMutex); + + LOG_INFO("Trying to save ini to: {0}", wstring_to_string(absoluteFileName.wstring())); + + return ini.SaveFile(absoluteFileName.wstring().c_str()) >= 0; +} + void Config::CheckUpscalerFiles() { if (!State::Instance().nvngxExists) diff --git a/OptiScaler/Config.h b/OptiScaler/Config.h index 4f7345ee..20dcae9e 100644 --- a/OptiScaler/Config.h +++ b/OptiScaler/Config.h @@ -786,6 +786,12 @@ class Config bool SaveIni(); bool SaveXeFG(); + // Keys that aren't OptiScaler options (plugin settings), kept in the ini as they are + std::optional GetRawValue(const char* section, const char* key); + void SetRawValue(const char* section, const char* key, const char* value); + void DeleteRawValue(const char* section, const char* key); + bool SaveRawValues(); + void CheckUpscalerFiles(); // FG on/off and interpolation count, following the game's DLSSG state when FGEnabled is unset diff --git a/OptiScaler/OptiScaler.vcxproj b/OptiScaler/OptiScaler.vcxproj index e55161a7..3bf45207 100644 --- a/OptiScaler/OptiScaler.vcxproj +++ b/OptiScaler/OptiScaler.vcxproj @@ -509,6 +509,8 @@ copy NUL "$(SolutionDir)x64\Release\a\!! EXTRACT ALL FILES TO GAME FOLDER !!" /Y + + @@ -784,6 +786,7 @@ copy NUL "$(SolutionDir)x64\Release\a\!! EXTRACT ALL FILES TO GAME FOLDER !!" /Y + diff --git a/OptiScaler/OptiScaler.vcxproj.filters b/OptiScaler/OptiScaler.vcxproj.filters index 70320943..ff11fa3c 100644 --- a/OptiScaler/OptiScaler.vcxproj.filters +++ b/OptiScaler/OptiScaler.vcxproj.filters @@ -12,6 +12,9 @@ {0d5515bc-9b5a-4d33-a918-989059c29e08} + + {a3805674-e01c-4786-856f-119e7c376d29} + {eb352600-7864-4906-a7f8-b065f137cc80} @@ -299,6 +302,12 @@ Header Files + + Plugins + + + Plugins + Header Files @@ -1346,6 +1355,9 @@ Source Files + + Plugins + Source Files diff --git a/OptiScaler/dllmain.cpp b/OptiScaler/dllmain.cpp index dd4d433d..99075fc7 100644 --- a/OptiScaler/dllmain.cpp +++ b/OptiScaler/dllmain.cpp @@ -8,6 +8,7 @@ #include "DllNames.h" #include "BuildInfo.h" #include "misc/GameConfigs.h" +#include "plugins/PluginApi.h" #include "proxies/Dxgi_Proxy.h" #include "proxies/Kernel32_Proxy.h" @@ -289,6 +290,10 @@ void LoadAsiPlugins() if (init != nullptr) init(); + PluginApi::InitPlugin( + hMod, (PFN_OptiPluginInit) KernelBaseProxy::GetProcAddress_()(hMod, OPTI_PLUGIN_INIT_NAME), + entry.path()); + if (patchResult != nullptr) { auto pr = patchResult(); @@ -352,6 +357,11 @@ void LoadAsiPlugins() if (init != nullptr) init(); + PluginApi::InitPlugin(hMod, + (PFN_OptiPluginInit) KernelBaseProxy::GetProcAddress_()( + hMod, OPTI_PLUGIN_INIT_NAME), + entry.path()); + if (patchResult != nullptr) { auto pr = patchResult(); diff --git a/OptiScaler/menu/menu_common.cpp b/OptiScaler/menu/menu_common.cpp index d4e5bd42..23103651 100644 --- a/OptiScaler/menu/menu_common.cpp +++ b/OptiScaler/menu/menu_common.cpp @@ -42,6 +42,7 @@ #include #include #include +#include #include #include @@ -9705,8 +9706,15 @@ void MenuCommon::RenderMainMenuTabs(RenderMenuContext& ctx) constexpr int customTab = 0; const bool customTabEnabled = config->CustomTabEnabled.value_or_default(); + // Tabs registered by plugins come after the built-in ones + constexpr int builtinTabCount = (int) std::size(tabs); + const auto pluginTabs = PluginApi::GetTabs(); + const int tabCount = builtinTabCount + (int) pluginTabs.size(); + auto isTabVisible = [&](int i) { + if (i >= builtinTabCount) + return true; if (i == customTab) return customTabEnabled; return tabs[i].visible == nullptr || tabs[i].visible(ctx); @@ -9723,12 +9731,12 @@ void MenuCommon::RenderMainMenuTabs(RenderMenuContext& ctx) requestedMenuTab = nullptr; } - selectedMenuTab = std::clamp(selectedMenuTab, 0, (int) std::size(tabs) - 1); + selectedMenuTab = std::clamp(selectedMenuTab, 0, tabCount - 1); // Selected tab can disappear, pick the first one that's visible if (!isTabVisible(selectedMenuTab)) { - for (int i = 0; i < (int) std::size(tabs); i++) + for (int i = 0; i < builtinTabCount; i++) { if (isTabVisible(i)) { @@ -9752,15 +9760,18 @@ void MenuCommon::RenderMainMenuTabs(RenderMenuContext& ctx) { const char* lastGroup = nullptr; - for (int i = 0; i < (int) std::size(tabs); i++) + for (int i = 0; i < tabCount; i++) { if (!isTabVisible(i)) continue; - if (lastGroup != nullptr && strcmp(lastGroup, tabs[i].group) != 0) + const bool pluginTab = i >= builtinTabCount; + const char* group = pluginTab ? "PLUGINS" : tabs[i].group; + + if (lastGroup != nullptr && strcmp(lastGroup, group) != 0) ImGui::Separator(); - lastGroup = tabs[i].group; + lastGroup = group; const bool selected = selectedMenuTab == i; @@ -9769,13 +9780,30 @@ void MenuCommon::RenderMainMenuTabs(RenderMenuContext& ctx) selectedMenuTab = i; ImGui::PopID(); + // Description comes from the plugin, so it isn't used as a format string + if (pluginTab && !pluginTabs[i - builtinTabCount].description.empty() && + ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + { + ImGui::BeginTooltip(); + ImGui::TextUnformatted(pluginTabs[i - builtinTabCount].description.c_str()); + ImGui::EndTooltip(); + } + // Label is drawn manually to center it vertically const ImVec2 rectMin = ImGui::GetItemRectMin(); + const ImVec2 rectMax = ImGui::GetItemRectMax(); + auto drawList = ImGui::GetWindowDrawList(); - ImGui::GetWindowDrawList()->AddText( + const char* label = pluginTab ? pluginTabs[i - builtinTabCount].name.c_str() + : tabs[i].displayLabel != nullptr ? tabs[i].displayLabel(ctx) + : tabs[i].label; + + // Long plugin names are cut at the edge of the sidebar + drawList->PushClipRect(rectMin, rectMax, true); + drawList->AddText( ImVec2(rectMin.x + 6.0f * menuResScale, rectMin.y + (tabHeight - ImGui::GetTextLineHeight()) * 0.5f), - ImGui::GetColorU32(ImGuiCol_Text), - tabs[i].displayLabel != nullptr ? tabs[i].displayLabel(ctx) : tabs[i].label); + ImGui::GetColorU32(ImGuiCol_Text), label); + drawList->PopClipRect(); } // OptiPatcher status only visible when used @@ -9871,6 +9899,18 @@ void MenuCommon::RenderMainMenuTabs(RenderMenuContext& ctx) // Scrollable content of the tab ----------------------------- ImGui::BeginChild("##MenuContent", ImVec2(0.0f, -footerHeight), ImGuiChildFlags_NavFlattened, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); + if (selectedMenuTab >= builtinTabCount) + { + // Own ID per tab, so every tab remembers its scroll position + ImGui::PushID(selectedMenuTab); + ImGui::BeginChild("##MenuTabBody", ImVec2(0.0f, 0.0f)); + + PluginApi::DrawTab(selectedMenuTab - builtinTabCount, menuResScale, toneMapColor); + + ImGui::EndChild(); + ImGui::PopID(); + } + else { const Tab& tab = tabs[selectedMenuTab]; diff --git a/OptiScaler/plugins/PluginApi.cpp b/OptiScaler/plugins/PluginApi.cpp new file mode 100644 index 00000000..4cc36a00 --- /dev/null +++ b/OptiScaler/plugins/PluginApi.cpp @@ -0,0 +1,601 @@ +#include "pch.h" + +#include "PluginApi.h" + +#include "Config.h" +#include "menu/menu_common.h" + +#include + +#include + +struct OptiPlugin +{ + std::string name; + std::string section; // Plugin. in OptiScaler.ini +}; + +namespace +{ +struct PluginTab +{ + OptiPlugin* plugin; + std::string name; + std::string description; + OptiDrawTabFn draw; + void* userData; + bool faulted = false; +}; + +// Plugins live as long as the process, the API keeps pointers to them +std::vector> _plugins; +std::vector _initedModules; +std::vector> _tabs; +std::mutex _mutex; + +// State of the draw callback that is running, widgets do nothing without it +struct TabDrawState +{ + std::optional card; + bool disabled = false; + ImVec4 (*colorMap)(const ImVec4&) = nullptr; +}; + +thread_local TabDrawState* _draw = nullptr; +float _menuScale = 1.0f; + +// Plugin code is called through these, a crash in it disables the plugin instead of the game +bool CallDraw(OptiDrawTabFn draw, void* userData) +{ + __try + { + draw(userData); + return true; + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + return false; + } +} + +bool CallInit(PFN_OptiPluginInit init, const OptiPluginApi* api, OptiPlugin* plugin, bool* result) +{ + __try + { + *result = init(api, plugin); + return true; + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + return false; + } +} + +void ShowItemTooltip(const char* text) +{ + if (text == nullptr || !ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + return; + + ImGui::BeginTooltip(); + ImGui::TextUnformatted(text); + ImGui::EndTooltip(); +} + +void WrappedText(const char* text, const ImVec4* color) +{ + if (color != nullptr) + ImGui::PushStyleColor(ImGuiCol_Text, _draw->colorMap != nullptr ? _draw->colorMap(*color) : *color); + + ImGui::TextWrapped("%s", text); + + if (color != nullptr) + ImGui::PopStyleColor(); +} + +// Copies at most bufferSize - 1 bytes without cutting a UTF-8 character in half +void CopyUtf8(const std::string& value, char* buffer, size_t bufferSize) +{ + if (buffer == nullptr || bufferSize == 0) + return; + + size_t length = std::min(value.size(), bufferSize - 1); + + // Continuation bytes are 10xxxxxx + if (length < value.size()) + { + while (length > 0 && (static_cast(value[length]) & 0xC0) == 0x80) + length--; + } + + memcpy(buffer, value.data(), length); + buffer[length] = '\0'; +} + +// "auto" is treated as a missing value, like for OptiScaler options +std::optional ReadValue(OptiPlugin* plugin, const char* key) +{ + if (plugin == nullptr || key == nullptr) + return std::nullopt; + + auto value = Config::Instance()->GetRawValue(plugin->section.c_str(), key); + if (!value.has_value()) + return std::nullopt; + + std::string lower = *value; + std::ranges::transform(lower, lower.begin(), [](unsigned char c) { return (char) std::tolower(c); }); + + if (lower == "auto") + return std::nullopt; + + return value; +} + +template std::optional ParseNumber(const std::string& text) +{ + T value {}; + const char* end = text.data() + text.size(); + auto [ptr, ec] = std::from_chars(text.data(), end, value); + + if (ec != std::errc() || ptr != end) + return std::nullopt; + + return value; +} + +void WriteValue(OptiPlugin* plugin, const char* key, const std::string& value) +{ + if (plugin == nullptr || key == nullptr) + return; + + Config::Instance()->SetRawValue(plugin->section.c_str(), key, value.c_str()); +} + +// API functions ----------------------------- + +bool Api_RegisterTab(OptiPlugin* plugin, const char* name, const char* description, OptiDrawTabFn draw, void* userData) +{ + if (plugin == nullptr || name == nullptr || name[0] == '\0' || draw == nullptr) + return false; + + auto tab = std::make_shared(); + tab->plugin = plugin; + tab->name = name; + tab->description = description != nullptr ? description : ""; + tab->draw = draw; + tab->userData = userData; + + std::lock_guard lock(_mutex); + _tabs.push_back(std::move(tab)); + + LOG_INFO("[{}] Registered tab: {}", plugin->name, name); + + return true; +} + +void Api_Section(const char* title) +{ + if (_draw == nullptr) + return; + + _draw->card.reset(); + _draw->card.emplace(title); +} + +void Api_Separator() +{ + if (_draw != nullptr) + ImGui::Separator(); +} + +void Api_SameLine() +{ + if (_draw != nullptr) + ImGui::SameLine(); +} + +void Api_Spacing() +{ + if (_draw != nullptr) + ImGui::Spacing(); +} + +void Api_Disabled(bool disabled) +{ + if (_draw == nullptr || _draw->disabled == disabled) + return; + + if (disabled) + ImGui::BeginDisabled(); + else + ImGui::EndDisabled(); + + _draw->disabled = disabled; +} + +void Api_ItemTooltip(const char* text) +{ + if (_draw != nullptr) + ShowItemTooltip(text); +} + +void Api_Text(const char* text) +{ + if (_draw != nullptr && text != nullptr) + WrappedText(text, nullptr); +} + +void Api_TextDisabled(const char* text) +{ + if (_draw == nullptr || text == nullptr) + return; + + // Disabled color isn't tone mapped by the menu either + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled)); + ImGui::TextWrapped("%s", text); + ImGui::PopStyleColor(); +} + +void Api_TextColored(float r, float g, float b, float a, const char* text) +{ + if (_draw == nullptr || text == nullptr) + return; + + const ImVec4 color(r, g, b, a); + WrappedText(text, &color); +} + +bool Api_Button(const char* label) { return _draw != nullptr && label != nullptr && ImGui::Button(label); } + +bool Api_Checkbox(const char* label, bool* value) +{ + return _draw != nullptr && label != nullptr && value != nullptr && ImGui::Checkbox(label, value); +} + +bool Api_SliderFloat(const char* label, float* value, float min, float max, const char* format) +{ + if (_draw == nullptr || label == nullptr || value == nullptr) + return false; + + return ImGui::SliderFloat(label, value, min, max, format != nullptr ? format : "%.3f", + ImGuiSliderFlags_AlwaysClamp); +} + +bool Api_SliderInt(const char* label, int32_t* value, int32_t min, int32_t max, const char* format) +{ + if (_draw == nullptr || label == nullptr || value == nullptr) + return false; + + return ImGui::SliderInt(label, value, min, max, format != nullptr ? format : "%d", ImGuiSliderFlags_AlwaysClamp); +} + +bool Api_Combo(const char* label, int32_t* current, const char* const* items, int32_t itemCount) +{ + if (_draw == nullptr || label == nullptr || current == nullptr || (items == nullptr && itemCount > 0)) + return false; + + const bool validIndex = *current >= 0 && *current < itemCount && items[*current] != nullptr; + const char* preview = validIndex ? items[*current] : ""; + bool changed = false; + + if (ImGui::BeginCombo(label, preview)) + { + for (int32_t i = 0; i < itemCount; i++) + { + ImGui::PushID(i); + + const bool selected = *current == i; + if (ImGui::Selectable(items[i] != nullptr ? items[i] : "", selected) && !selected) + { + *current = i; + changed = true; + } + + if (selected) + ImGui::SetItemDefaultFocus(); + + ImGui::PopID(); + } + + ImGui::EndCombo(); + } + + return changed; +} + +bool Api_InputText(const char* label, char* buffer, size_t bufferSize) +{ + if (_draw == nullptr || label == nullptr || buffer == nullptr || bufferSize == 0) + return false; + + return ImGui::InputText(label, buffer, bufferSize); +} + +bool Api_ColorEdit(const char* label, float* rgba, bool withAlpha) +{ + if (_draw == nullptr || label == nullptr || rgba == nullptr) + return false; + + return withAlpha ? ImGui::ColorEdit4(label, rgba) : ImGui::ColorEdit3(label, rgba); +} + +float Api_GetMenuScale() { return _menuScale; } + +bool Api_IsMenuOpen() { return MenuCommon::IsVisible(); } + +bool Api_GetBool(OptiPlugin* plugin, const char* key, bool defaultValue) +{ + auto value = ReadValue(plugin, key); + if (!value.has_value()) + return defaultValue; + + std::string lower = *value; + std::ranges::transform(lower, lower.begin(), [](unsigned char c) { return (char) std::tolower(c); }); + + if (lower == "true" || lower == "1") + return true; + + if (lower == "false" || lower == "0") + return false; + + return defaultValue; +} + +int32_t Api_GetInt(OptiPlugin* plugin, const char* key, int32_t defaultValue) +{ + auto value = ReadValue(plugin, key); + if (!value.has_value()) + return defaultValue; + + return ParseNumber(*value).value_or(defaultValue); +} + +float Api_GetFloat(OptiPlugin* plugin, const char* key, float defaultValue) +{ + auto value = ReadValue(plugin, key); + if (!value.has_value()) + return defaultValue; + + return ParseNumber(*value).value_or(defaultValue); +} + +bool Api_GetString(OptiPlugin* plugin, const char* key, char* buffer, size_t bufferSize, const char* defaultValue) +{ + auto value = ReadValue(plugin, key); + + if (!value.has_value()) + { + CopyUtf8(defaultValue != nullptr ? defaultValue : "", buffer, bufferSize); + return false; + } + + CopyUtf8(*value, buffer, bufferSize); + return true; +} + +void Api_SetBool(OptiPlugin* plugin, const char* key, bool value) { WriteValue(plugin, key, value ? "true" : "false"); } + +void Api_SetInt(OptiPlugin* plugin, const char* key, int32_t value) { WriteValue(plugin, key, std::to_string(value)); } + +// Shortest text that reads back as the same float +void Api_SetFloat(OptiPlugin* plugin, const char* key, float value) +{ + WriteValue(plugin, key, std::format("{}", value)); +} + +void Api_SetString(OptiPlugin* plugin, const char* key, const char* value) +{ + WriteValue(plugin, key, value != nullptr ? value : ""); +} + +void Api_ResetValue(OptiPlugin* plugin, const char* key) +{ + if (plugin != nullptr && key != nullptr) + Config::Instance()->DeleteRawValue(plugin->section.c_str(), key); +} + +bool Api_SaveSettings(OptiPlugin* plugin) +{ + if (plugin == nullptr) + return false; + + return Config::Instance()->SaveRawValues(); +} + +void Api_Log(OptiPlugin* plugin, OptiLogLevel level, const char* message) +{ + if (plugin == nullptr || message == nullptr) + return; + + switch (level) + { + case OptiLog_Debug: + LOG_DEBUG("[{}] {}", plugin->name, message); + break; + case OptiLog_Warn: + LOG_WARN("[{}] {}", plugin->name, message); + break; + case OptiLog_Error: + LOG_ERROR("[{}] {}", plugin->name, message); + break; + default: + LOG_INFO("[{}] {}", plugin->name, message); + break; + } +} + +const OptiPluginApi _api = { + .size = sizeof(OptiPluginApi), + .version = OPTI_PLUGIN_API_VERSION, + + .RegisterTab = Api_RegisterTab, + + .Section = Api_Section, + .Separator = Api_Separator, + .SameLine = Api_SameLine, + .Spacing = Api_Spacing, + .Disabled = Api_Disabled, + .ItemTooltip = Api_ItemTooltip, + + .Text = Api_Text, + .TextDisabled = Api_TextDisabled, + .TextColored = Api_TextColored, + + .Button = Api_Button, + .Checkbox = Api_Checkbox, + .SliderFloat = Api_SliderFloat, + .SliderInt = Api_SliderInt, + .Combo = Api_Combo, + .InputText = Api_InputText, + .ColorEdit = Api_ColorEdit, + + .GetMenuScale = Api_GetMenuScale, + .IsMenuOpen = Api_IsMenuOpen, + + .GetBool = Api_GetBool, + .GetInt = Api_GetInt, + .GetFloat = Api_GetFloat, + .GetString = Api_GetString, + .SetBool = Api_SetBool, + .SetInt = Api_SetInt, + .SetFloat = Api_SetFloat, + .SetString = Api_SetString, + .ResetValue = Api_ResetValue, + .SaveSettings = Api_SaveSettings, + + .Log = Api_Log, +}; +} // namespace + +void PluginApi::InitPlugin(HMODULE module, PFN_OptiPluginInit init, const std::filesystem::path& path) +{ + if (module == nullptr || init == nullptr) + return; + + OptiPlugin* plugin = nullptr; + + { + std::lock_guard lock(_mutex); + + // Late loaded plugins can be reported more than once + if (std::ranges::find(_initedModules, module) != _initedModules.end()) + return; + + _initedModules.push_back(module); + + // Name shouldn't change when the plugin is switched to late loading + std::string name = wstring_to_string(path.stem().wstring()); + constexpr std::string_view lateSuffix = "-loadlate"; + + if (name.size() > lateSuffix.size()) + { + std::string tail = name.substr(name.size() - lateSuffix.size()); + std::ranges::transform(tail, tail.begin(), [](unsigned char c) { return (char) std::tolower(c); }); + + if (tail == lateSuffix) + name.resize(name.size() - lateSuffix.size()); + } + + auto& created = _plugins.emplace_back(std::make_unique()); + created->name = name; + created->section = "Plugin." + name; + plugin = created.get(); + } + + LOG_INFO("Initializing plugin API for {}", plugin->name); + + bool accepted = false; + const bool finished = CallInit(init, &_api, plugin, &accepted); + + if (finished && accepted) + return; + + if (!finished) + LOG_ERROR("[{}] Crashed in OptiPluginInit, its tabs are removed", plugin->name); + else + LOG_INFO("[{}] Declined the plugin API", plugin->name); + + std::lock_guard lock(_mutex); + std::erase_if(_tabs, [plugin](const auto& tab) { return tab->plugin == plugin; }); +} + +std::vector PluginApi::GetTabs() +{ + std::lock_guard lock(_mutex); + + std::vector tabs; + tabs.reserve(_tabs.size()); + + for (const auto& tab : _tabs) + tabs.push_back({ tab->name, tab->description }); + + return tabs; +} + +void PluginApi::DrawTab(size_t index, float menuScale, ImVec4 (*colorMap)(const ImVec4&)) +{ + std::shared_ptr tab; + + { + std::lock_guard lock(_mutex); + if (index >= _tabs.size()) + return; + + tab = _tabs[index]; + } + + _menuScale = menuScale; + + if (tab->faulted) + { + ImGui::TextColored(colorMap(ImVec4(1.0f, 0.4f, 0.4f, 1.0f)), "%s", + "This plugin crashed while drawing its tab and was disabled.\nCheck the log for details."); + return; + } + + // Lock isn't held while the plugin runs, it can register more tabs from here + TabDrawState state; + state.colorMap = colorMap; + + ImGuiErrorRecoveryState recovery; + ImGui::ErrorRecoveryStoreState(&recovery); + + ImGui::PushID(tab->plugin->name.c_str()); + ImGui::PushID(tab->name.c_str()); + ImGui::PushItemWidth(220.0f * menuScale); + + _draw = &state; + const bool finished = CallDraw(tab->draw, tab->userData); + _draw = nullptr; + + if (!finished) + { + LOG_ERROR("[{}] Crashed while drawing tab {}, disabling it", tab->plugin->name, tab->name); + tab->faulted = true; + + // Closes whatever was left open when the plugin crashed, popups of a combo for example. + // Also pops the IDs and the disabled state from above, but not the item width. + auto& io = ImGui::GetIO(); + const bool enableAssert = io.ConfigErrorRecoveryEnableAssert; + const bool enableTooltip = io.ConfigErrorRecoveryEnableTooltip; + io.ConfigErrorRecoveryEnableAssert = false; + io.ConfigErrorRecoveryEnableTooltip = false; + + ImGui::ErrorRecoveryTryToRecoverState(&recovery); + + io.ConfigErrorRecoveryEnableAssert = enableAssert; + io.ConfigErrorRecoveryEnableTooltip = enableTooltip; + + ImGui::PopItemWidth(); + state.card.reset(); + return; + } + + if (state.disabled) + ImGui::EndDisabled(); + + state.card.reset(); + + ImGui::PopItemWidth(); + ImGui::PopID(); + ImGui::PopID(); +} diff --git a/OptiScaler/plugins/PluginApi.h b/OptiScaler/plugins/PluginApi.h new file mode 100644 index 00000000..f1ce661e --- /dev/null +++ b/OptiScaler/plugins/PluginApi.h @@ -0,0 +1,26 @@ +#pragma once + +#include "SysUtils.h" + +#include "../../plugin_sdk/optiscaler_plugin.h" + +#include + +// OptiScaler side of plugin_sdk/optiscaler_plugin.h +class PluginApi +{ + public: + struct TabInfo + { + std::string name; + std::string description; + }; + + // Calls OptiPluginInit of a loaded ASI plugin, once per module + static void InitPlugin(HMODULE module, PFN_OptiPluginInit init, const std::filesystem::path& path); + + static std::vector GetTabs(); + + // Draws a registered tab inside of the menu, colorMap adjusts colors for the HDR menu + static void DrawTab(size_t index, float menuScale, ImVec4 (*colorMap)(const ImVec4&)); +}; diff --git a/plugin_sdk/README.md b/plugin_sdk/README.md new file mode 100644 index 00000000..576989e9 --- /dev/null +++ b/plugin_sdk/README.md @@ -0,0 +1,53 @@ +# OptiScaler plugin SDK + +ASI plugins loaded by OptiScaler can add their own tabs to the OptiScaler menu and keep their settings in `OptiScaler.ini`. + +- The API is a plain C function table defined in [`optiscaler_plugin.h`](optiscaler_plugin.h). This header is all you need: you don't link against OptiScaler or ImGui. +- Plugins don't have to be rebuilt for newer OptiScaler versions. Fields are only ever appended to `OptiPluginApi`, so before you use a field added after version 1, check it with `OPTI_API_HAS(api, Field)`. + +## Getting started + +1. Export `OptiPluginInit` from your plugin: + + ```cpp + extern "C" __declspec(dllexport) bool OptiPluginInit(const OptiPluginApi* api, OptiPlugin* plugin) + { + api->RegisterTab(plugin, "My Plugin", "Tooltip in the sidebar", DrawTab, nullptr); + return true; + } + ``` + + OptiScaler calls it once, right after `InitializeASI`. Return `false` to opt out; any tabs you registered are then removed. +2. Put the `.asi` file in the `plugins` folder and set `LoadAsiPlugins=true` in `OptiScaler.ini`. +3. Your tabs appear under **PLUGINS** in the menu sidebar. + +## Drawing + +Inside a draw callback you can use `Section`, `Text`, `Checkbox`, `SliderFloat`/`SliderInt`, `Combo`, `InputText`, `ColorEdit`, `Button`, `SameLine`, `Disabled` and `ItemTooltip`. + +- `Section` starts a card like the ones in OptiScaler's own tabs. +- Cards, disabled blocks and IDs are closed by OptiScaler after the callback, so a plugin can't leave ImGui in a broken state. +- Widget functions do nothing when called outside a draw callback or from another thread. +- Draw callbacks run on the render thread while the menu is open. Keep them fast, don't call D3D/Vulkan from them, and protect any data you share with your own threads. +- If a callback crashes, OptiScaler disables that tab and logs it, instead of crashing the game. + +## Settings + +Settings are stored in the `[Plugin.]` section of `OptiScaler.ini`, where `` is the plugin file name without the extension and without a `-loadlate` suffix. + +- `Get*` returns the default when the key is missing or set to `auto`. +- `Set*` only changes the value in memory. `SaveSettings`, or **Save INI** in the menu, writes the file. +- `ResetValue` removes the key. + +## Sample + +[`sample/`](sample) contains a plugin that uses every function of the API. + +To build it: + +1. Install Visual Studio 2022 or newer with the **Desktop development with C++** workload. The free Community edition is enough. +2. Open `sample/SamplePlugin.vcxproj` in Visual Studio (File → Open → Project/Solution). +3. Select the `Release` configuration and the `x64` platform in the toolbar. +4. Build → Build Solution. + +The plugin is written to `sample/bin/Release/SamplePlugin.asi`. Copy it to the `plugins` folder next to OptiScaler and set `LoadAsiPlugins=true` in `OptiScaler.ini`. diff --git a/plugin_sdk/optiscaler_plugin.h b/plugin_sdk/optiscaler_plugin.h new file mode 100644 index 00000000..f46b3a1a --- /dev/null +++ b/plugin_sdk/optiscaler_plugin.h @@ -0,0 +1,154 @@ +/* + * OptiScaler plugin API + * + * Lets an ASI plugin loaded by OptiScaler (plugins folder, LoadAsiPlugins=true) add its own tabs to the + * OptiScaler menu and keep its settings in OptiScaler.ini. + * + * The API is plain C and does not depend on the ImGui version used by OptiScaler, so a plugin built against + * this header keeps working with newer OptiScaler builds. No OptiScaler library or ImGui is linked. + * + * Usage: + * Export OptiPluginInit from the plugin. OptiScaler calls it once, right after InitializeASI (if present). + * Keep the api pointer, it stays valid for the lifetime of the process. + * + * Compatibility rules: + * - Fields are only ever appended to OptiPluginApi, never removed or reordered. + * - api->size is sizeof(OptiPluginApi) of the running OptiScaler. Before using a field added after + * version 1, check it with OPTI_API_HAS(api, Field). + * + * Strings are UTF-8 and copied by OptiScaler when it has to keep them. + * + * Threading: + * - Widget functions only work inside a tab draw callback, which runs on the render thread while the menu + * is open. Outside of it they do nothing and return false. + * - Draw callbacks have to be quick and must not call into D3D/Vulkan or present. + * - Registration, settings and logging functions can be called from any thread. + * + * Settings: + * Stored in OptiScaler.ini, in the [Plugin.] section. is the plugin file name without the + * extension and without a "-loadlate" suffix. A missing key or the value "auto" returns the default. + * Set* only changes the value in memory, SaveSettings (or Save INI in the menu) writes the file. + */ + +#ifndef OPTISCALER_PLUGIN_H +#define OPTISCALER_PLUGIN_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + +#define OPTI_PLUGIN_API_VERSION 1 + + // Handle of the calling plugin, given to OptiPluginInit + typedef struct OptiPlugin OptiPlugin; + + // Called every frame while the tab is selected and the menu is open + typedef void (*OptiDrawTabFn)(void* userData); + + typedef enum OptiLogLevel + { + OptiLog_Debug = 0, + OptiLog_Info = 1, + OptiLog_Warn = 2, + OptiLog_Error = 3, + } OptiLogLevel; + + typedef struct OptiPluginApi + { + uint32_t size; // sizeof(OptiPluginApi) of the running OptiScaler + uint32_t version; // OPTI_PLUGIN_API_VERSION of the running OptiScaler + + // Registration ------------------------------------------------------------------------------------- + + // Adds a tab under the PLUGINS group of the menu sidebar. A plugin can register several tabs. + // description is shown as the sidebar tooltip and can be NULL. + bool (*RegisterTab)(OptiPlugin* plugin, const char* name, const char* description, OptiDrawTabFn draw, + void* userData); + + // Layout, only inside a draw callback --------------------------------------------------------------- + + // Starts a new card with a title, the previous one is closed. Cards are closed after the callback. + void (*Section)(const char* title); + void (*Separator)(void); + // Places the next widget on the same line as the previous one + void (*SameLine)(void); + void (*Spacing)(void); + // Widgets after Disabled(true) can't be interacted with, until Disabled(false) or the end of the callback + void (*Disabled)(bool disabled); + // Shows a tooltip when the previous widget is hovered + void (*ItemTooltip)(const char* text); + + // Text, only inside a draw callback ----------------------------------------------------------------- + + void (*Text)(const char* text); + void (*TextDisabled)(const char* text); + // r, g, b, a in 0.0 - 1.0 + void (*TextColored)(float r, float g, float b, float a, const char* text); + + // Widgets, only inside a draw callback -------------------------------------------------------------- + // Labels have to be unique inside a tab. Text after "##" is not shown, "Scale##2" is drawn as "Scale". + // format is printf-like for the value shown on the slider, NULL for the default. + + bool (*Button)(const char* label); // true when clicked + bool (*Checkbox)(const char* label, bool* value); // true when changed + bool (*SliderFloat)(const char* label, float* value, float min, float max, const char* format); + bool (*SliderInt)(const char* label, int32_t* value, int32_t min, int32_t max, const char* format); + // items is an array of itemCount strings, current is the selected index + bool (*Combo)(const char* label, int32_t* current, const char* const* items, int32_t itemCount); + // buffer is a zero terminated UTF-8 string that is edited in place + bool (*InputText)(const char* label, char* buffer, size_t bufferSize); + // rgba is float[4] in 0.0 - 1.0 + bool (*ColorEdit)(const char* label, float* rgba, bool withAlpha); + + // Menu state ---------------------------------------------------------------------------------------- + + // UI scale of the menu, multiply custom sizes by it + float (*GetMenuScale)(void); + bool (*IsMenuOpen)(void); + + // Settings in [Plugin.] of OptiScaler.ini --------------------------------------------------- + + bool (*GetBool)(OptiPlugin* plugin, const char* key, bool defaultValue); + int32_t (*GetInt)(OptiPlugin* plugin, const char* key, int32_t defaultValue); + float (*GetFloat)(OptiPlugin* plugin, const char* key, float defaultValue); + // Copies the value to buffer (always zero terminated, truncated if needed). + // Returns false and copies defaultValue when the key is missing. + bool (*GetString)(OptiPlugin* plugin, const char* key, char* buffer, size_t bufferSize, + const char* defaultValue); + + void (*SetBool)(OptiPlugin* plugin, const char* key, bool value); + void (*SetInt)(OptiPlugin* plugin, const char* key, int32_t value); + void (*SetFloat)(OptiPlugin* plugin, const char* key, float value); + void (*SetString)(OptiPlugin* plugin, const char* key, const char* value); + // Removes the key, Get* returns the default afterwards + void (*ResetValue)(OptiPlugin* plugin, const char* key); + + // Writes OptiScaler.ini to the disk + bool (*SaveSettings)(OptiPlugin* plugin); + + // Misc ------------------------------------------------------------------------------------------------ + + // Writes to the OptiScaler log, prefixed with the plugin name + void (*Log)(OptiPlugin* plugin, OptiLogLevel level, const char* message); + + } OptiPluginApi; + +// True when the running OptiScaler has the given field of OptiPluginApi +#define OPTI_API_HAS(api, field) \ + ((api) != NULL && (api)->size >= offsetof(OptiPluginApi, field) + sizeof((api)->field) && (api)->field != NULL) + + // Exported by the plugin. Return false to not use the API (nothing registered is kept). + typedef bool (*PFN_OptiPluginInit)(const OptiPluginApi* api, OptiPlugin* plugin); + +#define OPTI_PLUGIN_INIT_NAME "OptiPluginInit" + +#ifdef __cplusplus +} +#endif + +#endif // OPTISCALER_PLUGIN_H diff --git a/plugin_sdk/sample/.gitignore b/plugin_sdk/sample/.gitignore new file mode 100644 index 00000000..f1ba482d --- /dev/null +++ b/plugin_sdk/sample/.gitignore @@ -0,0 +1,3 @@ +bin/ +obj/ +*.vcxproj.user diff --git a/plugin_sdk/sample/SamplePlugin.cpp b/plugin_sdk/sample/SamplePlugin.cpp new file mode 100644 index 00000000..a039d1d2 --- /dev/null +++ b/plugin_sdk/sample/SamplePlugin.cpp @@ -0,0 +1,216 @@ +// Sample OptiScaler plugin, uses every part of plugin_sdk/optiscaler_plugin.h +// +// Open SamplePlugin.vcxproj in Visual Studio, select Release | x64 and build it. Copy +// bin/Release/SamplePlugin.asi to the plugins folder next to OptiScaler and set LoadAsiPlugins=true +// in OptiScaler.ini. Two tabs show up under PLUGINS in the menu and +// the settings are kept in the [Plugin.SamplePlugin] section of OptiScaler.ini. + +#include + +#include + +#include "../optiscaler_plugin.h" + +namespace +{ +const OptiPluginApi* api = nullptr; +OptiPlugin* self = nullptr; + +const char* const qualityNames[] = { "Low", "Medium", "High", "Ultra" }; +constexpr int32_t qualityCount = sizeof(qualityNames) / sizeof(qualityNames[0]); + +struct Settings +{ + bool enabled = true; + float strength = 0.5f; + int32_t samples = 4; + int32_t quality = 2; + char label[64] = "Hello from the sample plugin"; + float tint[4] = { 0.3f, 0.7f, 1.0f, 1.0f }; +}; + +Settings settings; +bool unsaved = false; +int32_t clickCount = 0; + +void LoadSettings() +{ + const Settings defaults; + + settings.enabled = api->GetBool(self, "Enabled", defaults.enabled); + settings.strength = api->GetFloat(self, "Strength", defaults.strength); + settings.samples = api->GetInt(self, "Samples", defaults.samples); + settings.quality = api->GetInt(self, "Quality", defaults.quality); + api->GetString(self, "Label", settings.label, sizeof(settings.label), defaults.label); + + // Colors don't have their own type, they are kept as separate floats + const char* channelKeys[] = { "TintR", "TintG", "TintB", "TintA" }; + for (int i = 0; i < 4; i++) + settings.tint[i] = api->GetFloat(self, channelKeys[i], defaults.tint[i]); + + unsaved = false; +} + +void StoreTint() +{ + const char* channelKeys[] = { "TintR", "TintG", "TintB", "TintA" }; + for (int i = 0; i < 4; i++) + api->SetFloat(self, channelKeys[i], settings.tint[i]); +} + +void ResetSettings() +{ + const char* keys[] = { "Enabled", "Strength", "Samples", "Quality", "Label", "TintR", "TintG", "TintB", "TintA" }; + for (const char* key : keys) + api->ResetValue(self, key); + + LoadSettings(); + unsaved = true; +} + +void DrawMainTab(void* /*userData*/) +{ + api->Section("General"); + + // Set* only changes the value in memory, Save writes the file + if (api->Checkbox("Enabled", &settings.enabled)) + { + api->SetBool(self, "Enabled", settings.enabled); + unsaved = true; + } + api->ItemTooltip("Turns the whole effect on or off"); + + // Everything below can't be used while the effect is off + api->Disabled(!settings.enabled); + + if (api->SliderFloat("Strength", &settings.strength, 0.0f, 1.0f, "%.2f")) + { + api->SetFloat(self, "Strength", settings.strength); + unsaved = true; + } + api->ItemTooltip("0.0 - no effect\n1.0 - full effect"); + + if (api->SliderInt("Samples", &settings.samples, 1, 16, nullptr)) + { + api->SetInt(self, "Samples", settings.samples); + unsaved = true; + } + + if (api->Combo("Quality", &settings.quality, qualityNames, qualityCount)) + { + api->SetInt(self, "Quality", settings.quality); + unsaved = true; + } + + api->Section("Appearance"); + + if (api->InputText("Label", settings.label, sizeof(settings.label))) + { + api->SetString(self, "Label", settings.label); + unsaved = true; + } + + if (api->ColorEdit("Tint", settings.tint, true)) + { + StoreTint(); + unsaved = true; + } + + api->TextColored(settings.tint[0], settings.tint[1], settings.tint[2], settings.tint[3], settings.label); + + api->Disabled(false); + + api->Section("Settings"); + + if (unsaved) + api->TextColored(1.0f, 0.8f, 0.0f, 1.0f, "There are unsaved changes"); + else + api->TextDisabled("Everything is saved"); + + api->Spacing(); + + if (api->Button("Save")) + { + if (api->SaveSettings(self)) + { + unsaved = false; + api->Log(self, OptiLog_Info, "Settings saved"); + } + else + { + api->Log(self, OptiLog_Error, "Couldn't save the settings"); + } + } + api->ItemTooltip("Writes OptiScaler.ini, the Save INI button of the menu does the same"); + + api->SameLine(); + + if (api->Button("Reload")) + LoadSettings(); + api->ItemTooltip("Throws away the unsaved changes"); + + api->SameLine(); + + if (api->Button("Defaults")) + ResetSettings(); + api->ItemTooltip("Removes the keys from the ini, save to make it permanent"); +} + +void DrawInfoTab(void* userData) +{ + auto counter = static_cast(userData); + + api->Section("Plugin API"); + + char text[128]; + snprintf(text, sizeof(text), "OptiScaler API version %u, table size %u bytes", api->version, api->size); + api->Text(text); + + snprintf(text, sizeof(text), "Built against version %d, table size %zu bytes", OPTI_PLUGIN_API_VERSION, + sizeof(OptiPluginApi)); + api->TextDisabled(text); + + api->Separator(); + + snprintf(text, sizeof(text), "Menu scale: %.2f, menu open: %s", api->GetMenuScale(), + api->IsMenuOpen() ? "yes" : "no"); + api->Text(text); + + api->Section("Counter"); + + // userData given to RegisterTab comes back here + if (api->Button("Click me")) + { + (*counter)++; + + snprintf(text, sizeof(text), "Button clicked %d times", *counter); + api->Log(self, OptiLog_Debug, text); + } + + api->SameLine(); + + snprintf(text, sizeof(text), "Clicked %d times", *counter); + api->Text(text); +} +} // namespace + +extern "C" __declspec(dllexport) bool OptiPluginInit(const OptiPluginApi* optiApi, OptiPlugin* plugin) +{ + // An older OptiScaler doesn't have everything this plugin uses + if (!OPTI_API_HAS(optiApi, Log)) + return false; + + api = optiApi; + self = plugin; + + LoadSettings(); + + api->RegisterTab(self, "Sample", "Settings of the sample plugin", DrawMainTab, nullptr); + api->RegisterTab(self, "Sample Info", "What the plugin API reports", DrawInfoTab, &clickCount); + + api->Log(self, OptiLog_Info, "Sample plugin initialized"); + + return true; +} + +BOOL APIENTRY DllMain(HMODULE, DWORD, LPVOID) { return TRUE; } diff --git a/plugin_sdk/sample/SamplePlugin.vcxproj b/plugin_sdk/sample/SamplePlugin.vcxproj new file mode 100644 index 00000000..032705fe --- /dev/null +++ b/plugin_sdk/sample/SamplePlugin.vcxproj @@ -0,0 +1,80 @@ + + + + + Debug + x64 + + + Release + x64 + + + + 17.0 + {6B0E2A4C-3D1F-4E8B-9A57-2C64F1D0B8E3} + SamplePlugin + 10.0 + + + + DynamicLibrary + + $(DefaultPlatformToolset) + Unicode + + + true + + + false + true + + + + .asi + $(ProjectDir)bin\$(Configuration)\ + $(ProjectDir)obj\$(Configuration)\ + + + + Level4 + true + true + stdcpp20 + WIN32_LEAN_AND_MEAN;NOMINMAX;%(PreprocessorDefinitions) + + + Windows + + + + + Disabled + MultiThreadedDebug + + + true + + + + + true + true + + MultiThreaded + + + true + true + true + + + + + + + + + +