diff --git a/CHANGELOG.md b/CHANGELOG.md index 6caa822..14619a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,23 @@ The release notes for each tag are taken from the section for that version. +## Unreleased + +### New +- **Mods for VIctory-NVIDIA** (*Settings → Mods & controls*, Windows): VIctory-NVIDIA v2026.11.29.01 loads every DLL in `%LOCALAPPDATA% ictorymods` at each start (its PR #1892). The launcher lists them, adds a DLL, turns one off (renamed to `.dll.off`, which the game skips) or on again, removes one, and opens the folder. It never downloads or runs a mod itself, and never overwrites one. Screenshot mode hides the folder's path. +- **Memory saver on VIctory-NVIDIA:** most of its switches are KLBF Lab's, which this build does not read. On a `victory play` start it now also sends the ones the build does read for the same need, from its docs/windows-memory.md: two pipeline workers (Light and up), and a smaller VRAM reserve for later render targets, given back once they settle (Very light). A value of your own always wins. +- **Short of Windows memory, told apart:** when the game's memory guard reports the commit limit (RAM and page file) and the driver refuses pipelines with `0x8007000E`, Fix and verify says the PC is short, not the card, and how to let Windows manage the page file. Its fix turns on Series S and the memory saver, and leaves the render scale and output alone. For VIctory-NVIDIA on 16 GB of RAM, two pipeline workers is offered as a possible setting when a start does not already send it. +- **Start-up reservation crash of VIctory-NVIDIA v2026.11.29.01 named:** `XMemVirtualAlloc refused … (os error 8)` followed by a stop is a problem of that release on some PCs, not of RAM or switches. The launcher says so and points to *Restore previous build*. +- **Screens that are not 16:9:** VIctory-NVIDIA v2026.11.29.01 sizes its picture after the screen's shape, and players on 21:9, 32:9 and 16:10 screens report it stopping at the start. On such a screen the launcher asks for 2560x1440, the size before, unless you set `VICTORY_NATIVE_SIZE` yourself or in the F1 menu. + +### Changed +- **Keyboard keys for the controller skip builds with their own mouse and keyboard:** VIctory-NVIDIA from v2026.11.29.01 has mouse and keyboard controls of its own (F1, MOUSE AND KEYBOARD; keys in `bindings.ini`), so the launcher's keys leave it alone and are never remapped twice. Every other fork still reads the fixed keyboard table, and keeps the launcher's keys. The launcher tells the builds apart from the program itself. + +### Fixed +- **F1 menu on VIctory-NVIDIA:** the launcher no longer closes the game whenever the F1 menu saves a choice. That build applies its choices and restarts itself for those that need it; the launcher's own watcher closed it even for choices applied at once. +- **Fewer `--help` runs:** the launcher asks a build what it offers once per program file, not before every check and start (seconds each through Wine or CrossOver). +- **Agent tool:** `status` said a VIctory-NVIDIA build was not installed. The project has a `diag` profile, and the tool looked for the program there; the launcher builds `release`, as the tool now does too. + ## 1.2.2 ### New diff --git a/scripts/vilauncher-agent.mjs b/scripts/vilauncher-agent.mjs index 36fadb0..9fd2c06 100644 --- a/scripts/vilauncher-agent.mjs +++ b/scripts/vilauncher-agent.mjs @@ -272,13 +272,10 @@ async function readBuilt(targetDir) { } } -async function readCargoProfile(repoDir) { - try { - const text = await readFile(join(repoDir, "Cargo.toml"), "utf8"); - return text.includes("[profile.diag]") ? "diag" : "release"; - } catch { - return "release"; - } +// Mirrors launcher.rs detect_build_profile(): players always get the release build, even when +// the project also has a `diag` profile (VIctory-NVIDIA does), so its program is under release. +async function readCargoProfile(_repoDir) { + return "release"; } // Mirrors launcher.rs project_installed(): the recorded Rust install, else the victory program under the profile. diff --git a/src-tauri/known-problems/known-problems.json b/src-tauri/known-problems/known-problems.json index 7511893..8080683 100644 --- a/src-tauri/known-problems/known-problems.json +++ b/src-tauri/known-problems/known-problems.json @@ -10,6 +10,27 @@ "summary": "Black or incorrect surfaces.", "source": "Research brief, Phase 1: one A/B run reported black or incorrect surfaces with VICTORY_INPLACE=1. Single run; no repo doc names this switch.", "status": "single_run_report" + }, + { + "id": "victory-nvidia-commit-pipeline-workers", + "project": "VIctory-NVIDIA", + "switch": "VICTORY_PIPELINE_WORKERS=2", + "summary": "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.", + "source": "trustno1-coder/VIctory-NVIDIA docs/windows-memory.md (v2026.11.29.01): on 32 GB of RAM and an 8 GB RTX 3060 Ti the first scene load reached the commit limit and closed; with two pipeline workers it loaded past that point. A run of v2026.11.29.01 on an 8 GB RTX 4060 with 16 GB of RAM had 1137 pipelines refused with 0x8007000E while the memory guard reported commit under its floor.", + "status": "single_run_report", + "advice": { + "switch": "VICTORY_PIPELINE_WORKERS=2", + "evidence": "single_run_report", + "source": "docs/windows-memory.md, Reproduction on 32 GB RAM and an 8 GB RTX 3060 Ti", + "when": [ + { + "ram_gb_at_most": 16 + }, + { + "windows_only": true + } + ] + } } ] } diff --git a/src-tauri/locales/es/launcher.json b/src-tauri/locales/es/launcher.json index af78de4..ce8978a 100644 --- a/src-tauri/locales/es/launcher.json +++ b/src-tauri/locales/es/launcher.json @@ -166,5 +166,20 @@ "CrossOver was not found in Applications.": "No se encontró CrossOver en Aplicaciones.", "The CrossOver bottle {bottle} was not found.": "No se encontró la botella de CrossOver {bottle}.", "The Wine program {wine} is not there.": "El programa Wine {wine} no está ahí.", - "{program} is a Windows program. Choose a runner (CrossOver or Wine) in Settings under Windows builds on this Mac, or build the project from source on macOS.": "{program} es un programa de Windows. Elige un entorno (CrossOver o Wine) en Configuración, bajo Compilaciones de Windows en este Mac, o compila el proyecto desde el código fuente en macOS." + "{program} is a Windows program. Choose a runner (CrossOver or Wine) in Settings under Windows builds on this Mac, or build the project from source on macOS.": "{program} es un programa de Windows. Elige un entorno (CrossOver o Wine) en Configuración, bajo Compilaciones de Windows en este Mac, o compila el proyecto desde el código fuente en macOS.", + "Mods are loaded on Windows only: this PC has no mods folder.": "Los mods solo se cargan en Windows: este PC no tiene carpeta de mods.", + "{file} is not the name of a mod DLL.": "{file} no es el nombre de una DLL de mod.", + "The mod {file} is not in the mods folder.": "El mod {file} no está en la carpeta de mods.", + "{file} is in the mods folder twice (on and off): remove one.": "{file} está dos veces en la carpeta de mods (activado y desactivado): quita uno.", + "Could not rename {file}: {e}": "No se pudo renombrar {file}: {e}", + "{file} is not a file.": "{file} no es un archivo.", + "A mod named {file} is already in the mods folder.": "Ya hay un mod llamado {file} en la carpeta de mods.", + "Could not make the mods folder: {e}": "No se pudo crear la carpeta de mods: {e}", + "Could not copy {file}: {e}": "No se pudo copiar {file}: {e}", + "Could not remove {file}: {e}": "No se pudo quitar {file}: {e}", + "Windows ran short of memory for the game (RAM and page file).": "Windows se quedó sin memoria para el juego (RAM y archivo de paginación).", + "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify turns on Series S and the memory saver, which on VIctory-NVIDIA started through its own play prepares two shaders at a time instead of up to eight. It leaves the render scale and output as they are: those are for the card's memory.": "El juego pidió a Windows más memoria de la que dejaban la RAM y el archivo de paginación, así que se rechazaron pipelines de shaders y faltaron sus dibujados. Cierra otros programas y deja que Windows administre el tamaño del archivo de paginación (Sistema, Acerca de, Configuración avanzada del sistema, Rendimiento, Memoria virtual) y reinicia. Reparar y verificar activa la Series S y el ahorro de memoria, que en VIctory-NVIDIA iniciado con su propio play prepara dos shaders a la vez en lugar de hasta ocho. La escala de renderizado y la salida se quedan como están: son para la memoria de la tarjeta.", + "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "Menos pipelines de shaders preparados a la vez (2 en lugar de hasta 8), para que el juego se mantenga por debajo del límite de memoria confirmada de Windows (RAM y archivo de paginación) en un PC con 16 GB de RAM. Los shaders tardan más en terminarse la primera vez.", + "This build could not reserve the game's memory at the start.": "Esta compilación no pudo reservar la memoria del juego al iniciar.", + "It is not your RAM or page file: this release of VIctory-NVIDIA reserves the game's memory in an address range that runs out on some PCs, and its next release fixes it. Until then, use Restore previous build on the project (the release before starts), or update when a newer one is out.": "No es tu RAM ni tu archivo de paginación: esta versión de VIctory-NVIDIA reserva la memoria del juego en un rango de direcciones que se agota en algunos PC, y su próxima versión lo corrige. Hasta entonces, usa Restaurar compilación anterior en el proyecto (la versión anterior sí inicia), o actualiza cuando salga una más nueva." } diff --git a/src-tauri/locales/fr/launcher.json b/src-tauri/locales/fr/launcher.json index ece9c99..779bd9a 100644 --- a/src-tauri/locales/fr/launcher.json +++ b/src-tauri/locales/fr/launcher.json @@ -166,5 +166,20 @@ "CrossOver was not found in Applications.": "CrossOver est introuvable dans Applications.", "The CrossOver bottle {bottle} was not found.": "La bouteille CrossOver {bottle} est introuvable.", "The Wine program {wine} is not there.": "Le programme Wine {wine} est introuvable.", - "{program} is a Windows program. Choose a runner (CrossOver or Wine) in Settings under Windows builds on this Mac, or build the project from source on macOS.": "{program} est un programme Windows. Choisissez un runner (CrossOver ou Wine) dans les réglages, sous « Fichiers Windows sur ce Mac », ou compilez le projet depuis les sources sous macOS." + "{program} is a Windows program. Choose a runner (CrossOver or Wine) in Settings under Windows builds on this Mac, or build the project from source on macOS.": "{program} est un programme Windows. Choisissez un runner (CrossOver ou Wine) dans les réglages, sous « Fichiers Windows sur ce Mac », ou compilez le projet depuis les sources sous macOS.", + "Mods are loaded on Windows only: this PC has no mods folder.": "Les mods ne se chargent que sous Windows : ce PC n'a pas de dossier de mods.", + "{file} is not the name of a mod DLL.": "{file} n'est pas le nom d'une DLL de mod.", + "The mod {file} is not in the mods folder.": "Le mod {file} n'est pas dans le dossier des mods.", + "{file} is in the mods folder twice (on and off): remove one.": "{file} est deux fois dans le dossier des mods (activé et désactivé) : supprimez-en un.", + "Could not rename {file}: {e}": "Impossible de renommer {file} : {e}", + "{file} is not a file.": "{file} n'est pas un fichier.", + "A mod named {file} is already in the mods folder.": "Un mod nommé {file} est déjà dans le dossier des mods.", + "Could not make the mods folder: {e}": "Impossible de créer le dossier des mods : {e}", + "Could not copy {file}: {e}": "Impossible de copier {file} : {e}", + "Could not remove {file}: {e}": "Impossible de supprimer {file} : {e}", + "Windows ran short of memory for the game (RAM and page file).": "Windows a manqué de mémoire pour le jeu (RAM et fichier d'échange).", + "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify turns on Series S and the memory saver, which on VIctory-NVIDIA started through its own play prepares two shaders at a time instead of up to eight. It leaves the render scale and output as they are: those are for the card's memory.": "Le jeu a demandé à Windows plus de mémoire que la RAM et le fichier d'échange n'en laissaient : des pipelines de shaders ont été refusés et leurs rendus ont manqué. Fermez les autres programmes et laissez Windows gérer la taille du fichier d'échange (Système, Informations système, Paramètres système avancés, Performances, Mémoire virtuelle), puis redémarrez. Corriger et vérifier active la Series S et l'économiseur de mémoire qui, sur VIctory-NVIDIA lancé par son propre play, prépare deux shaders à la fois au lieu de huit au plus. L'échelle de rendu et la sortie restent telles quelles : elles concernent la mémoire de la carte.", + "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "Moins de pipelines de shaders préparés à la fois (2 au lieu de 8 au plus) : le jeu reste sous la limite de mémoire validée de Windows (RAM et fichier d’échange) sur un PC avec 16 Go de RAM. Les shaders mettent plus de temps à se terminer la première fois.", + "This build could not reserve the game's memory at the start.": "Cette version n'a pas pu réserver la mémoire du jeu au démarrage.", + "It is not your RAM or page file: this release of VIctory-NVIDIA reserves the game's memory in an address range that runs out on some PCs, and its next release fixes it. Until then, use Restore previous build on the project (the release before starts), or update when a newer one is out.": "Ce n'est ni votre RAM ni votre fichier d'échange : cette version de VIctory-NVIDIA réserve la mémoire du jeu dans une plage d'adresses qui s'épuise sur certains PC, et sa prochaine version corrige cela. D'ici là, utilisez Restaurer le build précédent sur le projet (la version d'avant démarre), ou mettez à jour quand une plus récente sort." } diff --git a/src-tauri/locales/ru/launcher.json b/src-tauri/locales/ru/launcher.json index fbd258d..8d08649 100644 --- a/src-tauri/locales/ru/launcher.json +++ b/src-tauri/locales/ru/launcher.json @@ -166,5 +166,20 @@ "CrossOver was not found in Applications.": "CrossOver не найден в «Программах».", "The CrossOver bottle {bottle} was not found.": "Бутылка CrossOver {bottle} не найдена.", "The Wine program {wine} is not there.": "Программа Wine {wine} не найдена.", - "{program} is a Windows program. Choose a runner (CrossOver or Wine) in Settings under Windows builds on this Mac, or build the project from source on macOS.": "{program} — программа для Windows. Выберите слой совместимости (CrossOver или Wine) в Настройках в разделе «Сборки Windows на этом Mac» или соберите проект из исходников на macOS." + "{program} is a Windows program. Choose a runner (CrossOver or Wine) in Settings under Windows builds on this Mac, or build the project from source on macOS.": "{program} — программа для Windows. Выберите слой совместимости (CrossOver или Wine) в Настройках в разделе «Сборки Windows на этом Mac» или соберите проект из исходников на macOS.", + "Mods are loaded on Windows only: this PC has no mods folder.": "Моды загружаются только в Windows: на этом ПК нет папки модов.", + "{file} is not the name of a mod DLL.": "{file} — не имя DLL мода.", + "The mod {file} is not in the mods folder.": "Мода {file} нет в папке модов.", + "{file} is in the mods folder twice (on and off): remove one.": "{file} есть в папке модов дважды (включённый и выключенный): удалите один.", + "Could not rename {file}: {e}": "Не удалось переименовать {file}: {e}", + "{file} is not a file.": "{file} — не файл.", + "A mod named {file} is already in the mods folder.": "Мод с именем {file} уже есть в папке модов.", + "Could not make the mods folder: {e}": "Не удалось создать папку модов: {e}", + "Could not copy {file}: {e}": "Не удалось скопировать {file}: {e}", + "Could not remove {file}: {e}": "Не удалось удалить {file}: {e}", + "Windows ran short of memory for the game (RAM and page file).": "Windows не хватило памяти для игры (ОЗУ и файл подкачки).", + "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify turns on Series S and the memory saver, which on VIctory-NVIDIA started through its own play prepares two shaders at a time instead of up to eight. It leaves the render scale and output as they are: those are for the card's memory.": "Игра запросила у Windows больше памяти, чем оставалось в ОЗУ и файле подкачки, поэтому конвейеры шейдеров были отклонены, а их отрисовка пропала. Закройте другие программы и позвольте Windows автоматически выбирать размер файла подкачки (Система, О программе, Дополнительные параметры системы, Быстродействие, Виртуальная память), затем перезагрузите ПК. «Исправить и проверить» включает Series S и экономию памяти: в VIctory-NVIDIA, запущенной через её собственный play, она готовит два шейдера одновременно вместо восьми. Масштаб рендеринга и выходное разрешение не меняются: они относятся к памяти видеокарты.", + "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "Меньше конвейеров шейдеров одновременно (2 вместо до 8), чтобы игра не выходила за предел выделенной памяти Windows (ОЗУ и файл подкачки) на ПК с 16 ГБ ОЗУ. В первый раз шейдеры готовятся дольше.", + "This build could not reserve the game's memory at the start.": "Этой сборке не удалось зарезервировать память игры при запуске.", + "It is not your RAM or page file: this release of VIctory-NVIDIA reserves the game's memory in an address range that runs out on some PCs, and its next release fixes it. Until then, use Restore previous build on the project (the release before starts), or update when a newer one is out.": "Дело не в ОЗУ и не в файле подкачки: этот выпуск VIctory-NVIDIA резервирует память игры в диапазоне адресов, которого на некоторых ПК не хватает, и следующий выпуск это исправляет. До тех пор используйте «Восстановить предыдущую сборку» в проекте (предыдущий выпуск запускается) или обновитесь, когда выйдет новый." } diff --git a/src-tauri/locales/zh-CN/launcher.json b/src-tauri/locales/zh-CN/launcher.json index 1fc5088..7de3afa 100644 --- a/src-tauri/locales/zh-CN/launcher.json +++ b/src-tauri/locales/zh-CN/launcher.json @@ -166,5 +166,20 @@ "Install the project first.": "请先安装项目。", "Memory stack": "内存精简补丁", "Cuts VRAM and private memory with no change to what is drawn. On the author's RTX 5080 16 GB: VRAM about 12.6 GB down to 8.55 GB, private commit about 26 GB down to about 20.5 GB.": "降低显存与私有内存用量,画面完全不变。在作者的 RTX 5080 16 GB 上:显存约从 12.6 GB 降到 8.55 GB,私有提交约从 26 GB 降到约 20.5 GB。", - "Turning this on commits the memory stack's patches to a vilauncher/memory-stack branch of this project, then switches the project to that branch. It only applies if the project is close to the stack's base (e94251a). Forks that have moved further do not take the patches: the launcher says so and changes nothing. The first run after turning it on makes the shaders again (minutes of missing draws). Turning it off goes back to the project's own branch.": "开启后,内存精简补丁会提交到这个项目的 vilauncher/memory-stack 分支,并把项目切换到该分支。只有接近补丁基准(e94251a)的项目才能应用。差异更大的分支无法应用这些补丁:启动器会说明原因,且不做任何更改。开启后第一次运行会重新生成着色器(会有几分钟缺少画面)。关闭后会回到项目原本的分支。" + "Turning this on commits the memory stack's patches to a vilauncher/memory-stack branch of this project, then switches the project to that branch. It only applies if the project is close to the stack's base (e94251a). Forks that have moved further do not take the patches: the launcher says so and changes nothing. The first run after turning it on makes the shaders again (minutes of missing draws). Turning it off goes back to the project's own branch.": "开启后,内存精简补丁会提交到这个项目的 vilauncher/memory-stack 分支,并把项目切换到该分支。只有接近补丁基准(e94251a)的项目才能应用。差异更大的分支无法应用这些补丁:启动器会说明原因,且不做任何更改。开启后第一次运行会重新生成着色器(会有几分钟缺少画面)。关闭后会回到项目原本的分支。", + "Mods are loaded on Windows only: this PC has no mods folder.": "模组只能在 Windows 上加载:这台电脑没有模组文件夹。", + "{file} is not the name of a mod DLL.": "{file} 不是模组 DLL 的名称。", + "The mod {file} is not in the mods folder.": "模组 {file} 不在模组文件夹中。", + "{file} is in the mods folder twice (on and off): remove one.": "{file} 在模组文件夹中有两份(已启用和已停用):请移除其中一份。", + "Could not rename {file}: {e}": "无法重命名 {file}:{e}", + "{file} is not a file.": "{file} 不是文件。", + "A mod named {file} is already in the mods folder.": "模组文件夹中已有名为 {file} 的模组。", + "Could not make the mods folder: {e}": "无法创建模组文件夹:{e}", + "Could not copy {file}: {e}": "无法复制 {file}:{e}", + "Could not remove {file}: {e}": "无法移除 {file}:{e}", + "Windows ran short of memory for the game (RAM and page file).": "Windows 给游戏的内存不足(内存和页面文件)。", + "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify turns on Series S and the memory saver, which on VIctory-NVIDIA started through its own play prepares two shaders at a time instead of up to eight. It leaves the render scale and output as they are: those are for the card's memory.": "游戏向 Windows 申请的内存超过了内存和页面文件剩余的量,因此着色器管线被拒绝,相应的绘制缺失。请关闭其他程序,并让 Windows 自动管理页面文件大小(系统、系统信息、高级系统设置、性能、虚拟内存),然后重启。“修复并验证”会开启 Series S 和内存节省;在通过自身 play 启动的 VIctory-NVIDIA 上,它每次只准备两个着色器,而不是最多八个。渲染比例和输出保持不变:它们针对的是显卡的显存。", + "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "同时准备的着色器管线更少(2 个,而不是最多 8 个),这样在 16 GB 内存的电脑上,游戏不会超出 Windows 的提交内存上限(内存和页面文件)。第一次准备着色器会更久。", + "This build could not reserve the game's memory at the start.": "此构建在启动时无法预留游戏所需的内存。", + "It is not your RAM or page file: this release of VIctory-NVIDIA reserves the game's memory in an address range that runs out on some PCs, and its next release fixes it. Until then, use Restore previous build on the project (the release before starts), or update when a newer one is out.": "这不是内存或页面文件的问题:这个版本的 VIctory-NVIDIA 会在一段地址范围内预留游戏内存,而这段范围在部分电脑上会不够用,下一个版本会修复。在此之前,请在项目上使用“还原上一个构建版本”(上一个版本可以启动),或等有新版本时更新。" } diff --git a/src-tauri/locales/zh-TW/launcher.json b/src-tauri/locales/zh-TW/launcher.json index f682141..4269305 100644 --- a/src-tauri/locales/zh-TW/launcher.json +++ b/src-tauri/locales/zh-TW/launcher.json @@ -166,5 +166,20 @@ "Install the project first.": "請先安裝專案。", "Memory stack": "記憶體精簡修補", "Cuts VRAM and private memory with no change to what is drawn. On the author's RTX 5080 16 GB: VRAM about 12.6 GB down to 8.55 GB, private commit about 26 GB down to about 20.5 GB.": "降低顯示記憶體與私有記憶體用量,畫面完全不變。在作者的 RTX 5080 16 GB 上:顯示記憶體約從 12.6 GB 降到 8.55 GB,私有提交約從 26 GB 降到約 20.5 GB。", - "Turning this on commits the memory stack's patches to a vilauncher/memory-stack branch of this project, then switches the project to that branch. It only applies if the project is close to the stack's base (e94251a). Forks that have moved further do not take the patches: the launcher says so and changes nothing. The first run after turning it on makes the shaders again (minutes of missing draws). Turning it off goes back to the project's own branch.": "開啟後,記憶體精簡修補程式會提交到這個專案的 vilauncher/memory-stack 分支,並把專案切換到該分支。只有接近修補程式基準(e94251a)的專案才能套用。差異更大的分支無法套用這些修補程式:啟動器會說明原因,且不做任何變更。開啟後第一次執行會重新產生著色器(會有幾分鐘缺少畫面)。關閉後會回到專案原本的分支。" + "Turning this on commits the memory stack's patches to a vilauncher/memory-stack branch of this project, then switches the project to that branch. It only applies if the project is close to the stack's base (e94251a). Forks that have moved further do not take the patches: the launcher says so and changes nothing. The first run after turning it on makes the shaders again (minutes of missing draws). Turning it off goes back to the project's own branch.": "開啟後,記憶體精簡修補程式會提交到這個專案的 vilauncher/memory-stack 分支,並把專案切換到該分支。只有接近修補程式基準(e94251a)的專案才能套用。差異更大的分支無法套用這些修補程式:啟動器會說明原因,且不做任何變更。開啟後第一次執行會重新產生著色器(會有幾分鐘缺少畫面)。關閉後會回到專案原本的分支。", + "Mods are loaded on Windows only: this PC has no mods folder.": "模組只能在 Windows 上載入:這台電腦沒有模組資料夾。", + "{file} is not the name of a mod DLL.": "{file} 不是模組 DLL 的名稱。", + "The mod {file} is not in the mods folder.": "模組 {file} 不在模組資料夾中。", + "{file} is in the mods folder twice (on and off): remove one.": "{file} 在模組資料夾中有兩份(已啟用和已停用):請移除其中一份。", + "Could not rename {file}: {e}": "無法重新命名 {file}:{e}", + "{file} is not a file.": "{file} 不是檔案。", + "A mod named {file} is already in the mods folder.": "模組資料夾中已有名為 {file} 的模組。", + "Could not make the mods folder: {e}": "無法建立模組資料夾:{e}", + "Could not copy {file}: {e}": "無法複製 {file}:{e}", + "Could not remove {file}: {e}": "無法移除 {file}:{e}", + "Windows ran short of memory for the game (RAM and page file).": "Windows 給遊戲的記憶體不足(記憶體和分頁檔)。", + "The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify turns on Series S and the memory saver, which on VIctory-NVIDIA started through its own play prepares two shaders at a time instead of up to eight. It leaves the render scale and output as they are: those are for the card's memory.": "遊戲向 Windows 要求的記憶體超過了記憶體和分頁檔剩餘的量,因此著色器管線被拒絕,相應的繪製缺失。請關閉其他程式,並讓 Windows 自動管理分頁檔大小(系統、關於、進階系統設定、效能、虛擬記憶體),然後重新開機。「修復並驗證」會開啟 Series S 和記憶體節省;在透過自身 play 啟動的 VIctory-NVIDIA 上,它一次只準備兩個著色器,而不是最多八個。渲染比例和輸出保持不變:它們針對的是顯示卡的記憶體。", + "Fewer shader pipelines made at once (2 instead of up to 8), so the game stays under the Windows commit limit (RAM and page file) on a PC with 16 GB of RAM. Shaders take longer to finish the first time.": "同時準備的著色器管線更少(2 個,而不是最多 8 個),這樣在 16 GB 記憶體的電腦上,遊戲不會超出 Windows 的認可記憶體上限(記憶體和分頁檔)。第一次準備著色器會更久。", + "This build could not reserve the game's memory at the start.": "此建置在啟動時無法預留遊戲所需的記憶體。", + "It is not your RAM or page file: this release of VIctory-NVIDIA reserves the game's memory in an address range that runs out on some PCs, and its next release fixes it. Until then, use Restore previous build on the project (the release before starts), or update when a newer one is out.": "這不是記憶體或分頁檔的問題:這個版本的 VIctory-NVIDIA 會在一段位址範圍內預留遊戲記憶體,而這段範圍在部分電腦上會不夠用,下一個版本會修復。在此之前,請在專案上使用「還原上一個建置版本」(上一個版本可以啟動),或等有新版本時更新。" } diff --git a/src-tauri/src/controller_keys.rs b/src-tauri/src/controller_keys.rs index 064bb92..5d10022 100644 --- a/src-tauri/src/controller_keys.rs +++ b/src-tauri/src/controller_keys.rs @@ -5,9 +5,27 @@ //! those controls another key. While the game window is in front, a low-level keyboard //! hook sends the layer's own key for the control whose key was pressed. Off by default. //! Only Windows has the hook; elsewhere the settings are kept and nothing is sent. +//! +//! A build with mouse and keyboard of its own (VIctory-NVIDIA from v2026.11.29.01: F1, +//! MOUSE AND KEYBOARD, keys in bindings.ini) is left alone, or the keys would be remapped +//! twice. Every other fork still reads the fixed table, so for them the keys stay. use std::collections::BTreeMap; +/// Text only a build with its own mouse and keyboard bindings has in its program: the switch +/// naming VIctory-NVIDIA's bindings.ini (crates/victory-hle/src/modules/mnk.rs, play.rs). +// Only the Windows hook reads programs; elsewhere this is for the tests. +#[cfg_attr(not(windows), allow(dead_code))] +const OWN_KEYBOARD_MARK: &[u8] = b"VICTORY_MNK_BINDINGS"; + +/// Whether a program's bytes are those of a build with its own mouse and keyboard. +#[cfg_attr(not(windows), allow(dead_code))] +pub fn has_own_keyboard(program: &[u8]) -> bool { + program + .windows(OWN_KEYBOARD_MARK.len()) + .any(|window| window == OWN_KEYBOARD_MARK) +} + /// One control the layer reads from the keyboard, with the key the layer uses for it. pub struct Control { pub id: &'static str, @@ -277,7 +295,7 @@ mod hook { let consumed = if up { release(key) } else { - ENABLED.load(Ordering::Relaxed) && game_in_front() && press(key) + ENABLED.load(Ordering::Relaxed) && game_without_own_keyboard() && press(key) }; if consumed { return 1; @@ -330,28 +348,61 @@ mod hook { } } - /// Whether the window in front belongs to the game. - unsafe fn game_in_front() -> bool { + /// What is known of each game program: whether it has its own mouse and keyboard; None + /// while it is being read. Read once per program file, on a thread of its own: never in + /// the hook, which Windows drops when it is slow. + static OWN_KEYBOARD: Mutex>>> = Mutex::new(None); + + /// Whether the window in front is the game, of a build known to have no mouse and keyboard + /// of its own. False while that is still being read: those keys pass unchanged. + unsafe fn game_without_own_keyboard() -> bool { + let Some(path) = game_in_front() else { + return false; + }; + let mut guard = OWN_KEYBOARD.lock().unwrap_or_else(|e| e.into_inner()); + let known = guard.get_or_insert_with(HashMap::new); + match known.get(&path) { + Some(Some(own)) => !own, + Some(None) => false, + None => { + known.insert(path.clone(), None); + std::thread::spawn(move || { + let own = + std::fs::read(&path).is_ok_and(|bytes| super::has_own_keyboard(&bytes)); + let mut guard = OWN_KEYBOARD.lock().unwrap_or_else(|e| e.into_inner()); + guard + .get_or_insert_with(HashMap::new) + .insert(path, Some(own)); + }); + false + } + } + } + + /// The program of the window in front, when it is the game. + unsafe fn game_in_front() -> Option { let window = GetForegroundWindow(); if window.is_null() { - return false; + return None; } let mut pid = 0u32; GetWindowThreadProcessId(window, &mut pid); let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); if process.is_null() { - return false; + return None; } let mut buffer = [0u16; 1024]; let mut length = buffer.len() as u32; let named = QueryFullProcessImageNameW(process, 0, buffer.as_mut_ptr(), &mut length) != 0; CloseHandle(process); - named && { - let path = String::from_utf16_lossy(&buffer[..length as usize]); - std::path::Path::new(&path) - .file_name() - .is_some_and(|name| name.to_string_lossy().eq_ignore_ascii_case(GAME_EXE)) + if !named { + return None; } + let path = String::from_utf16_lossy(&buffer[..length as usize]); + std::path::Path::new(&path) + .file_name() + .is_some_and(|name| name.to_string_lossy().eq_ignore_ascii_case(GAME_EXE)) + .then_some(path) } unsafe fn send(key: u16, down: bool) { @@ -433,6 +484,13 @@ mod tests { assert!(check_key(&none, "a", 0x5B).is_err()); } + #[test] + fn a_build_with_its_own_keyboard_is_told_from_its_program() { + assert!(has_own_keyboard(b"..VICTORY_MNK_BINDINGS..")); + assert!(!has_own_keyboard(b"..VICTORY_MNK.. VICTORY_KBM_PC..")); + assert!(!has_own_keyboard(b"")); + } + #[test] fn every_control_has_a_distinct_default_key() { for (i, a) in CONTROLS.iter().enumerate() { diff --git a/src-tauri/src/diagnose.rs b/src-tauri/src/diagnose.rs index 8dcf590..eedb3bc 100644 --- a/src-tauri/src/diagnose.rs +++ b/src-tauri/src/diagnose.rs @@ -20,6 +20,9 @@ pub(crate) const FIX_CLEAR_SHADER_CACHE: &str = "clear-shader-cache"; pub(crate) const FIX_PERMISSIONS: &str = "permissions"; pub(crate) const FIX_DISK: &str = "disk-space"; pub(crate) const FIX_GRAPHICS_MEMORY: &str = "graphics-memory"; +/// Windows' commit (RAM and page file) ran out, not the card's memory: Series S and the memory +/// saver, without the render scale and output cuts that are for the card. +pub(crate) const FIX_COMMIT_MEMORY: &str = "commit-memory"; pub(crate) const FIX_GRAPHICS_DEVICE: &str = "graphics-device"; pub(crate) const FIX_DRIVER_PAGE: &str = "driver-page"; pub(crate) const FIX_REPO_SWITCH: &str = "repo-switch"; @@ -1157,9 +1160,29 @@ pub(crate) fn from_log(lines: &[String]) -> Vec { advice: None, }); } + // VIctory-NVIDIA v2026.11.29.01 reserves the title's memory under a 2^37 cap + // (crates/victory-hle/src/modules/xmem.rs, TITLE_TOP_BITS) that runs out on some PCs: the + // reservation is refused with Windows error 8 and the title stops on 0x80000003 at the start + // (upstream issues #2081, #2112, #2141, #2150, #2167; PR #2133 fixes it). RAM and the page + // file are fine there, and the release before starts. The Windows text is in the player's + // language, so the English token and the error number are matched. + let xmem = lines + .iter() + .any(|line| line.contains("XMemVirtualAlloc refused") && line.contains("os error 8")); + if xmem { + found.push(Finding { + title: msg_str!("This build could not reserve the game's memory at the start.").to_string(), + detail: msg_str!("It is not your RAM or page file: this release of VIctory-NVIDIA reserves the game's memory in an address range that runs out on some PCs, and its next release fixes it. Until then, use Restore previous build on the project (the release before starts), or update when a newer one is out.").to_string(), + fix: None, + heavy: false, + data: None, + advice: None, + }); + } // The game's own crash reporter prints this when its code stops on an exception before - // or while the title starts. The usual cause is an experimental switch. - if has(&["VIctory: unhandled exception"]) { + // or while the title starts. The usual cause is an experimental switch (not when the + // reservation above is why). + if !xmem && has(&["VIctory: unhandled exception"]) { found.push(Finding { title: "The game stopped with an unhandled exception.".to_string(), detail: "The game's code hit an exception (for example 0x80000003, a breakpoint trap) and closed. Open Launch options and clear the extra switches, then Play again. If it still stops, send the report: it has the exception and the game's crash files.".to_string(), @@ -1193,11 +1216,33 @@ pub(crate) fn from_log(lines: &[String]) -> Vec { advice: None, }); } - if has(&["out of memory", "0x8007000E"]) { + // VIctory-NVIDIA's memory guard puts a driver compile off when it would leave Windows' + // commit (RAM and page file together) under its floor, and the driver refuses one with + // 0x8007000E when there is none: then the PC is short, not the card, and the refused + // pipelines stay unmade, their draws missing (freezes, a black picture). + // The guard's line alone is a compile put off and made later; with a refusal, or an + // allocation that found no commit left (the runtime's abort), the PC ran short. + let refused = has(&["out of memory", "0x8007000E", "0x8007000e"]); + let commit = + has(&["left to commit"]) || refused && has(&["the commit left would fall under its floor"]); + if commit || refused { + let (title, detail, fix) = if commit { + ( + msg_str!("Windows ran short of memory for the game (RAM and page file)."), + msg_str!("The game asked Windows for more memory than RAM and the page file left, so shader pipelines were refused and their draws went missing. Close other programs, and let Windows manage the page file size (System, About, Advanced system settings, Performance, Virtual memory), then restart. Fix and verify turns on Series S and the memory saver, which on VIctory-NVIDIA started through its own play prepares two shaders at a time instead of up to eight. It leaves the render scale and output as they are: those are for the card's memory."), + FIX_COMMIT_MEMORY, + ) + } else { + ( + "The game ran out of memory.", + "Fix and verify lowers the render scale, turns on the texture fix and the memory saver, and lowers an output above 1080p to 1080p.", + FIX_GRAPHICS_MEMORY, + ) + }; found.push(Finding { - title: "The game ran out of memory.".to_string(), - detail: "Fix and verify lowers the render scale, turns on the texture fix and the memory saver, and lowers an output above 1080p to 1080p.".to_string(), - fix: Some(FIX_GRAPHICS_MEMORY), + title: title.to_string(), + detail: detail.to_string(), + fix: Some(fix), heavy: false, data: None, advice: None, @@ -1536,6 +1581,32 @@ mod tests { assert!(from_log(&bad).iter().any(|f| f.fix == Some(FIX_CACHE))); } + #[test] + fn short_commit_is_told_from_a_full_card() { + // VIctory-NVIDIA v2026.11.29.01 on an RTX 4060 with 16 GB of RAM: the memory guard and + // the driver's refusals, 1137 pipelines never made. + let commit = vec![ + r#"WARN victory_gpu::memguard: memory guard: a compile is put off (it is made again later; the process goes on) what="c0ffd16bf5bacb43" so_far=1024 free_physical_mb=1664 free_commit_mb=1765 reason="the commit left would fall under its floor""#.to_string(), + r#"WARN victory_gpu::pipeline::refused: host pipeline failed (logged once per key) key="37e19ccb4f889f63" stage="compute" hr=0x8007000e lacks="" reason="compute 0x8007000e""#.to_string(), + ]; + let found = from_log(&commit); + let memory: Vec<_> = found + .iter() + .filter(|f| matches!(f.fix, Some(FIX_GRAPHICS_MEMORY | FIX_COMMIT_MEMORY))) + .collect(); + assert_eq!(memory.len(), 1, "one finding, so the fix runs once"); + // Windows' commit, not the card: the lighter fix. + assert_eq!(memory[0].fix, Some(FIX_COMMIT_MEMORY)); + assert!(memory[0].title.contains("page file")); + // The guard's line alone is a compile made later: no finding. + assert!(from_log(&commit[..1]).is_empty()); + // A refusal alone (the card's own memory) keeps the plain finding. + let card = vec![commit[1].clone()]; + let found = from_log(&card); + assert_eq!(found.len(), 1); + assert_eq!(found[0].title, "The game ran out of memory."); + } + #[test] fn a_missing_build_is_a_heavy_finding() { let root = temp("missing-build"); @@ -1805,6 +1876,19 @@ mod tests { assert_eq!(hint.fix, None); } + #[test] + fn a_refused_title_reservation_is_named_and_not_blamed_on_switches_or_memory() { + // From upstream issue #2081 (v2026.11.29.01), the reservation then the stop. + let lines = vec![ + "WARN victory_hle::modules::xmem: XMemVirtualAlloc refused size=6538919936 kind=0x42000 flags=0x23 error=Not enough memory resources are available to process this command. (os error 8)".to_string(), + "VIctory: unhandled exception 0x80000003 at victory-image-0000+0x1e6c284 on thread 1234".to_string(), + ]; + let found = from_log(&lines); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].title.contains("reserve the game's memory")); + assert!(found[0].detail.contains("Restore previous build")); + } + #[test] fn an_unhandled_exception_is_named_with_the_switches_as_the_likely_cause() { let lines = vec!["VIctory: unhandled exception 0x80000003 at game_scarlett_master.exe+0x1ce6e13 on thread 3848".to_string()]; diff --git a/src-tauri/src/launcher.rs b/src-tauri/src/launcher.rs index a28833e..697d4a2 100644 --- a/src-tauri/src/launcher.rs +++ b/src-tauri/src/launcher.rs @@ -2470,7 +2470,7 @@ fn install( data: &data, cache: &cache, last_log: &[], - switches: &l.extra, + switches: &check_switches(l, starts_native(&exe, l)), installed: true, game_ok: game_files_ok(&l.game_dir), unplugged: !drive_connected(&l.game_dir), @@ -3027,6 +3027,13 @@ fn extra_sets(extra: &str, name: &str, value: &str) -> bool { }) } +/// Whether the player's lines name the switch `name`, with any value. +fn extra_names(extra: &str, name: &str) -> bool { + extra + .lines() + .any(|line| line.split_once('=').is_some_and(|(k, _)| k.trim() == name)) +} + /// The DLSS and frame-generation switches for one run, set the way Neptune's own launcher sets them: /// the F1 menu's saved choice, only on NVIDIA RTX cards, with NVIDIA's files in `dir`. The player's own /// Launch options that name these switches win (nothing is set then). Returns the switches and, for the @@ -3293,6 +3300,28 @@ fn run_until_f1_restart( } fn victory_help(exe: &Path, subcommand: &str) -> Option { + // Asked again for every check and start (through Wine or CrossOver on a Mac, seconds each): + // one answer per program, subcommand and build of the file. + type Key = (PathBuf, String, Option, u64); + static ANSWERS: std::sync::OnceLock>>> = + std::sync::OnceLock::new(); + let meta = std::fs::metadata(exe).ok()?; + let key = ( + exe.to_path_buf(), + subcommand.to_owned(), + meta.modified().ok(), + meta.len(), + ); + let answers = ANSWERS.get_or_init(Default::default); + if let Some(answer) = answers.lock().unwrap().get(&key) { + return answer.clone(); + } + let answer = victory_help_uncached(exe, subcommand); + answers.lock().unwrap().insert(key, answer.clone()); + answer +} + +fn victory_help_uncached(exe: &Path, subcommand: &str) -> Option { let mut command = Command::new(exe); command.args([subcommand, "--help"]); crate::runner::adapt(&mut command); @@ -4115,6 +4144,56 @@ fn fix_graphics( )) } +/// Windows' commit (RAM and page file) ran out: Series S and the memory saver, which ask +/// Windows for less. The render scale, output and texture fix stay: they are for the card's +/// memory, which had room. The page file is the player's to change (the finding says how). +fn fix_commit(job: &Arc>, p: &Project, l: &mut Launch) -> Result { + let before = l.graphics; + let mut g = before; + g.series_s = true; + g.memory = g.memory.max(MemorySaver::Light); + if g == before { + return Ok(format!( + "The settings were already light (Series S, memory saver {:?}).", + g.memory + )); + } + l.graphics = g; + l.series_s = g.series_s; + if g.memory != before.memory { + // This run's switches were made from the old level: add the new one's (later lines win). + l.extra.push_str(&g.memory.lines()); + } + job.lock().unwrap().adjusted_graphics = Some((p.repo.clone(), g)); + Ok(format!( + "Series S, memory saver {:?}; render scale {:.2} and output {:?} kept; saved for the next Play.", + g.memory, g.render_scale, g.output + )) +} + +#[test] +fn the_commit_fix_keeps_the_picture_and_lightens_memory() { + let job = Arc::new(Mutex::new(Job::default())); + let mut launch = test_launch(std::env::temp_dir()); + launch.series_s = false; + launch.graphics.series_s = false; + launch.graphics.render_scale = 0.75; + launch.graphics.output = OutputResolution::P1440; + launch.graphics.memory = MemorySaver::Normal; + let done = fix_commit(&job, &test_project(), &mut launch).unwrap(); + assert!(done.contains("Series S"), "{done}"); + let g = launch.graphics; + assert!(g.series_s && launch.series_s); + assert_eq!(g.memory, MemorySaver::Light); + assert_eq!(g.render_scale, 0.75); + assert_eq!(g.output, OutputResolution::P1440); + assert!(job.lock().unwrap().adjusted_graphics.is_some()); + // Run again: nothing more to change. + assert!(fix_commit(&job, &test_project(), &mut launch) + .unwrap() + .contains("already")); +} + fn open_driver_page(vendor: Option<&str>) -> Result { let url = match vendor { Some("nvidia") => "https://www.nvidia.com/Download/index.aspx", @@ -4171,6 +4250,7 @@ fn apply_finding( diagnose::FIX_PERMISSIONS => fix_permissions(p), diagnose::FIX_DISK => fix_disk(p, job), diagnose::FIX_GRAPHICS_MEMORY => fix_graphics(job, p, l, true), + diagnose::FIX_COMMIT_MEMORY => fix_commit(job, p, l), diagnose::FIX_GRAPHICS_DEVICE => fix_graphics(job, p, l, false), diagnose::FIX_DRIVER_PAGE => open_driver_page(l.gpu_vendor), diagnose::FIX_REPO_SWITCH => fix_repo_switch(job, p, l, finding.data.as_deref()), @@ -4209,7 +4289,7 @@ fn run_fixes( data: &data, cache: &cache, last_log: &last_log, - switches: &l.extra, + switches: &check_switches(l, starts_native(&exe, l)), installed: true, game_ok: game_files_ok(&l.game_dir), unplugged: !drive_connected(&l.game_dir), @@ -4358,6 +4438,13 @@ fn native_nvidia_args(l: &Launch, help: &str) -> Result<(Vec, Vec Option<(u32, u32)> { + if cfg!(test) { + None + } else { + crate::platform::primary_screen() + } +} + +fn native_size_for_screen(screen: Option<(u32, u32)>) -> Option<&'static str> { + let (w, h) = screen?; + if w == 0 || h == 0 { + return None; + } + let off = (u64::from(w) * 9).abs_diff(u64::from(h) * 16) * 100 > u64::from(h) * 16; + off.then_some("2560x1440") +} + +#[test] +fn a_screen_that_is_not_16_9_gets_the_old_picture_size() { + for screen in [(2560, 1440), (1920, 1080), (3840, 2160), (1366, 768)] { + assert_eq!(native_size_for_screen(Some(screen)), None, "{screen:?}"); + } + for screen in [ + (3440, 1440), + (5120, 1440), + (2560, 1600), + (1920, 1200), + (1280, 800), + ] { + assert_eq!( + native_size_for_screen(Some(screen)), + Some("2560x1440"), + "{screen:?}" + ); + } + assert_eq!(native_size_for_screen(None), None); +} + +/// The memory saver on VIctory-NVIDIA (`victory play`). That build sizes its own pools for a +/// PC under 24 GB of RAM and a card of 8 GB or less, so the launcher only adds what its +/// docs/windows-memory.md measured against the crashes the saver is for: +/// - Light and up: two pipeline workers. Each compile asks the driver for commit; a 32 GB PC +/// with 8 workers' worth of compiles reached the Windows commit limit and closed, with two +/// it loaded past that point (the default is up to 8 on a PC with 32 GB or less). +/// - Very light: the VRAM kept for render targets that may come later, lowered from its +/// 2,560 MiB (8 GB card) default to 768 MiB and given back once the targets settle (8 s): +/// with the default it was never given back on Series S, where targets stay under 1.5 GiB. +fn native_memory_switches(memory: MemorySaver) -> &'static [(&'static str, &'static str)] { + match memory { + MemorySaver::Normal => &[], + MemorySaver::Light => &[("VICTORY_PIPELINE_WORKERS", "2")], + MemorySaver::VeryLight => &[ + ("VICTORY_PIPELINE_WORKERS", "2"), + ("VICTORY_CARD_ROOM_FOR_TARGETS_MB", "768"), + ("VICTORY_CARD_ROOM_FOR_TARGETS_SETTLE_MS", "8000"), + ], + } +} + +#[test] +fn memory_saver_on_native_play_sends_switches_the_build_reads() { + let root = + std::env::temp_dir().join(format!("vilauncher-nvidia-memory-{}", std::process::id())); + let mut launch = test_launch(root.clone()); + let set = |launch: &Launch| -> Vec { + let command = native_nvidia_command( + &root.join("victory.exe"), + &root, + &test_project(), + launch, + &[], + ); + command + .get_args() + .map(|arg| arg.to_string_lossy().into_owned()) + .filter(|arg| arg.starts_with("VICTORY_")) + .collect() + }; + launch.graphics.memory = MemorySaver::Normal; + assert!(!set(&launch) + .iter() + .any(|a| a.starts_with("VICTORY_PIPELINE_WORKERS"))); + launch.graphics.memory = MemorySaver::Light; + let light = set(&launch); + assert!(light.contains(&"VICTORY_PIPELINE_WORKERS=2".to_string())); + assert!(!light + .iter() + .any(|a| a.starts_with("VICTORY_CARD_ROOM_FOR_TARGETS"))); + launch.graphics.memory = MemorySaver::VeryLight; + let very = set(&launch); + assert!(very.contains(&"VICTORY_CARD_ROOM_FOR_TARGETS_MB=768".to_string())); + // The player's own value wins. + launch.extra = "VICTORY_PIPELINE_WORKERS=4".into(); + let own = set(&launch); + assert!(own.contains(&"VICTORY_PIPELINE_WORKERS=4".to_string())); + assert!(!own.contains(&"VICTORY_PIPELINE_WORKERS=2".to_string())); +} + +/// Whether a start of `exe` with `l` goes through the build's own `victory play`, as [`play`] +/// decides it: the build offers it, and `play` takes this start's launch arguments. +fn starts_native(exe: &Path, l: &Launch) -> bool { + victory_help(exe, "play") + .filter(|help| has_native_play(help)) + .is_some_and(|help| native_nvidia_args(l, &help).is_ok()) +} + +/// The switches a start sends, as the checks read them: the player's and the fixes' lines, +/// and, on a start through `victory play` (`native`), the memory saver's that only that start +/// sends, so advice already in effect is not offered and advice that is not still is. +fn check_switches(l: &Launch, native: bool) -> String { + let mut text = l.extra.clone(); + if native { + for (key, value) in native_memory_switches(l.graphics.memory) { + text.push_str(&format!("\n{key}={value}")); + } + } + text +} + +#[test] +fn advice_the_memory_saver_already_sends_is_not_offered() { + let mut launch = test_launch(std::env::temp_dir()); + launch.graphics.memory = MemorySaver::Light; + let manifest = crate::known_problems::shipped().unwrap(); + let hardware = crate::known_problems::Hardware { + gpus: vec![(Some("nvidia"), "NVIDIA GeForce RTX 4060".into())], + ram_gb: Some(16.0), + os_build: None, + windows: true, + }; + let offered = |switches: &str| { + crate::known_problems::advice_for(&manifest, "owner_VIctory-NVIDIA", &hardware, switches) + .iter() + .any(|entry| entry.id == "victory-nvidia-commit-pipeline-workers") + }; + // Through `victory play` the saver sends it: not offered. + assert!(!offered(&check_switches(&launch, true))); + // Through `run` (no native play, or a launch argument it does not take) it is not sent. + assert!(offered(&check_switches(&launch, false))); + launch.graphics.memory = MemorySaver::Normal; + assert!(offered(&check_switches(&launch, true))); + // A program that is not there has no native play. + assert!(!starts_native( + &std::env::temp_dir().join("no-such-victory.exe"), + &launch + )); +} + +#[test] +fn the_players_value_wins_over_the_memory_saver_also_when_it_is_the_presets() { + let root = + std::env::temp_dir().join(format!("vilauncher-nvidia-preset-{}", std::process::id())); + std::fs::create_dir_all(root.join("scripts")).unwrap(); + std::fs::write( + root.join("scripts/play-foxhound.ps1"), + "$settings = @{ +VICTORY_PIPELINE_WORKERS = '4' +}", + ) + .unwrap(); + let mut launch = test_launch(root.clone()); + launch.foxhound_preset = true; + launch.graphics.memory = MemorySaver::Light; + launch.extra = "VICTORY_PIPELINE_WORKERS=4".into(); + let command = native_nvidia_command( + &root.join("victory.exe"), + &root, + &test_project(), + &launch, + &[], + ); + let args: Vec<_> = command + .get_args() + .map(|a| a.to_string_lossy().into_owned()) + .collect(); + assert!( + !args.iter().any(|a| a == "VICTORY_PIPELINE_WORKERS=2"), + "{args:?}" + ); + let _ = std::fs::remove_dir_all(root); +} + fn native_nvidia_command( exe: &Path, root: &Path, @@ -4435,6 +4712,8 @@ fn native_nvidia_command( .arg("play") .arg(l.game_dir.join(EXE_NAME)); let mut switches = std::collections::BTreeMap::new(); + // Every switch the player's lines name, also one left out below for equalling the preset's. + let mut named = std::collections::BTreeSet::new(); switches.insert("VICTORY_FULLSCREEN", if l.fullscreen { "1" } else { "0" }); for (key, value) in l.extra.lines().filter_map(|line| line.split_once('=')) { let (key, value) = (key.trim(), value.trim()); @@ -4445,6 +4724,7 @@ fn native_nvidia_command( ) && !key.starts_with("VICTORY_MENU_") { + named.insert(key); if defaults.get(key).copied() == Some(value) { switches.remove(key); } else { @@ -4452,6 +4732,18 @@ fn native_nvidia_command( } } } + // The memory saver's own switches are mostly KLBF Lab's, which this build does not read. + // These are the ones it does read for the same need; a player's own value wins. + for (key, value) in native_memory_switches(l.graphics.memory) { + if !named.contains(key) { + switches.insert(key, value); + } + } + if !named.contains("VICTORY_NATIVE_SIZE") { + if let Some(size) = native_size_for_screen(screen_for_native_size()) { + switches.insert("VICTORY_NATIVE_SIZE", size); + } + } // `victory play` puts `--set` over what the F1 menu saved, so a switch the player // chose in F1 would be undone at every start: those are left to the menu. let saved = victory_menu_file() @@ -4627,6 +4919,11 @@ fn play( } }, }; + // A build started through its own `play` applies the F1 menu's choices itself and restarts + // itself for those that need it; it also drops every switch given as an environment + // variable (play.rs's KEPT). The launcher's F1 watcher, which closes the game whenever the + // menu's file changes, would close it at every F1 change, even one applied at once. + let native_start = native.is_some(); let mut c = if let Some(command) = native { job.lock() .unwrap() @@ -4665,7 +4962,7 @@ fn play( job.lock().unwrap().stoppable = true; job.lock().unwrap().last_log.clear(); let _ = std::fs::remove_file(project_state(&p.repo).join("last-run.txt")); - let result = run_until_f1_restart(job, ctx, &mut c, l, |pid| { + let spawned = |pid| { record_play_spawn(job, p, pid); if p.local_exe.is_none() { if let Err(error) = build_activity::BuildActivity::record_run(&target_dir(&p.repo)) { @@ -4678,7 +4975,12 @@ fn play( if fullscreen { fullscreen::keep_borderless(pid); } - }); + }; + let result = if native_start { + run_with(job, ctx, &mut c, spawned) + } else { + run_until_f1_restart(job, ctx, &mut c, l, spawned) + }; // The player's Stop is not a crash: nothing is reported for it. let stopped = { let mut j = job.lock().unwrap(); diff --git a/src-tauri/src/launcher/actions.rs b/src-tauri/src/launcher/actions.rs index 63e4b37..e4b6f85 100644 --- a/src-tauri/src/launcher/actions.rs +++ b/src-tauri/src/launcher/actions.rs @@ -268,6 +268,19 @@ pub(crate) enum Action { ImportSaveZip { path: String, }, + /// Copies a DLL into VIctory-NVIDIA's mods folder (mods.rs), on. + ModAdd { + path: String, + }, + /// Turns a mod in the mods folder on or off, by its name there (`x.dll` or `x.dll.off`). + ModSetOn { + entry: String, + on: bool, + }, + /// Deletes a mod from the mods folder, by its name there. + ModRemove { + entry: String, + }, ExportSave { source: String, path: String, @@ -957,6 +970,17 @@ impl App { ("workspace", _) => workspace(), ("cache", _) => cache_root(), ("saves", _) => shared_saves().unwrap_or_else(|| workspace().join("data")), + ("mods", _) => crate::mods::folder().ok_or(NO_MODS)?, + // The game's own mouse and keyboard keys: its file is shown where it is. + ("bindings", _) => { + let home = crate::mods::victory_home().ok_or(NO_MODS)?; + let file = home.join("bindings.ini"); + if file.is_file() { + reveal(&file)?; + return Ok(Outcome::Value(Value::Null)); + } + home + } ("update", _) => match &self.updater.state { updater::State::Downloaded(update) => update .path @@ -1023,6 +1047,20 @@ impl App { .map_err(|error| msg!("Could not import the save: {error}"))?; json!(name) } + Action::ModAdd { path } => { + let folder = crate::mods::folder().ok_or(NO_MODS)?; + json!(crate::mods::add(&folder, Path::new(&path))?) + } + Action::ModSetOn { entry, on } => { + let folder = crate::mods::folder().ok_or(NO_MODS)?; + crate::mods::set_on(&folder, &entry, on)?; + Value::Null + } + Action::ModRemove { entry } => { + let folder = crate::mods::folder().ok_or(NO_MODS)?; + crate::mods::remove(&folder, &entry)?; + Value::Null + } Action::ExportSave { source, path } => { let destination = PathBuf::from(path); let destination = if destination.extension().is_none() { @@ -1411,6 +1449,9 @@ fn open_link(url: &str) -> Result<(), String> { crate::platform::open_url(url) } +/// VIctory-NVIDIA loads its mods with LoadLibrary: there is a mods folder on Windows only. +const NO_MODS: &str = msg_str!("Mods are loaded on Windows only: this PC has no mods folder."); + fn open_folder(path: &Path) -> Result<(), String> { crate::platform::open_folder(path) } diff --git a/src-tauri/src/launcher/view.rs b/src-tauri/src/launcher/view.rs index 3dc5a2d..2c6c75a 100644 --- a/src-tauri/src/launcher/view.rs +++ b/src-tauri/src/launcher/view.rs @@ -82,6 +82,26 @@ fn controller_keys_view(saved: &super::Saved) -> ControllerKeysView { } } +/// VIctory-NVIDIA's mods folder (mods.rs) and what is in it. None where there is none (off +/// Windows). +#[derive(Serialize)] +pub(crate) struct ModsView { + folder: String, + items: Vec, + /// `bindings.ini`, the game's own mouse and keyboard keys, is in the runtime's home. + bindings: bool, +} + +fn mods_view() -> Option { + let home = crate::mods::victory_home()?; + let folder = home.join("mods"); + Some(ModsView { + items: crate::mods::list(&folder), + folder: folder.display().to_string(), + bindings: home.join("bindings.ini").is_file(), + }) +} + impl super::App { /// The advice that applies to a project on this PC now (known_problems.rs). fn advice_for(&self, repo: &str, switches: &str) -> Vec { @@ -237,6 +257,7 @@ struct SettingsView { skip_update_warning: bool, agent_access: bool, controller_keys: ControllerKeysView, + mods: Option, acknowledged: Vec, /// The player's language choice; none: the system's. language: Option, @@ -445,6 +466,7 @@ impl App { skip_update_warning: self.saved.skip_update_warning, agent_access: self.saved.agent_access, controller_keys: controller_keys_view(&self.saved), + mods: mods_view(), acknowledged: self.saved.acknowledged.clone(), language: self.saved.language.clone(), }, diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 9fa1683..227df84 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -20,6 +20,7 @@ mod fullscreen; mod job_log; mod known_problems; mod launcher; +mod mods; mod notify; mod patches; mod platform; diff --git a/src-tauri/src/mods.rs b/src-tauri/src/mods.rs new file mode 100644 index 0000000..3a80d9e --- /dev/null +++ b/src-tauri/src/mods.rs @@ -0,0 +1,286 @@ +//! The mods folder of VIctory-NVIDIA (PR #1892, release v2026.11.29.01 on). +//! +//! At every start, `victory` loads each `*.dll` in `\mods`, by name, before the title runs; +//! `` is `VICTORY_HOME`, else `%LOCALAPPDATA%\victory` (the same home as the F1 menu's +//! `victory-settings.txt`). The folder is the runtime's, so it is shared by every build of it. +//! Here the player can see what is in it, add a DLL, turn one off (renamed to `.dll.off`, +//! which the runtime does not load), turn it on again, or remove it. Mods load with +//! `LoadLibrary`, so the folder is a Windows one; elsewhere there is none. +//! +//! A mod is native code run inside the game with the player's rights. The launcher only moves +//! files: it never downloads a mod, and it never runs one itself. + +use std::path::{Path, PathBuf}; + +/// The suffix a turned-off mod gets after `.dll`. +const OFF: &str = ".off"; + +/// One mod in the folder. +#[derive(Clone, Debug, PartialEq, serde::Serialize)] +pub(crate) struct Mod { + /// The DLL's name as the runtime loads it (`example.dll`), also when it is off. + pub file: String, + /// Its name in the folder now (`example.dll`, or `example.dll.off` when off). The actions + /// take it, so a mod that is there both on and off is two rows, each acting on its own file. + pub entry: String, + pub on: bool, + pub bytes: u64, +} + +/// The runtime's home: `VICTORY_HOME`, else `%LOCALAPPDATA%\victory`. None off Windows, in +/// tests (they never touch the player's own), and with neither variable. +pub(crate) fn victory_home() -> Option { + if cfg!(test) || !cfg!(windows) { + return None; + } + std::env::var_os("VICTORY_HOME") + .filter(|home| !home.is_empty()) + .map(PathBuf::from) + .or_else(|| std::env::var_os("LOCALAPPDATA").map(|dir| PathBuf::from(dir).join("victory"))) +} + +/// The mods folder (it may not exist yet). +pub(crate) fn folder() -> Option { + victory_home().map(|home| home.join("mods")) +} + +/// The DLL name of a folder entry, and whether it is on: `x.dll` on, `x.dll.off` off. +fn parse_name(name: &str) -> Option<(String, bool)> { + let lower = name.to_ascii_lowercase(); + if lower.ends_with(".dll") && name.len() > 4 { + return Some((name.to_owned(), true)); + } + if lower.ends_with(".dll.off") && name.len() > 8 { + return Some((name[..name.len() - OFF.len()].to_owned(), false)); + } + None +} + +/// Every mod in `dir`, by name (the order the runtime loads them in), the one on first when a +/// name is there twice. A folder that does not exist has none. +pub(crate) fn list(dir: &Path) -> Vec { + let Ok(entries) = std::fs::read_dir(dir) else { + return Vec::new(); + }; + let mut mods: Vec = entries + .flatten() + .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_file())) + .filter_map(|entry| { + let name = entry.file_name().to_string_lossy().into_owned(); + let (file, on) = parse_name(&name)?; + let bytes = entry.metadata().map(|m| m.len()).unwrap_or(0); + Some(Mod { + file, + entry: name, + on, + bytes, + }) + }) + .collect(); + mods.sort_by(|a, b| a.file.cmp(&b.file).then(b.on.cmp(&a.on))); + mods +} + +/// A plain file name of a DLL: no folder, no `..`, ends in `.dll`. +fn checked_name(file: &str) -> Result<&str, String> { + let plain = !file.is_empty() + && !file.contains(['/', '\\', ':']) + && file != "." + && file != ".." + && Path::new(file).file_name().is_some_and(|name| name == file); + if !plain || !file.to_ascii_lowercase().ends_with(".dll") || file.len() <= 4 { + return Err(msg!("{file} is not the name of a mod DLL.")); + } + Ok(file) +} + +/// Whether a mod named `file` is in `dir`, on or off. +fn present(dir: &Path, file: &str) -> bool { + dir.join(file).is_file() || dir.join(format!("{file}{OFF}")).is_file() +} + +/// A folder entry the window names (`x.dll` or `x.dll.off`): its DLL name, whether it is on, +/// and its path. Err for a name with a folder in it, another kind of file, or one not there. +fn checked_entry(dir: &Path, entry: &str) -> Result<(String, bool, PathBuf), String> { + let parsed = parse_name(entry).filter(|(file, _)| checked_name(file).is_ok()); + let Some((file, on)) = parsed else { + return Err(msg!("{file} is not the name of a mod DLL.", file = entry)); + }; + let path = dir.join(entry); + if !path.is_file() { + return Err(msg!("The mod {file} is not in the mods folder.")); + } + Ok((file, on, path)) +} + +/// Turns the mod at folder entry `entry` on or off. Nothing changes when it already is. +pub(crate) fn set_on(dir: &Path, entry: &str, on: bool) -> Result<(), String> { + let (file, is_on, path) = checked_entry(dir, entry)?; + if is_on == on { + return Ok(()); + } + let to = if on { + dir.join(&file) + } else { + dir.join(format!("{file}{OFF}")) + }; + if to.exists() { + return Err(msg!( + "{file} is in the mods folder twice (on and off): remove one." + )); + } + std::fs::rename(&path, &to).map_err(|e| msg!("Could not rename {file}: {e}")) +} + +/// Copies the DLL at `source` into `dir`, on. Refuses another file kind, and a name already +/// there (on or off), so a mod is never overwritten. Returns the name it has there. +pub(crate) fn add(dir: &Path, source: &Path) -> Result { + let file = source + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + checked_name(&file)?; + if !source.is_file() { + return Err(msg!("{file} is not a file.")); + } + if present(dir, &file) { + return Err(msg!("A mod named {file} is already in the mods folder.")); + } + std::fs::create_dir_all(dir).map_err(|e| msg!("Could not make the mods folder: {e}"))?; + std::fs::copy(source, dir.join(&file)).map_err(|e| msg!("Could not copy {file}: {e}"))?; + Ok(file) +} + +/// Deletes the folder entry `entry` (a mod, on or off) from `dir`. +pub(crate) fn remove(dir: &Path, entry: &str) -> Result<(), String> { + let (file, _, path) = checked_entry(dir, entry)?; + std::fs::remove_file(&path).map_err(|e| msg!("Could not remove {file}: {e}")) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp(name: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("vilauncher-mods-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn one(file: &str, entry: &str, on: bool, bytes: u64) -> Mod { + Mod { + file: file.into(), + entry: entry.into(), + on, + bytes, + } + } + + #[test] + fn lists_on_and_off_mods_by_name_and_nothing_else() { + let dir = temp("list"); + std::fs::write(dir.join("b.dll"), b"bb").unwrap(); + std::fs::write(dir.join("A.DLL.off"), b"a").unwrap(); + std::fs::write(dir.join("notes.txt"), b"").unwrap(); + std::fs::write(dir.join(".dll"), b"").unwrap(); + std::fs::create_dir(dir.join("folder.dll")).unwrap(); + assert_eq!( + list(&dir), + vec![ + one("A.DLL", "A.DLL.off", false, 1), + one("b.dll", "b.dll", true, 2) + ] + ); + assert!(list(&dir.join("missing")).is_empty()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn turning_off_renames_so_the_runtime_skips_it_and_on_brings_it_back() { + let dir = temp("toggle"); + std::fs::write(dir.join("x.dll"), b"x").unwrap(); + set_on(&dir, "x.dll", false).unwrap(); + assert!(!dir.join("x.dll").exists() && dir.join("x.dll.off").is_file()); + // The runtime loads files whose extension is dll: this one's is "off". + assert_eq!(Path::new("x.dll.off").extension().unwrap(), "off"); + set_on(&dir, "x.dll.off", false).unwrap(); + set_on(&dir, "x.dll.off", true).unwrap(); + assert!(dir.join("x.dll").is_file() && !dir.join("x.dll.off").exists()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_mod_there_on_and_off_is_two_rows_each_acting_on_its_own_file() { + let dir = temp("twice"); + std::fs::write(dir.join("x.dll"), b"new").unwrap(); + std::fs::write(dir.join("x.dll.off"), b"old").unwrap(); + let rows = list(&dir); + assert_eq!( + rows, + vec![ + one("x.dll", "x.dll", true, 3), + one("x.dll", "x.dll.off", false, 3) + ] + ); + // Neither copy overwrites the other. + assert!(set_on(&dir, "x.dll.off", true).is_err()); + assert!(set_on(&dir, "x.dll", false).is_err()); + // Removing the off row removes the off copy, never the one that loads. + remove(&dir, "x.dll.off").unwrap(); + assert_eq!(std::fs::read(dir.join("x.dll")).unwrap(), b"new"); + assert!(!dir.join("x.dll.off").exists()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn adds_a_dll_without_overwriting_and_removes_it() { + let dir = temp("add"); + let from = temp("add-source"); + std::fs::write(from.join("m.dll"), b"mod").unwrap(); + std::fs::write(from.join("m.exe"), b"no").unwrap(); + let mods = dir.join("mods"); + assert_eq!(add(&mods, &from.join("m.dll")).unwrap(), "m.dll"); + assert_eq!(std::fs::read(mods.join("m.dll")).unwrap(), b"mod"); + assert!(add(&mods, &from.join("m.dll")).is_err(), "already there"); + set_on(&mods, "m.dll", false).unwrap(); + assert!( + add(&mods, &from.join("m.dll")).is_err(), + "already there, off" + ); + assert!(add(&mods, &from.join("m.exe")).is_err(), "not a DLL"); + remove(&mods, "m.dll.off").unwrap(); + assert!(list(&mods).is_empty()); + assert!(remove(&mods, "m.dll").is_err()); + std::fs::remove_dir_all(dir).unwrap(); + std::fs::remove_dir_all(from).unwrap(); + } + + #[test] + fn names_with_folders_are_refused() { + let dir = temp("names"); + std::fs::create_dir(dir.join("sub")).unwrap(); + std::fs::write(dir.join("sub").join("x.dll"), b"x").unwrap(); + for bad in [ + "../x.dll", + "sub/x.dll", + "sub\\x.dll", + "C:x.dll", + "x.exe", + ".dll", + ".dll.off", + "", + ] { + assert!(set_on(&dir, bad, false).is_err(), "{bad}"); + assert!(remove(&dir, bad).is_err(), "{bad}"); + } + assert!(dir.join("sub").join("x.dll").is_file()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn tests_never_see_the_players_own_folder() { + assert!(folder().is_none()); + } +} diff --git a/src/dev/mock.ts b/src/dev/mock.ts index 2316c64..e865262 100644 --- a/src/dev/mock.ts +++ b/src/dev/mock.ts @@ -59,6 +59,13 @@ const state = { agentAccess: false, controllerKeysOn: false, controllerBindings: {} as Record, + // VIctory-NVIDIA's mods folder, by name there: "x.dll" on, "x.dll.off" off (?mods=0: empty). + mods: (params.get("mods") === "0" + ? [] + : [ + { entry: "fps-overlay.dll", bytes: 412_160 }, + { entry: "photo-mode.dll.off", bytes: 1_284_096 }, + ]) as { entry: string; bytes: number }[], acknowledged: [] as ResponsibilityId[], macRunner: { kind: "none", bottle: "", wine: "", prefix: "", metalfx: false, streamline_dir: "" } as MacRunnerChoice, // ?lang=zh-TW starts in that language, as if the player had chosen it. @@ -177,6 +184,17 @@ function snapshot(): Snapshot { on: state.controllerKeysOn, controls: CONTROLLER_CONTROLS.map((c) => ({ ...c, key: state.controllerBindings[c.id] ?? c.default_key })), }, + // As the launcher: the mods folder is a Windows one. + mods: + platform !== "windows" + ? null + : { + folder: "C:\\Users\\you\\AppData\\Local\\victory\\mods", + items: state.mods + .map((m) => ({ file: m.entry.replace(/\.off$/i, ""), entry: m.entry, on: !/\.off$/i.test(m.entry), bytes: m.bytes })) + .sort((a, b) => a.file.localeCompare(b.file) || Number(b.on) - Number(a.on)), + bindings: true, + }, acknowledged: state.acknowledged, language: state.language, }, @@ -398,6 +416,28 @@ async function act(a: Action): Promise { state.controllerBindings[a.control] = a.key break } + case "mod_add": { + const file = a.path.split(/[\\/]/).pop() ?? "" + if (!/\.dll$/i.test(file) || file.length <= 4) throw new Error(`${file} is not the name of a mod DLL.`) + const taken = (name: string) => state.mods.some((m) => m.entry.toLowerCase() === name.toLowerCase()) + if (taken(file) || taken(`${file}.off`)) throw new Error(`A mod named ${file} is already in the mods folder.`) + state.mods = [...state.mods, { entry: file, bytes: 256_000 }] + return file + } + case "mod_set_on": { + const mod = state.mods.find((m) => m.entry === a.entry) + if (!mod) throw new Error(`The mod ${a.entry} is not in the mods folder.`) + const file = mod.entry.replace(/\.off$/i, "") + const to = a.on ? file : `${file}.off` + if (to === mod.entry) break + if (state.mods.some((m) => m.entry.toLowerCase() === to.toLowerCase())) throw new Error(`${file} is in the mods folder twice (on and off): remove one.`) + mod.entry = to + break + } + case "mod_remove": + if (!state.mods.some((m) => m.entry === a.entry)) throw new Error(`The mod ${a.entry} is not in the mods folder.`) + state.mods = state.mods.filter((m) => m.entry !== a.entry) + break case "acknowledge": if (!state.acknowledged.includes(a.id)) state.acknowledged = [...state.acknowledged, a.id] break diff --git a/src/features/settings/controller-keys.tsx b/src/features/settings/controller-keys.tsx index bfb7328..bae53c8 100644 --- a/src/features/settings/controller-keys.tsx +++ b/src/features/settings/controller-keys.tsx @@ -76,7 +76,7 @@ export function ControllerKeysGroup() { ) : undefined } > - + void run({ type: "set_controller_keys", on })} diff --git a/src/features/settings/mods.tsx b/src/features/settings/mods.tsx new file mode 100644 index 0000000..358e984 --- /dev/null +++ b/src/features/settings/mods.tsx @@ -0,0 +1,96 @@ +import { useState } from "react" +import { toast } from "sonner" +import { FileText, FolderOpen, Plus, Trash2 } from "lucide-react" +import { Button } from "@/components/ui/button" +import { Group, Row } from "@/components/ui/group" +import { Switch } from "@/components/ui/switch" +import { formatBytes, useT } from "@/i18n" +import { pickFile } from "@/lib/api" +import { run, useStore } from "@/lib/store" + +/** + * VIctory-NVIDIA's mods folder (src-tauri/src/mods.rs): every DLL in it loads at each start. + * Off renames a mod so the game skips it; remove asks once in the row. Below, where the + * game's own mouse and keyboard controls are, which replaced the launcher's keyboard hook. + */ +export function ModsGroups() { + const t = useT() + const mods = useStore((s) => s.snap)!.settings.mods + // Screenshot mode hides paths: the folder's has the player's Windows user name. + const screenshot = useStore((s) => s.screenshot) + const [removing, setRemoving] = useState(null) + if (!mods) return null + + const add = async () => { + const path = await pickFile(t("settings.mods.pickTitle"), [{ name: t("settings.mods.filterName"), extensions: ["dll"] }]) + if (!path) return + const file = await run({ type: "mod_add", path }) + if (file) toast.success(t("settings.mods.added", { file })) + } + + return ( + <> + void add()}> + {t("settings.mods.add")} + + } + > + {mods.folder}}> + + + {mods.items.length === 0 && {t("settings.mods.empty")}} />} + {mods.items.map((mod) => ( + {mod.file}} + hint={mod.on ? formatBytes(mod.bytes) : `${formatBytes(mod.bytes)} · ${t("settings.mods.offHint")}`} + > + {removing === mod.entry ? ( + <> + + + + ) : ( + <> + + void run({ type: "mod_set_on", entry: mod.entry, on })} + aria-label={t("settings.mods.load", { file: mod.file })} + /> + + )} + + ))} + +

{t("settings.mods.warning")}

+ + + + + + + + ) +} diff --git a/src/features/settings/settings-view.tsx b/src/features/settings/settings-view.tsx index 822df60..e589a60 100644 --- a/src/features/settings/settings-view.tsx +++ b/src/features/settings/settings-view.tsx @@ -8,6 +8,7 @@ import { Spinner } from "@/components/ui/spinner" import { Switch } from "@/components/ui/switch" import { GraphicsGroups } from "@/features/library/graphics-tab" import { ControllerKeysGroup } from "@/features/settings/controller-keys" +import { ModsGroups } from "@/features/settings/mods" import { MacRunnerGroup, MetalfxRows } from "@/features/settings/mac-runner" import { LanguageSelect } from "@/features/shared/language-select" import { ResponsibilityDialog } from "@/features/shared/responsibility" @@ -191,6 +192,9 @@ export function SettingsView() { )} + {/* VIctory-NVIDIA's mods folder and controls: a Windows folder, so none elsewhere. */} + + diff --git a/src/i18n/messages/en/settings.ts b/src/i18n/messages/en/settings.ts index cb01238..8d5d87d 100644 --- a/src/i18n/messages/en/settings.ts +++ b/src/i18n/messages/en/settings.ts @@ -139,6 +139,7 @@ export default { description: "VIctory reads a controller from the keyboard when no controller is plugged in. Give any of its controls another key here.", on: "Use the keyboard as a controller", onHint: "Off by default. A keyboard hook runs only while victory.exe is in front, and sends the game's own key for the control whose key you press.", + ownKeyboard: "VIctory-NVIDIA builds with their own mouse and keyboard (F1, MOUSE AND KEYBOARD) are left alone, so keys are never remapped twice.", change: "Change", press: "Press a key, or Esc to cancel", reset: "Reset", @@ -155,6 +156,29 @@ export default { left_trigger: "Left trigger", right_trigger: "Right trigger", }, }, + mods: { + title: "Mods & controls", + description: "VIctory-NVIDIA (v2026.11.29.01 and later) loads every DLL in its mods folder at each start, before the game runs. Every build of it shares this folder.", + warning: "A mod is a program that runs inside the game with your rights. Only add DLLs from people you trust.", + folder: "Mods folder", + add: "Add a mod…", + pickTitle: "Choose a mod DLL", + filterName: "Mod DLL", + added: "{file} added. It loads at the next start.", + empty: "No mods yet. Add a DLL, or put one in the folder.", + load: "Load {file}", + offHint: "Off: kept in the folder, not loaded.", + remove: "Remove", + removeConfirm: "Remove {file}", + keep: "Keep", + removed: "{file} removed.", + controlsTitle: "Mouse, keyboard and controllers", + controlsDescription: "VIctory-NVIDIA reads controllers itself, generic USB pads too beside Xbox and PlayStation ones, and has its own mouse and keyboard controls. Other builds use the controller keys.", + mnk: "Mouse and keyboard", + mnkHint: "Turn it on in the game: press F1, then MOUSE AND KEYBOARD. Its keys are in bindings.ini, and KEY BINDINGS in the same menu changes them while you play.", + openBindings: "Show bindings.ini", + noBindings: "bindings.ini is written the first time mouse and keyboard is on.", + }, updates: { title: "Updates", available: "{tag} is available", diff --git a/src/i18n/messages/es/settings.ts b/src/i18n/messages/es/settings.ts index df12b67..61347f1 100644 --- a/src/i18n/messages/es/settings.ts +++ b/src/i18n/messages/es/settings.ts @@ -141,6 +141,7 @@ export default { description: "VIctory lee un mando desde el teclado cuando no hay ningún mando conectado. Asigna aquí otra tecla a cualquiera de sus controles.", on: "Usar el teclado como mando", onHint: "Desactivado por defecto. Un hook de teclado solo se ejecuta mientras victory.exe esté en primer plano y envía la tecla propia del juego para el control cuya tecla pulses.", + ownKeyboard: "Las compilaciones de VIctory-NVIDIA con su propio ratón y teclado (F1, MOUSE AND KEYBOARD) no se tocan, así que las teclas nunca se reasignan dos veces.", change: "Cambiar", press: "Pulsa una tecla, o Esc para cancelar", reset: "Restablecer", @@ -157,6 +158,29 @@ export default { left_trigger: "Gatillo izquierdo", right_trigger: "Gatillo derecho", }, }, + mods: { + title: "Mods y controles", + description: "VIctory-NVIDIA (v2026.11.29.01 y posteriores) carga cada DLL de su carpeta de mods en cada inicio, antes de que corra el juego. Todas sus compilaciones comparten esta carpeta.", + warning: "Un mod es un programa que corre dentro del juego con tus permisos. Añade solo DLL de personas en las que confíes.", + folder: "Carpeta de mods", + add: "Añadir un mod…", + pickTitle: "Elige una DLL de mod", + filterName: "DLL de mod", + added: "{file} añadido. Se carga en el próximo inicio.", + empty: "Aún no hay mods. Añade una DLL o pon una en la carpeta.", + load: "Cargar {file}", + offHint: "Desactivado: se guarda en la carpeta, no se carga.", + remove: "Quitar", + removeConfirm: "Quitar {file}", + keep: "Conservar", + removed: "{file} quitado.", + controlsTitle: "Ratón, teclado y mandos", + controlsDescription: "VIctory-NVIDIA lee los mandos por sí mismo, también los mandos USB genéricos además de los de Xbox y PlayStation, y tiene sus propios controles de ratón y teclado. Las demás compilaciones usan las teclas de mando.", + mnk: "Ratón y teclado", + mnkHint: "Actívalo en el juego: pulsa F1 y luego MOUSE AND KEYBOARD. Sus teclas están en bindings.ini, y KEY BINDINGS en el mismo menú las cambia mientras juegas.", + openBindings: "Mostrar bindings.ini", + noBindings: "bindings.ini se escribe la primera vez que se activan el ratón y el teclado.", + }, updates: { title: "Actualizaciones", available: "{tag} está disponible", diff --git a/src/i18n/messages/fr/settings.ts b/src/i18n/messages/fr/settings.ts index f8608ea..8f2b92a 100644 --- a/src/i18n/messages/fr/settings.ts +++ b/src/i18n/messages/fr/settings.ts @@ -105,6 +105,7 @@ export default { description: "VIctory lit une manette depuis le clavier quand aucune manette n’est branchée. Donnez ici une autre touche à n’importe laquelle de ses commandes.", on: "Utiliser le clavier comme manette", onHint: "Désactivé par défaut. Un hook clavier ne s’exécute que lorsque victory.exe est au premier plan, et envoie la touche propre au jeu pour la commande dont vous appuyez sur la touche.", + ownKeyboard: "Les versions de VIctory-NVIDIA qui ont leur propre souris et clavier (F1, MOUSE AND KEYBOARD) ne sont pas touchées : les touches ne sont jamais remappées deux fois.", change: "Modifier", press: "Appuyez sur une touche, ou sur Échap pour annuler", reset: "Réinitialiser", @@ -121,6 +122,29 @@ export default { left_trigger: "Gâchette gauche", right_trigger: "Gâchette droite", }, }, + mods: { + title: "Mods et commandes", + description: "VIctory-NVIDIA (v2026.11.29.01 et suivantes) charge chaque DLL de son dossier de mods à chaque démarrage, avant que le jeu ne tourne. Toutes ses versions partagent ce dossier.", + warning: "Un mod est un programme qui tourne dans le jeu avec vos droits. N’ajoutez que des DLL de personnes en qui vous avez confiance.", + folder: "Dossier des mods", + add: "Ajouter un mod…", + pickTitle: "Choisir une DLL de mod", + filterName: "DLL de mod", + added: "{file} ajouté. Il se charge au prochain démarrage.", + empty: "Aucun mod pour l’instant. Ajoutez une DLL, ou placez-en une dans le dossier.", + load: "Charger {file}", + offHint: "Désactivé : gardé dans le dossier, non chargé.", + remove: "Supprimer", + removeConfirm: "Supprimer {file}", + keep: "Garder", + removed: "{file} supprimé.", + controlsTitle: "Souris, clavier et manettes", + controlsDescription: "VIctory-NVIDIA lit les manettes lui-même, y compris les manettes USB génériques à côté des Xbox et PlayStation, et a ses propres commandes souris et clavier. Les autres versions utilisent les touches de manette.", + mnk: "Souris et clavier", + mnkHint: "Activez-les dans le jeu : appuyez sur F1, puis MOUSE AND KEYBOARD. Les touches sont dans bindings.ini, et KEY BINDINGS dans le même menu les change pendant la partie.", + openBindings: "Afficher bindings.ini", + noBindings: "bindings.ini est écrit la première fois que la souris et le clavier sont activés.", + }, updates: { title: "Mises à jour", available: "{tag} est disponible", diff --git a/src/i18n/messages/ru/settings.ts b/src/i18n/messages/ru/settings.ts index 80fb15b..11b713a 100644 --- a/src/i18n/messages/ru/settings.ts +++ b/src/i18n/messages/ru/settings.ts @@ -139,6 +139,7 @@ export default { description: "VIctory эмулирует контроллер с клавиатуры, когда геймпад не подключён. Здесь можно переназначить любую кнопку.", on: "Использовать клавиатуру как контроллер", onHint: "По умолчанию выключено. Перехват клавиш работает только когда окно victory.exe активно, и передаёт игре соответствующую кнопку контроллера.", + ownKeyboard: "Сборки VIctory-NVIDIA с собственным управлением мышью и клавиатурой (F1, MOUSE AND KEYBOARD) не затрагиваются, поэтому клавиши никогда не переназначаются дважды.", change: "Изменить", press: "Нажмите клавишу или Esc для отмены", reset: "Сбросить", @@ -155,6 +156,29 @@ export default { left_trigger: "Левый триггер (LT)", right_trigger: "Правый триггер (RT)", }, }, + mods: { + title: "Моды и управление", + description: "VIctory-NVIDIA (v2026.11.29.01 и новее) при каждом запуске загружает все DLL из своей папки модов, до запуска игры. Эту папку используют все её сборки.", + warning: "Мод — это программа, которая работает внутри игры с вашими правами. Добавляйте только DLL от тех, кому доверяете.", + folder: "Папка модов", + add: "Добавить мод…", + pickTitle: "Выберите DLL мода", + filterName: "DLL мода", + added: "{file} добавлен. Он загрузится при следующем запуске.", + empty: "Модов пока нет. Добавьте DLL или положите её в папку.", + load: "Загружать {file}", + offHint: "Выключен: остаётся в папке, но не загружается.", + remove: "Удалить", + removeConfirm: "Удалить {file}", + keep: "Оставить", + removed: "{file} удалён.", + controlsTitle: "Мышь, клавиатура и геймпады", + controlsDescription: "VIctory-NVIDIA сама читает геймпады, в том числе обычные USB-геймпады наряду с Xbox и PlayStation, и имеет собственное управление мышью и клавиатурой. Остальные сборки используют клавиши геймпада.", + mnk: "Мышь и клавиатура", + mnkHint: "Включите в игре: нажмите F1, затем MOUSE AND KEYBOARD. Клавиши хранятся в bindings.ini, а KEY BINDINGS в том же меню меняет их прямо во время игры.", + openBindings: "Показать bindings.ini", + noBindings: "bindings.ini создаётся при первом включении мыши и клавиатуры.", + }, updates: { title: "Обновления", available: "Доступна версия {tag}", diff --git a/src/i18n/messages/zh-CN/settings.ts b/src/i18n/messages/zh-CN/settings.ts index fe22814..20d8337 100644 --- a/src/i18n/messages/zh-CN/settings.ts +++ b/src/i18n/messages/zh-CN/settings.ts @@ -141,6 +141,7 @@ export default { description: "没有接上控制器时,VIctory 会从键盘读取手柄。你可以在这里为任一控制项指定另一个按键。", on: "用键盘代替控制器", onHint: "默认关闭。键盘钩子只在 victory.exe 位于最前方时运行,会把你按下的按键换成游戏本身对应该控制项的按键。", + ownKeyboard: "自带鼠标和键盘操控的 VIctory-NVIDIA 构建(F1,MOUSE AND KEYBOARD)不受影响,因此按键不会被重映射两次。", change: "更改", press: "按下按键,或按 Esc 取消", reset: "还原", @@ -157,6 +158,29 @@ export default { left_trigger: "左扳机", right_trigger: "右扳机", }, }, + mods: { + title: "模组与操控", + description: "VIctory-NVIDIA(v2026.11.29.01 及以后)每次启动时、在游戏运行之前,都会加载其模组文件夹中的每个 DLL。它的所有构建共用这个文件夹。", + warning: "模组是以你的权限在游戏内运行的程序。只添加你信任的人提供的 DLL。", + folder: "模组文件夹", + add: "添加模组…", + pickTitle: "选择模组 DLL", + filterName: "模组 DLL", + added: "已添加 {file},下次启动时加载。", + empty: "还没有模组。添加一个 DLL,或把它放进文件夹。", + load: "加载 {file}", + offHint: "已停用:保留在文件夹中,但不加载。", + remove: "移除", + removeConfirm: "移除 {file}", + keep: "保留", + removed: "已移除 {file}。", + controlsTitle: "鼠标、键盘和手柄", + controlsDescription: "VIctory-NVIDIA 会自己读取手柄,除了 Xbox 和 PlayStation 手柄,也支持通用 USB 手柄,并且有自己的鼠标和键盘操控。其他构建使用手柄按键。", + mnk: "鼠标和键盘", + mnkHint: "在游戏中开启:按 F1,然后选择 MOUSE AND KEYBOARD。按键保存在 bindings.ini 中,同一菜单里的 KEY BINDINGS 可以在游戏中修改它们。", + openBindings: "显示 bindings.ini", + noBindings: "第一次开启鼠标和键盘时会写入 bindings.ini。", + }, updates: { title: "更新", available: "{tag} 已发布", diff --git a/src/i18n/messages/zh-TW/settings.ts b/src/i18n/messages/zh-TW/settings.ts index 1f0359e..5af8875 100644 --- a/src/i18n/messages/zh-TW/settings.ts +++ b/src/i18n/messages/zh-TW/settings.ts @@ -141,6 +141,7 @@ export default { description: "沒有接上控制器時,VIctory 會從鍵盤讀取手把。你可以在這裡為任一控制項指定另一個按鍵。", on: "以鍵盤代替控制器", onHint: "預設關閉。鍵盤掛鉤只在 victory.exe 位於最前方時運作,會把你按下的按鍵送成遊戲本身對應該控制項的按鍵。", + ownKeyboard: "自帶滑鼠和鍵盤操控的 VIctory-NVIDIA 建置(F1,MOUSE AND KEYBOARD)不受影響,因此按鍵不會被重新對應兩次。", change: "變更", press: "按下按鍵,或按 Esc 取消", reset: "還原", @@ -157,6 +158,29 @@ export default { left_trigger: "左扳機", right_trigger: "右扳機", }, }, + mods: { + title: "模組與操控", + description: "VIctory-NVIDIA(v2026.11.29.01 及以後)每次啟動時、在遊戲執行之前,都會載入其模組資料夾中的每個 DLL。它的所有建置共用這個資料夾。", + warning: "模組是以你的權限在遊戲內執行的程式。只加入你信任的人提供的 DLL。", + folder: "模組資料夾", + add: "加入模組…", + pickTitle: "選擇模組 DLL", + filterName: "模組 DLL", + added: "已加入 {file},下次啟動時載入。", + empty: "還沒有模組。加入一個 DLL,或把它放進資料夾。", + load: "載入 {file}", + offHint: "已停用:保留在資料夾中,但不載入。", + remove: "移除", + removeConfirm: "移除 {file}", + keep: "保留", + removed: "已移除 {file}。", + controlsTitle: "滑鼠、鍵盤和手把", + controlsDescription: "VIctory-NVIDIA 會自己讀取手把,除了 Xbox 和 PlayStation 手把,也支援通用 USB 手把,並且有自己的滑鼠和鍵盤操控。其他建置使用手把按鍵。", + mnk: "滑鼠和鍵盤", + mnkHint: "在遊戲中開啟:按 F1,然後選擇 MOUSE AND KEYBOARD。按鍵儲存在 bindings.ini 中,同一選單裡的 KEY BINDINGS 可以在遊戲中修改它們。", + openBindings: "顯示 bindings.ini", + noBindings: "第一次開啟滑鼠和鍵盤時會寫入 bindings.ini。", + }, updates: { title: "更新", available: "{tag} 已推出", diff --git a/src/lib/types.ts b/src/lib/types.ts index 2096ea3..7a68500 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -30,6 +30,24 @@ export interface ControllerKeys { controls: ControllerControl[] } +/** One DLL in VIctory-NVIDIA's mods folder (src-tauri/src/mods.rs). */ +export interface ModEntry { + /** The name the game loads it by ("example.dll"), also while it is off. */ + file: string + /** Its name in the folder now ("example.dll", or "example.dll.off" when off): what the actions take. */ + entry: string + on: boolean + bytes: number +} + +/** VIctory-NVIDIA's mods folder: every DLL in it is loaded at each start. */ +export interface ModsView { + folder: string + items: ModEntry[] + /** The game's own mouse and keyboard keys file (bindings.ini) is there. */ + bindings: boolean +} + export interface ScriptOptions { ray_tracing: boolean probe_rays: boolean @@ -212,6 +230,8 @@ export interface Snapshot { language: string | null /** Off by default: the keyboard drives the game's controller controls while victory.exe is in front. */ controller_keys: ControllerKeys + /** VIctory-NVIDIA's mods folder; null where there is none (off Windows). */ + mods: ModsView | null } files: { chosen: boolean @@ -410,7 +430,7 @@ export type Action = | { type: "choose_saves_dir"; path: string } | { type: "use_default_saves_dir" } | { type: "confirm_move"; answer: "move" | "keep" | "cancel" } - | { type: "open"; what: "project_folder" | "backgrounds" | "workspace" | "update" | "cache" | "saves"; repo?: string } + | { type: "open"; what: "project_folder" | "backgrounds" | "workspace" | "update" | "cache" | "saves" | "mods" | "bindings"; repo?: string } | { type: "export_log"; path: string; repo?: string } | { type: "check_update" } | { type: "download_update" } @@ -423,6 +443,9 @@ export type Action = | { type: "accept_notice" } | { type: "storage_scan" } | { type: "clear_cache"; repo: string } + | { type: "mod_add"; path: string } + | { type: "mod_set_on"; entry: string; on: boolean } + | { type: "mod_remove"; entry: string } | { type: "get_nvidia_files" } | { type: "set_fsr_dll"; path: string | null } | { type: "set_mac_runner"; runner: MacRunnerChoice }