Skip to content

ReStreet: FIFA Street (2012) recompiled for Windows PC, with online play, a launcher with friends, chat and rooms. Bring your own game.

Release v0.4.0 experimental: quick installation, updates, languages and runtime fixes

SamuelitoDaVila3bec945090c5
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..4ea75e4
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1 @@
+*.patch -text
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..427e135
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,16 @@
+# Changelog
+
+## v0.4.0 Experimental
+
+- Faster installation using bundled precompiled binaries for the verified game build; no Visual Studio, compiler download or local game compilation in this installer.
+- Existing-installation updates: select the folder containing Game and GameData. Saves, extracted game data, launcher preferences and existing runtime configuration are preserved.
+- Update integrity checks, backups of replaced files and restoration on handled errors or cancellation. Power-loss recovery is not automatic.
+- Clear installation/update instructions and corrected folder browsing when the default installation path does not exist.
+- Launcher language selection: English, Spanish, French, German and Italian. All five were tested by Samuel.
+- First-run defaults: Direct3D 12, fullscreen, 2x internal scale, FXAA Extreme, native 2x MSAA, VSync off and D3D12 VRR/tearing on. Resolution and refresh rate follow the selected primary display; existing preferences are retained.
+- Rendering, synchronization and frame-pacing corrections for the tested Direct3D 12 and Vulkan configurations, retaining Full Readback for compatibility. No universal FPS guarantee or claim of unlocked game simulation.
+- World Tour FootballCompEng function-boundary override; local code-generation, copy-routine validation and Samuel's World Tour test passed.
+- Contributor fixes for Windows patch line endings, module-path lookup and diagnostics, flexible data discovery and resource compilation. The latest source improvements to data-discovery error handling require a future main-executable rebuild; they are not claimed as changes in the bundled main executable.
+- Credits to Emran_Ahm3d in the documentation, installer and launcher.
+
+Limitations: a separate clean Windows installation/update test has not been confirmed. The project's MIT licence does not establish rights to redistribute game-derived binaries; no legal clearance is claimed. Applicable bundled notices are included.
diff --git a/CREDITS.md b/CREDITS.md
new file mode 100644
index 0000000..b07c170
--- /dev/null
+++ b/CREDITS.md
@@ -0,0 +1,9 @@
+# Credits
+
+- SamuelitoDaVila: project direction, port integration, installer, launcher and gameplay validation.
+- Emran_Ahm3d: investigation and fixes concerning Windows patch line endings, module-registration paths, game-data discovery, FootballCompEng function boundaries and Windows resource compilation.
+- ReXGlue, Xenia and XenonRecomp contributors: runtime, graphics and recompilation foundations; their respective licences and notices continue to apply.
+- extract-xiso, .NET and MonoGame contributors, and Microsoft Visual C++ runtime: installation and runtime components, subject to their respective terms.
+- ChatGPT and OpenAI Codex: development assistance under Samuel's direction.
+
+FIFA Street, EA, Xbox, Microsoft, artwork and game content retain their respective ownership. Project credits and the MIT licence do not grant redistribution rights to game-derived binaries or third-party material.
diff --git a/Installer/BuildFifaStreet.ps1 b/Installer/BuildFifaStreet.ps1
index 7e98a48..6be79df 100644
--- a/Installer/BuildFifaStreet.ps1
+++ b/Installer/BuildFifaStreet.ps1
@@ -1,342 +1,351 @@
-param(
- [Parameter(Mandatory = $true)]
- [string]$GameData,
-
- [Parameter(Mandatory = $true)]
- [string]$Output,
-
- [string]$Workspace,
-
- [ValidateRange(1, 64)]
- [int]$Jobs = 2
-)
-
-$ErrorActionPreference = "Stop"
-[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
-$OutputEncoding = [Console]::OutputEncoding
-
-function Invoke-BuildTool {
- param([string]$Tool, [string[]]$Arguments)
- $ErrorActionPreference = 'Continue'
- $nativeLog = $logPath + '.native'
- $writer = [IO.StreamWriter]::new($nativeLog, $true, [Text.UTF8Encoding]::new($false))
- try {
- $writer.WriteLine("$Tool " + ($Arguments -join ' '))
- & $Tool @Arguments 2>&1 | ForEach-Object {
- $line = if ($_ -is [Management.Automation.ErrorRecord]) { $_.Exception.Message } else { [string]$_ }
- $writer.WriteLine($line)
- if ($line -match '^\[\d+|^\s*(start|phase|done)\s|FAILED:|fatal error:|error:|^Failed:|Codegen summary:|^Done in') {
- Write-Host $line
- }
- }
- $exitCode = $LASTEXITCODE
- }
- finally { $writer.Dispose() }
- if ($exitCode -ne 0) { throw "$Tool failed with code $exitCode. Full log: $nativeLog" }
-}
-
-$installerRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
-
-$template = Join-Path $installerRoot "recomp-template"
-
-$rexGlueSource = if ($env:REXSDK_DIR) { [IO.Path]::GetFullPath($env:REXSDK_DIR) } else {
- "C:\Users\Samuel M\Desktop\FIFASTREET - 2012\ReXGlue"
-}
-
-$bundledSdk = Join-Path $installerRoot 'sdk'
-$bundledTools = Join-Path $installerRoot 'compiler'
-$useBundledSdk = Test-Path -LiteralPath (Join-Path $bundledSdk 'bin\rexglue.exe')
-$llvmBin = if (Test-Path -LiteralPath $bundledTools) { Join-Path $bundledTools 'bin' } else { "C:\Program Files\LLVM\bin" }
-
-$clang = Join-Path $llvmBin "clang.exe"
-$clangxx = Join-Path $llvmBin "clang++.exe"
-
-if (!(Test-Path $clang)) {
- throw "clang.exe not found at $clang"
-}
-
-if (!(Test-Path $clangxx)) {
- throw "clang++.exe not found at $clangxx"
-}
-
-$env:PATH = "$llvmBin;$env:PATH"
-if ($useBundledSdk) { $env:PATH = "$(Join-Path $bundledSdk 'bin');$env:PATH" }
-
-$shortTempRoot = if ($env:FIFA_BUILD_ROOT) { $env:FIFA_BUILD_ROOT } else { "C:\FSTRB" }
-
-if (!(Test-Path $shortTempRoot)) {
- New-Item -ItemType Directory -Path $shortTempRoot -Force | Out-Null
-}
-
-$resume = ![string]::IsNullOrWhiteSpace($Workspace)
-$workRoot = if ($resume) { [IO.Path]::GetFullPath($Workspace) } else {
- Join-Path $shortTempRoot ([guid]::NewGuid().ToString("N").Substring(0, 8))
-}
-
-$workProject = Join-Path $workRoot "FifaStreetRex"
-if ($resume -and !(Test-Path -LiteralPath (Join-Path $workProject 'CMakeLists.txt'))) {
- throw "Invalid build workspace: $workRoot"
-}
-$GameData = [IO.Path]::GetFullPath($GameData)
-$Output = [IO.Path]::GetFullPath($Output)
-
-Write-Host ""
-Write-Host "======================================"
-Write-Host " FIFA Street PC - Recomp Build"
-Write-Host "======================================"
-Write-Host ""
-
-if (!(Test-Path $GameData)) {
- throw "GameData does not exist: $GameData"
-}
-
-$defaultXex = Join-Path $GameData "default.xex"
-$fifaDll = Join-Path $GameData "fifadllzf.xex.dll"
-$footballCompDll = Join-Path $GameData "dlc\dlc_FootballCompEng\dlc\FootballCompEng\FootballCompEngzf.xex.dll"
-
-if (!(Test-Path $defaultXex)) {
- throw "default.xex was not found."
-}
-
-if (!(Test-Path $fifaDll)) {
- throw "fifadllzf.xex.dll was not found."
-}
-
-if (!(Test-Path $footballCompDll)) {
- throw "FootballCompEngzf.xex.dll was not found. This module is required for World Tour."
-}
-
-if (!(Test-Path $template)) {
- throw "recomp-template was not found: $template"
-}
-
-if (!$useBundledSdk -and !(Test-Path $rexGlueSource)) {
- throw "ReXGlue source was not found: $rexGlueSource"
-}
-
-Write-Host "[1/6] Preparing temporary workspace..."
-
-New-Item -ItemType Directory -Path $workProject -Force | Out-Null
-
-Get-ChildItem -LiteralPath $template | Where-Object { $_.Name -ne 'fifastreet_manifest.toml' } |
- Copy-Item -Destination $workProject -Recurse -Force
-
-$logPath = Join-Path $workRoot 'build.log'
-Write-Host "Workspace: $workRoot"
-Write-Host "Log: $logPath"
-Write-Host "Full diagnostics: $logPath.native"
-Start-Transcript -Path $logPath -Append | Out-Null
-trap {
- Write-Host $_.ToString()
- Stop-Transcript -ErrorAction SilentlyContinue | Out-Null
- throw $_
-}
-
-Write-Host "[2/6] Preparing manifest..."
-
-$manifestPath = Join-Path $workProject "fifastreet_manifest.toml"
-
-$gameDataUnix = $GameData.Replace("\", "/").Replace('"', '\"')
-
-$manifest = @"
-[project]
-name = "fifastreet"
-sdk_version = "0.10.0"
-game_root = "$gameDataUnix"
-
-[entrypoint]
-file_path = "$gameDataUnix/default.xex"
-out_directory_path = "generated/default"
-includes = []
-
-[[modules]]
-guest_path = "game:\\fifadllzf.xex.dll"
-file_path = "$gameDataUnix/fifadllzf.xex.dll"
-out_directory_path = "generated/fifadllzf_xex"
-includes = ["config/fifadllzf_overrides.toml"]
-
-[[modules]]
-guest_path = "game:\\FootballCompEngzf.xex.dll"
-file_path = "$gameDataUnix/dlc/dlc_FootballCompEng/dlc/FootballCompEng/FootballCompEngzf.xex.dll"
-out_directory_path = "generated/FootballCompEngzf_xex"
-includes = []
-"@
-
-$manifest = $manifest.Replace("`r`n", "`n")
-$manifestChanged = !$resume -or [IO.File]::ReadAllText($manifestPath).Replace("`r`n", "`n").Trim() -ne $manifest.Trim()
-if ($manifestChanged) {
- [System.IO.File]::WriteAllText($manifestPath, $manifest, [System.Text.UTF8Encoding]::new($false))
-}
-
-Write-Host ""
-Write-Host "Manifest:"
-Get-Content $manifestPath
-Write-Host ""
-
-Write-Host "[3/6] Cleaning previous generated code..."
-
-$generatedDefault = Join-Path $workProject "generated\default"
-$generatedDll = Join-Path $workProject "generated\fifadllzf_xex"
-$generatedFootballComp = Join-Path $workProject "generated\FootballCompEngzf_xex"
-
-if (!$resume -and (Test-Path $generatedDefault)) {
- if (![IO.Path]::GetFullPath($generatedDefault).StartsWith($workProject + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'Unsafe generated path' }
- Remove-Item $generatedDefault -Recurse -Force
-}
-
-if (!$resume -and (Test-Path $generatedDll)) {
- if (![IO.Path]::GetFullPath($generatedDll).StartsWith($workProject + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'Unsafe generated path' }
- Remove-Item $generatedDll -Recurse -Force
-}
-
-if (!$resume -and (Test-Path $generatedFootballComp)) {
- if (![IO.Path]::GetFullPath($generatedFootballComp).StartsWith($workProject + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'Unsafe generated path' }
- Remove-Item $generatedFootballComp -Recurse -Force
-}
-
-Write-Host "[4/6] Configuring build..."
-
-Push-Location $workProject
-
-try {
-
- # Generate sources before configuration so CMake discovers both binaries.
- $codegen = if ($useBundledSdk) { Join-Path $bundledSdk 'bin\rexglue.exe' } else { Join-Path $rexGlueSource 'out\win-amd64\rexglue.exe' }
- if (!(Test-Path -LiteralPath $codegen)) { throw "ReXGlue code generator not found: $codegen" }
- if ($manifestChanged -or !(Test-Path -LiteralPath (Join-Path $generatedDefault 'sources.cmake')) -or
- !(Test-Path -LiteralPath (Join-Path $generatedDll 'sources.cmake')) -or
- !(Test-Path -LiteralPath (Join-Path $generatedFootballComp 'sources.cmake'))) {
- Invoke-BuildTool $codegen @('--log-file', (Join-Path $workRoot 'codegen.log'), 'codegen', $manifestPath)
- }
-
- $sdkArguments = if ($useBundledSdk) { @('-DREXSDK_DIR=', "-DCMAKE_PREFIX_PATH=$bundledSdk") } else { @("-DREXSDK_DIR=$rexGlueSource") }
- Invoke-BuildTool 'cmake' (@('--preset', 'win-amd64-release') + $sdkArguments + @(
- "-DCMAKE_C_COMPILER=$clang",
- "-DCMAKE_CXX_COMPILER=$clangxx", '-DCMAKE_C_FLAGS=-mssse3', '-DCMAKE_CXX_FLAGS=-mssse3')
- )
-
- Write-Host ""
- Write-Host "[5/6] Compiling FIFA Street..."
- Write-Host ""
-
- Invoke-BuildTool 'cmake' @('--build', '--preset', 'win-amd64-release', '--parallel', "$Jobs")
-
-}
-finally {
- Pop-Location
-}
-
-$buildFolder = Join-Path $workProject "out\build\win-amd64-release"
-
-$exe = Join-Path $buildFolder "fifastreet.exe"
-
-$dll = Join-Path $buildFolder "fifastreet_fifadllzf_xex.dll"
-$footballCompOut = Join-Path $buildFolder "fifastreet_FootballCompEngzf_xex.dll"
-
-if (!(Test-Path $exe)) {
- throw "The build finished but fifastreet.exe was not found."
-}
-
-if (!(Test-Path $dll)) {
- throw "The build finished but fifastreet_fifadllzf_xex.dll was not found."
-}
-
-if (!(Test-Path $footballCompOut)) {
- throw "The build finished but fifastreet_FootballCompEngzf_xex.dll was not found."
-}
-
-Write-Host ""
-Write-Host "[6/6] Installing game binaries..."
-
-New-Item `
- -ItemType Directory `
- -Path $Output `
- -Force | Out-Null
-
-Copy-Item $exe $Output -Force
-
-# Copy the recompiled game modules.
-Get-ChildItem -LiteralPath $buildFolder -Filter '*.dll' -File |
- Where-Object { $_.Name -notin @('rexruntime.dll', 'rexgpu-xenos.dll') } |
- Copy-Item -Destination $Output -Force
-
-# Install both validated graphics backends.
-$bundledBackends = Join-Path $bundledSdk 'backends'
-$outputBackends = Join-Path $Output 'Backends'
-
-New-Item -ItemType Directory -Path $outputBackends -Force | Out-Null
-
-$expectedBackends = @{
- 'D3D12' = @{
- RuntimeHash = '790B6B1B13765249160E53DCE6F28AF0F03B66D5D1AEDB1054949C50B13F04E8'
- GpuHash = '461A88F1D27C605106453B0F3C92BD72BD4BC166DCDC0BBF01E825BCEFB8418D'
- }
- 'Vulkan' = @{
- RuntimeHash = '115722CC5905D07FC6A6212B47692FFE6405DD1BA9F87CDA97F8DA2C25E4767A'
- GpuHash = '71FA61D82FF6134F1F407D682ACEBAC01F2B3B2DCEFCC34151A0C082B746BDD2'
- }
-}
-
-foreach ($backendName in @('D3D12', 'Vulkan')) {
- $sourceBackend = Join-Path $bundledBackends $backendName
- $destinationBackend = Join-Path $outputBackends $backendName
-
- $sourceRuntime = Join-Path $sourceBackend 'rexruntime.dll'
- $sourceGpu = Join-Path $sourceBackend 'rexgpu-xenos.dll'
-
- if (!(Test-Path -LiteralPath $sourceRuntime)) {
- throw "$backendName rexruntime.dll was not found: $sourceRuntime"
- }
-
- if (!(Test-Path -LiteralPath $sourceGpu)) {
- throw "$backendName rexgpu-xenos.dll was not found: $sourceGpu"
- }
-
- $runtimeHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $sourceRuntime).Hash
- $gpuHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $sourceGpu).Hash
-
- if ($runtimeHash -ne $expectedBackends[$backendName].RuntimeHash) {
- throw "$backendName rexruntime.dll is not the validated runtime."
- }
-
- if ($gpuHash -ne $expectedBackends[$backendName].GpuHash) {
- throw "$backendName rexgpu-xenos.dll is not the validated GPU backend."
- }
-
- New-Item -ItemType Directory -Path $destinationBackend -Force | Out-Null
-
- Copy-Item -LiteralPath $sourceRuntime `
- -Destination (Join-Path $destinationBackend 'rexruntime.dll') `
- -Force
-
- Copy-Item -LiteralPath $sourceGpu `
- -Destination (Join-Path $destinationBackend 'rexgpu-xenos.dll') `
- -Force
-}
-
-# D3D12 is the launcher's default graphics API, so install it as the
-# initially active backend beside fifastreet.exe.
-Copy-Item `
- -LiteralPath (Join-Path $outputBackends 'D3D12\rexruntime.dll') `
- -Destination (Join-Path $Output 'rexruntime.dll') `
- -Force
-
-Copy-Item `
- -LiteralPath (Join-Path $outputBackends 'D3D12\rexgpu-xenos.dll') `
- -Destination (Join-Path $Output 'rexgpu-xenos.dll') `
- -Force
-Write-Host ""
-Write-Host "======================================"
-Write-Host " BUILD COMPLETE"
-Write-Host "======================================"
-Write-Host ""
-
-Write-Host "Created:"
-Write-Host " $(Join-Path $Output 'fifastreet.exe')"
-Write-Host " $(Join-Path $Output 'fifastreet_fifadllzf_xex.dll')"
-Write-Host " $(Join-Path $Output 'fifastreet_FootballCompEngzf_xex.dll')"
-
-Write-Host ""
-Write-Host "Temporary workspace:"
-Write-Host $workRoot
-Stop-Transcript | Out-Null
+param(
+ [Parameter(Mandatory = $true)]
+ [string]$GameData,
+
+ [Parameter(Mandatory = $true)]
+ [string]$Output,
+
+ [string]$Workspace,
+
+ [ValidateRange(1, 64)]
+ [int]$Jobs = 2
+)
+
+$ErrorActionPreference = "Stop"
+[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
+$OutputEncoding = [Console]::OutputEncoding
+
+function Invoke-BuildTool {
+ param([string]$Tool, [string[]]$Arguments)
+ $ErrorActionPreference = 'Continue'
+ $nativeLog = $logPath + '.native'
+ $writer = [IO.StreamWriter]::new($nativeLog, $true, [Text.UTF8Encoding]::new($false))
+ try {
+ $writer.WriteLine("$Tool " + ($Arguments -join ' '))
+ & $Tool @Arguments 2>&1 | ForEach-Object {
+ $line = if ($_ -is [Management.Automation.ErrorRecord]) { $_.Exception.Message } else { [string]$_ }
+ $writer.WriteLine($line)
+ if ($line -match '^\[\d+|^\s*(start|phase|done)\s|FAILED:|fatal error:|error:|^Failed:|Codegen summary:|^Done in') {
+ Write-Host $line
+ }
+ }
+ $exitCode = $LASTEXITCODE
+ }
+ finally { $writer.Dispose() }
+ if ($exitCode -ne 0) { throw "$Tool failed with code $exitCode. Full log: $nativeLog" }
+}
+
+$installerRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
+. (Join-Path $installerRoot "BuildIntegrity.ps1")
+
+$template = Join-Path $installerRoot "recomp-template"
+
+$rexGlueSource = if ($env:REXSDK_DIR) { [IO.Path]::GetFullPath($env:REXSDK_DIR) } else {
+ "C:\Users\Samuel M\Desktop\FIFASTREET - 2012\ReXGlue"
+}
+
+$bundledSdk = Join-Path $installerRoot 'sdk'
+$bundledTools = Join-Path $installerRoot 'compiler'
+$useBundledSdk = Test-Path -LiteralPath (Join-Path $bundledSdk 'bin\rexglue.exe')
+$llvmBin = if (Test-Path -LiteralPath $bundledTools) { Join-Path $bundledTools 'bin' } else { "C:\Program Files\LLVM\bin" }
+
+$clang = Join-Path $llvmBin "clang.exe"
+$clangxx = Join-Path $llvmBin "clang++.exe"
+
+if (!(Test-Path $clang)) {
+ throw "clang.exe not found at $clang"
+}
+
+if (!(Test-Path $clangxx)) {
+ throw "clang++.exe not found at $clangxx"
+}
+
+$env:PATH = "$llvmBin;$env:PATH"
+if ($useBundledSdk) { $env:PATH = "$(Join-Path $bundledSdk 'bin');$env:PATH" }
+
+$shortTempRoot = if ($env:FIFA_BUILD_ROOT) { $env:FIFA_BUILD_ROOT } else { "C:\FSTRB" }
+
+if (!(Test-Path $shortTempRoot)) {
+ New-Item -ItemType Directory -Path $shortTempRoot -Force | Out-Null
+}
+
+$resume = ![string]::IsNullOrWhiteSpace($Workspace)
+$workRoot = if ($resume) { [IO.Path]::GetFullPath($Workspace) } else {
+ Join-Path $shortTempRoot ([guid]::NewGuid().ToString("N").Substring(0, 8))
+}
+
+$workProject = Join-Path $workRoot "FifaStreetRex"
+if ($resume -and !(Test-Path -LiteralPath (Join-Path $workProject 'CMakeLists.txt'))) {
+ throw "Invalid build workspace: $workRoot"
+}
+$GameData = [IO.Path]::GetFullPath($GameData)
+$Output = [IO.Path]::GetFullPath($Output)
+
+Write-Host ""
+Write-Host "======================================"
+Write-Host " FIFA Street PC - Recomp Build"
+Write-Host "======================================"
+Write-Host ""
+
+if (!(Test-Path $GameData)) {
+ throw "GameData does not exist: $GameData"
+}
+
+$defaultXex = Join-Path $GameData "default.xex"
+$fifaDll = Join-Path $GameData "fifadllzf.xex.dll"
+$footballCompDll = Join-Path $GameData "dlc\dlc_FootballCompEng\dlc\FootballCompEng\FootballCompEngzf.xex.dll"
+
+if (!(Test-Path $defaultXex)) {
+ throw "default.xex was not found."
+}
+
+if (!(Test-Path $fifaDll)) {
+ throw "fifadllzf.xex.dll was not found."
+}
+
+if (!(Test-Path $footballCompDll)) {
+ throw "FootballCompEngzf.xex.dll was not found. This module is required for World Tour."
+}
+
+if (!(Test-Path $template)) {
+ throw "recomp-template was not found: $template"
+}
+
+if (!$useBundledSdk -and !(Test-Path $rexGlueSource)) {
+ throw "ReXGlue source was not found: $rexGlueSource"
+}
+
+Write-Host "[1/6] Preparing temporary workspace..."
+
+New-Item -ItemType Directory -Path $workProject -Force | Out-Null
+
+Get-ChildItem -LiteralPath $template | Where-Object { $_.Name -ne 'fifastreet_manifest.toml' } |
+ Copy-Item -Destination $workProject -Recurse -Force
+
+$logPath = Join-Path $workRoot 'build.log'
+Write-Host "Workspace: $workRoot"
+Write-Host "Log: $logPath"
+Write-Host "Full diagnostics: $logPath.native"
+Start-Transcript -Path $logPath -Append | Out-Null
+trap {
+ Write-Host $_.ToString()
+ Stop-Transcript -ErrorAction SilentlyContinue | Out-Null
+ throw $_
+}
+
+Write-Host "[2/6] Preparing manifest..."
+
+$manifestPath = Join-Path $workProject "fifastreet_manifest.toml"
+
+$gameDataUnix = $GameData.Replace("\", "/").Replace('"', '\"')
+
+$manifest = @"
+[project]
+name = "fifastreet"
+sdk_version = "0.10.0"
+game_root = "$gameDataUnix"
+
+[entrypoint]
+file_path = "$gameDataUnix/default.xex"
+out_directory_path = "generated/default"
+includes = []
+
+[[modules]]
+guest_path = "game:\\fifadllzf.xex.dll"
+file_path = "$gameDataUnix/fifadllzf.xex.dll"
+out_directory_path = "generated/fifadllzf_xex"
+includes = ["config/fifadllzf_overrides.toml"]
+
+[[modules]]
+guest_path = "game:\\FootballCompEngzf.xex.dll"
+file_path = "$gameDataUnix/dlc/dlc_FootballCompEng/dlc/FootballCompEng/FootballCompEngzf.xex.dll"
+out_directory_path = "generated/FootballCompEngzf_xex"
+includes = ["config/footballcompeng_overrides.toml"]
+"@
+
+$manifest = $manifest.Replace("`r`n", "`n")
+$manifestChanged = !$resume -or !(Test-Path -LiteralPath $manifestPath) -or [IO.File]::ReadAllText($manifestPath).Replace("`r`n", "`n").Trim() -ne $manifest.Trim()
+if ($manifestChanged) {
+ [System.IO.File]::WriteAllText($manifestPath, $manifest, [System.Text.UTF8Encoding]::new($false))
+}
+
+Write-Host ""
+Write-Host "Manifest:"
+Get-Content $manifestPath
+Write-Host ""
+
+Write-Host "[3/6] Cleaning previous generated code..."
+
+$generatedDefault = Join-Path $workProject "generated\default"
+$generatedDll = Join-Path $workProject "generated\fifadllzf_xex"
+$generatedFootballComp = Join-Path $workProject "generated\FootballCompEngzf_xex"
+
+if (!$resume -and (Test-Path $generatedDefault)) {
+ if (![IO.Path]::GetFullPath($generatedDefault).StartsWith($workProject + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'Unsafe generated path' }
+ Remove-Item $generatedDefault -Recurse -Force
+}
+
+if (!$resume -and (Test-Path $generatedDll)) {
+ if (![IO.Path]::GetFullPath($generatedDll).StartsWith($workProject + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'Unsafe generated path' }
+ Remove-Item $generatedDll -Recurse -Force
+}
+
+if (!$resume -and (Test-Path $generatedFootballComp)) {
+ if (![IO.Path]::GetFullPath($generatedFootballComp).StartsWith($workProject + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'Unsafe generated path' }
+ Remove-Item $generatedFootballComp -Recurse -Force
+}
+
+Write-Host "[4/6] Configuring build..."
+
+Push-Location $workProject
+
+try {
+
+ # Generate sources before configuration so CMake discovers both binaries.
+ $codegen = if ($useBundledSdk) { Join-Path $bundledSdk 'bin\rexglue.exe' } else { Join-Path $rexGlueSource 'out\win-amd64\rexglue.exe' }
+ if (!(Test-Path -LiteralPath $codegen)) { throw "ReXGlue code generator not found: $codegen" }
+ $fingerprintPath = Join-Path $workProject 'codegen-inputs.sha256'
+ $fingerprintInputs = @($manifestPath, $codegen)
+ $fingerprintInputs += @(Get-ChildItem -LiteralPath $GameData -Filter '*.xex*' -File -Recurse | ForEach-Object { $_.FullName })
+ $fingerprintInputs += @(Get-ChildItem -LiteralPath (Join-Path $workProject 'config') -File -Recurse | ForEach-Object { $_.FullName })
+ $fingerprint = Get-CodegenFingerprint $fingerprintInputs
+ $inputsChanged = !(Test-Path -LiteralPath $fingerprintPath) -or [IO.File]::ReadAllText($fingerprintPath).Trim() -ne $fingerprint
+ if ($manifestChanged -or $inputsChanged -or !(Test-Path -LiteralPath (Join-Path $generatedDefault 'sources.cmake')) -or
+ !(Test-Path -LiteralPath (Join-Path $generatedDll 'sources.cmake')) -or
+ !(Test-Path -LiteralPath (Join-Path $generatedFootballComp 'sources.cmake'))) {
+ if (Test-Path -LiteralPath $fingerprintPath) { Remove-Item -LiteralPath $fingerprintPath -Force }
+ Invoke-BuildTool $codegen @('--log-file', (Join-Path $workRoot 'codegen.log'), 'codegen', $manifestPath)
+ [IO.File]::WriteAllText($fingerprintPath, $fingerprint, [Text.UTF8Encoding]::new($false))
+ }
+
+ $sdkArguments = if ($useBundledSdk) { @('-DREXSDK_DIR=', "-DCMAKE_PREFIX_PATH=$bundledSdk") } else { @("-DREXSDK_DIR=$rexGlueSource") }
+ Invoke-BuildTool 'cmake' (@('--preset', 'win-amd64-release') + $sdkArguments + @(
+ "-DCMAKE_C_COMPILER=$clang",
+ "-DCMAKE_CXX_COMPILER=$clangxx", '-DCMAKE_C_FLAGS=-mssse3', '-DCMAKE_CXX_FLAGS=-mssse3')
+ )
+
+ Write-Host ""
+ Write-Host "[5/6] Compiling FIFA Street..."
+ Write-Host ""
+
+ Invoke-BuildTool 'cmake' @('--build', '--preset', 'win-amd64-release', '--parallel', "$Jobs")
+
+}
+finally {
+ Pop-Location
+}
+
+$buildFolder = Join-Path $workProject "out\build\win-amd64-release"
+
+$exe = Join-Path $buildFolder "fifastreet.exe"
+
+$dll = Join-Path $buildFolder "fifastreet_fifadllzf_xex.dll"
+$footballCompOut = Join-Path $buildFolder "fifastreet_FootballCompEngzf_xex.dll"
+
+if (!(Test-Path $exe)) {
+ throw "The build finished but fifastreet.exe was not found."
+}
+
+if (!(Test-Path $dll)) {
+ throw "The build finished but fifastreet_fifadllzf_xex.dll was not found."
+}
+
+if (!(Test-Path $footballCompOut)) {
+ throw "The build finished but fifastreet_FootballCompEngzf_xex.dll was not found."
+}
+
+Write-Host ""
+Write-Host "[6/6] Installing game binaries..."
+
+New-Item `
+ -ItemType Directory `
+ -Path $Output `
+ -Force | Out-Null
+
+Copy-Item $exe $Output -Force
+
+# Copy the recompiled game modules.
+Get-ChildItem -LiteralPath $buildFolder -Filter '*.dll' -File |
+ Where-Object { $_.Name -notin @('rexruntime.dll', 'rexgpu-xenos.dll') } |
+ Copy-Item -Destination $Output -Force
+
+# Install both validated graphics backends.
+$bundledBackends = Join-Path $bundledSdk 'backends'
+$outputBackends = Join-Path $Output 'Backends'
+
+New-Item -ItemType Directory -Path $outputBackends -Force | Out-Null
+
+$expectedBackends = @{
+ 'D3D12' = @{
+ RuntimeHash = '790B6B1B13765249160E53DCE6F28AF0F03B66D5D1AEDB1054949C50B13F04E8'
+ GpuHash = '461A88F1D27C605106453B0F3C92BD72BD4BC166DCDC0BBF01E825BCEFB8418D'
+ }
+ 'Vulkan' = @{
+ RuntimeHash = '115722CC5905D07FC6A6212B47692FFE6405DD1BA9F87CDA97F8DA2C25E4767A'
+ GpuHash = '71FA61D82FF6134F1F407D682ACEBAC01F2B3B2DCEFCC34151A0C082B746BDD2'
+ }
+}
+
+foreach ($backendName in @('D3D12', 'Vulkan')) {
+ $sourceBackend = Join-Path $bundledBackends $backendName
+ $destinationBackend = Join-Path $outputBackends $backendName
+
+ $sourceRuntime = Join-Path $sourceBackend 'rexruntime.dll'
+ $sourceGpu = Join-Path $sourceBackend 'rexgpu-xenos.dll'
+
+ if (!(Test-Path -LiteralPath $sourceRuntime)) {
+ throw "$backendName rexruntime.dll was not found: $sourceRuntime"
+ }
+
+ if (!(Test-Path -LiteralPath $sourceGpu)) {
+ throw "$backendName rexgpu-xenos.dll was not found: $sourceGpu"
+ }
+
+ $runtimeHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $sourceRuntime).Hash
+ $gpuHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $sourceGpu).Hash
+
+ if ($runtimeHash -ne $expectedBackends[$backendName].RuntimeHash) {
+ throw "$backendName rexruntime.dll is not the validated runtime."
+ }
+
+ if ($gpuHash -ne $expectedBackends[$backendName].GpuHash) {
+ throw "$backendName rexgpu-xenos.dll is not the validated GPU backend."
+ }
+
+ New-Item -ItemType Directory -Path $destinationBackend -Force | Out-Null
+
+ Copy-Item -LiteralPath $sourceRuntime `
+ -Destination (Join-Path $destinationBackend 'rexruntime.dll') `
+ -Force
+
+ Copy-Item -LiteralPath $sourceGpu `
+ -Destination (Join-Path $destinationBackend 'rexgpu-xenos.dll') `
+ -Force
+}
+
+# D3D12 is the launcher's default graphics API, so install it as the
+# initially active backend beside fifastreet.exe.
+Copy-Item `
+ -LiteralPath (Join-Path $outputBackends 'D3D12\rexruntime.dll') `
+ -Destination (Join-Path $Output 'rexruntime.dll') `
+ -Force
+
+Copy-Item `
+ -LiteralPath (Join-Path $outputBackends 'D3D12\rexgpu-xenos.dll') `
+ -Destination (Join-Path $Output 'rexgpu-xenos.dll') `
+ -Force
+Write-Host ""
+Write-Host "======================================"
+Write-Host " BUILD COMPLETE"
+Write-Host "======================================"
+Write-Host ""
+
+Write-Host "Created:"
+Write-Host " $(Join-Path $Output 'fifastreet.exe')"
+Write-Host " $(Join-Path $Output 'fifastreet_fifadllzf_xex.dll')"
+Write-Host " $(Join-Path $Output 'fifastreet_FootballCompEngzf_xex.dll')"
+
+Write-Host ""
+Write-Host "Temporary workspace:"
+Write-Host $workRoot
+Stop-Transcript | Out-Null
diff --git a/Installer/BuildIntegrity.ps1 b/Installer/BuildIntegrity.ps1
new file mode 100644
index 0000000..4f0a9ca
--- /dev/null
+++ b/Installer/BuildIntegrity.ps1
@@ -0,0 +1,18 @@
+function Get-InputSha256 {
+ param([Parameter(Mandatory = $true)][string]$Path)
+ $stream = [IO.File]::OpenRead($Path)
+ $algorithm = [Security.Cryptography.SHA256]::Create()
+ try { return [BitConverter]::ToString($algorithm.ComputeHash($stream)).Replace('-', '').ToLowerInvariant() }
+ finally { $algorithm.Dispose(); $stream.Dispose() }
+}
+
+function Get-CodegenFingerprint {
+ param([Parameter(Mandatory = $true)][string[]]$Paths)
+ $records = foreach ($path in ($Paths | Sort-Object -Unique)) {
+ $absolute = [IO.Path]::GetFullPath($path)
+ $absolute + ':' + (Get-InputSha256 $absolute)
+ }
+ $algorithm = [Security.Cryptography.SHA256]::Create()
+ try { return [BitConverter]::ToString($algorithm.ComputeHash([Text.Encoding]::UTF8.GetBytes(($records -join "`n")))).Replace('-', '').ToLowerInvariant() }
+ finally { $algorithm.Dispose() }
+}
diff --git a/Installer/BuildPrecompiled.py b/Installer/BuildPrecompiled.py
new file mode 100644
index 0000000..dbe5021
--- /dev/null
+++ b/Installer/BuildPrecompiled.py
@@ -0,0 +1,89 @@
+"""Build a local precompiled installer from an explicitly supplied, tested runtime.
+
+This does not publish files or determine redistribution rights.
+"""
+import argparse
+import hashlib
+import json
+from pathlib import Path
+import shutil
+import subprocess
+import zipfile
+
+parser = argparse.ArgumentParser()
+parser.add_argument('--runtime', type=Path, required=True)
+parser.add_argument('--launcher', type=Path, help='Optional newly built launcher')
+parser.add_argument('--worldtour', type=Path, help='Optional verified World Tour module candidate')
+parser.add_argument('--inputs', type=Path, required=True, help='Folder containing the three original modules used for recompilation')
+parser.add_argument('--extractor', type=Path, required=True)
+parser.add_argument('--licenses-bundle', type=Path, required=True)
+parser.add_argument('--crt', type=Path, required=True, help='Official Visual Studio VC/Redist x64 CRT folder')
+parser.add_argument('--crt-notices', type=Path, required=True, help='Visual Studio Redist.txt')
+parser.add_argument('--output', type=Path, required=True)
+args = parser.parse_args()
+root = Path(__file__).resolve().parent
+stage = args.output.resolve()
+if stage.exists():
+ raise SystemExit('Choose a new output directory; existing packages are not overwritten.')
+stage.mkdir(parents=True)
+bundle = stage/'package'
+game = bundle/'payload/Game'
+game.mkdir(parents=True)
+(bundle/'tools').mkdir()
+shutil.copy2(args.extractor, bundle/'tools/extract-xiso.exe')
+shutil.copy2(args.launcher or args.runtime/'FifaStreetLauncher.exe', bundle/'payload/FifaStreetLauncher.exe')
+for name in ['fifastreet.exe', 'fifastreet_fifadllzf_xex.dll', 'fifastreet_FootballCompEngzf_xex.dll', 'rexruntime.dll', 'rexgpu-xenos.dll', 'TracyClient.dll']:
+ source = args.worldtour if name == 'fifastreet_FootballCompEngzf_xex.dll' and args.worldtour else args.runtime/name
+ shutil.copy2(source, game/name)
+for backend in ['D3D12', 'Vulkan']:
+ destination = game/'Backends'/backend
+ destination.mkdir(parents=True)
+ for name in ['rexruntime.dll', 'rexgpu-xenos.dll', 'TracyClient.dll']:
+ shutil.copy2(args.runtime/'Backends'/backend/name, destination/name)
+shutil.copy2(root/'payload/Game/fifastreet.toml', game/'fifastreet.toml')
+required_crt = ['msvcp140.dll', 'msvcp140_atomic_wait.dll', 'vcruntime140.dll', 'vcruntime140_1.dll']
+if not all((args.crt/name).is_file() for name in required_crt):
+ raise ValueError('The official x64 CRT folder is incomplete.')
+for dll in args.crt.glob('*.dll'):
+ shutil.copy2(dll, game/dll.name)
+# extract-xiso also imports VCRUNTIME140; it must run on a clean Windows PC.
+shutil.copy2(args.crt/'vcruntime140.dll', bundle/'tools/vcruntime140.dll')
+# The default selected backend must match the DLLs beside the executable.
+for name in ['rexruntime.dll', 'rexgpu-xenos.dll', 'TracyClient.dll']:
+ shutil.copy2(game/'Backends/D3D12'/name, game/name)
+with zipfile.ZipFile(args.licenses_bundle) as original:
+ for entry in original.infolist():
+ path = Path(entry.filename)
+ if path.parts and path.parts[0] == 'licenses' and not entry.is_dir():
+ if path.is_absolute() or '..' in path.parts:
+ raise ValueError('Invalid license archive path')
+ target = bundle/'payload'/path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(original.read(entry))
+if not (bundle/'payload/licenses').is_dir():
+ raise ValueError('Third-party license notices are required.')
+shutil.copy2(root/'FifaStreetSetupTool/ThirdParty/MonoGame-LICENSE.txt', bundle/'payload/licenses/MonoGame-LZX-MS-PL.txt')
+shutil.copy2(args.crt_notices, bundle/'payload/licenses/Microsoft-CRT-Redist.txt')
+shutil.copytree(root.parent/'licenses/bundled-tools', bundle/'payload/licenses/bundled-tools')
+shutil.copy2(root.parent/'licenses/README.md', bundle/'payload/licenses/LICENSE-SCOPE.md')
+for document in ['CREDITS.md', 'CHANGELOG.md', 'LICENSE']:
+ shutil.copy2(root.parent/document, bundle/'payload'/document)
+
+def digest(path):
+ with path.open('rb') as stream:
+ return hashlib.file_digest(stream, 'sha256').hexdigest()
+
+inputs = {'default.xex': 'default.xex', 'fifadllzf.xex.dll': 'fifadllzf.xex.dll', 'dlc/dlc_FootballCompEng/dlc/FootballCompEng/FootballCompEngzf.xex.dll': 'FootballCompEngzf.xex.dll'}
+manifest = {'Format': 1, 'Version': 'Known FIFA Street 2012 build (verified module hashes)', 'Inputs': {key: digest(args.inputs/value) for key, value in inputs.items()}, 'Payload': {p.relative_to(bundle/'payload').as_posix(): digest(p) for p in sorted((bundle/'payload').rglob('*')) if p.is_file()}}
+manifest_path = bundle/'precompiled.json'
+manifest_path.write_text(json.dumps(manifest, indent=2), encoding='utf-8')
+archive = stage/'precompiled-bundle.zip'
+with zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as packed:
+ for path in sorted(bundle.rglob('*')):
+ if path.is_file():
+ packed.write(path, path.relative_to(bundle).as_posix())
+subprocess.run(['rtk', 'proxy', 'dotnet', 'publish', str(root/'FifaStreetSetupTool/FifaStreetSetupTool.csproj'), '-c', 'Release', '-r', 'win-x64', '--self-contained', 'true', '-p:PublishSingleFile=true', '-p:IncludeNativeLibrariesForSelfExtract=true', '-p:RuntimeFrameworkVersion=8.0.31', f'-p:BundlePath={archive}', f'-p:PrecompiledManifest={manifest_path}', '-o', str(stage/'published')], check=True)
+exe = stage/'FifaStreetSetup-Precompiled-LOCAL.exe'
+shutil.copy2(stage/'published/FifaStreetSetup.exe', exe)
+(stage/'build.json').write_text(json.dumps({'installer': str(exe), 'sha256': digest(exe), 'bytes': exe.stat().st_size, 'publication': 'Local test only; redistribution not reviewed', 'manifest': manifest}, indent=2), encoding='utf-8')
+print(f'Local precompiled installer built: {exe} ({exe.stat().st_size / 1024**2:.1f} MiB)')
diff --git a/Installer/BuildSetup.ps1 b/Installer/BuildSetup.ps1
index b9d7c14..b83949d 100644
--- a/Installer/BuildSetup.ps1
+++ b/Installer/BuildSetup.ps1
@@ -1,134 +1,137 @@
-param(
- [Parameter(Mandatory = $true)][string]$Output,
- [string]$LLVMRoot = 'C:\Program Files\LLVM',
- [string]$CMakeRoot = 'C:\Program Files\CMake',
- [string]$NinjaPath = (Get-Command ninja.exe -ErrorAction Stop).Source,
- [string]$ClangResourceVersion
-)
-$ErrorActionPreference = 'Stop'
-if (-not $ClangResourceVersion) {
- $ClangResourceVersion = (Get-ChildItem -LiteralPath (Join-Path $LLVMRoot 'lib\clang') -Directory |
- Sort-Object { [version]$_.Name } -Descending | Select-Object -First 1).Name
-}
-if (-not $ClangResourceVersion) { throw 'Clang resource directory was not found.' }
-$root = $PSScriptRoot
-$projectRoot = Split-Path $root -Parent
-$stage = Join-Path $env:TEMP ('FifaStreetPackage_' + [guid]::NewGuid().ToString('N'))
-$utf8 = [Text.UTF8Encoding]::new($false)
-New-Item -ItemType Directory -Path $stage | Out-Null
-foreach ($name in @('BuildFifaStreet.ps1', 'README.md')) { Copy-Item -LiteralPath (Join-Path $root $name) -Destination $stage }
-$template = Join-Path $stage 'recomp-template'
-foreach ($name in @('', 'config', 'src', 'generated')) { New-Item -ItemType Directory -Path (Join-Path $template $name) -Force | Out-Null }
-foreach ($name in @('CMakeLists.txt','CMakePresets.json','fifastreet_manifest.toml','config\fifadllzf_overrides.toml','src\main.cpp','src\fifastreet_app.h','src\stubs.cpp','generated\rexglue.cmake')) {
- Copy-Item -LiteralPath (Join-Path $root "recomp-template\$name") -Destination (Join-Path $template $name)
-}
-Copy-Item -LiteralPath (Join-Path $root 'recomp-template\src\fifastreet.ico') -Destination (Join-Path $template 'src\fifastreet.ico')
-[IO.File]::WriteAllText((Join-Path $template 'src\fifastreet.rc'), '1 ICON "fifastreet.ico"', $utf8)
-New-Item -ItemType Directory -Path (Join-Path $stage 'tools') | Out-Null
-Copy-Item -LiteralPath (Join-Path $root 'tools\extract-xiso.exe') -Destination (Join-Path $stage 'tools')
-New-Item -ItemType Directory -Path (Join-Path $stage 'payload\Game') -Force | Out-Null
-Copy-Item -LiteralPath (Join-Path $root 'payload\Game\fifastreet.toml') -Destination (Join-Path $stage 'payload\Game')
-dotnet publish (Join-Path $projectRoot 'Launcher\FifaStreetLauncher\FifaStreetLauncher.csproj') -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:RuntimeFrameworkVersion=8.0.31 -o (Join-Path $stage 'payload')
-if ($LASTEXITCODE -ne 0) { throw 'Falha ao publicar o launcher.' }
-Get-ChildItem -LiteralPath (Join-Path $stage 'payload') -Filter '*.pdb' | Remove-Item
-
-# Use the installed public SDK layout, with the current runtime and code generator.
-Copy-Item -LiteralPath (Join-Path $projectRoot 'ReXGlue\out\install\win-amd64') -Destination (Join-Path $stage 'sdk') -Recurse
-$current = Join-Path $projectRoot 'ReXGlue\out\win-amd64'
-foreach ($name in @('rexglue.exe','rexruntime.dll','rexgpu-xenos.dll','TracyClient.dll')) { Copy-Item -LiteralPath (Join-Path $current $name) -Destination (Join-Path $stage 'sdk\bin') -Force }
-Get-ChildItem -LiteralPath $current -Filter '*.lib' | Copy-Item -Destination (Join-Path $stage 'sdk\lib') -Force
-# Package both graphics backends validated with FIFA Street.
-$backendRoot = Join-Path $stage 'sdk\backends'
-$d3d12Package = Join-Path $backendRoot 'D3D12'
-$vulkanPackage = Join-Path $backendRoot 'Vulkan'
-
-New-Item -ItemType Directory -Path $d3d12Package -Force | Out-Null
-New-Item -ItemType Directory -Path $vulkanPackage -Force | Out-Null
-
-$d3d12 = Join-Path $projectRoot 'ReXGlue\out\win-amd64-d3d12\Release'
-$vulkan = Join-Path $projectRoot 'ReXGlue\out\win-amd64-vulkan\Release'
-
-$expectedBackends = @{
- 'D3D12' = @{
- Source = $d3d12
- Destination = $d3d12Package
- RuntimeHash = '790B6B1B13765249160E53DCE6F28AF0F03B66D5D1AEDB1054949C50B13F04E8'
- GpuHash = '461A88F1D27C605106453B0F3C92BD72BD4BC166DCDC0BBF01E825BCEFB8418D'
- }
- 'Vulkan' = @{
- Source = $vulkan
- Destination = $vulkanPackage
- RuntimeHash = '115722CC5905D07FC6A6212B47692FFE6405DD1BA9F87CDA97F8DA2C25E4767A'
- GpuHash = '71FA61D82FF6134F1F407D682ACEBAC01F2B3B2DCEFCC34151A0C082B746BDD2'
- }
-}
-
-foreach ($backendName in @('D3D12', 'Vulkan')) {
- $backend = $expectedBackends[$backendName]
-
- foreach ($name in @('rexruntime.dll', 'rexgpu-xenos.dll')) {
- $source = Join-Path $backend.Source $name
-
- if (!(Test-Path -LiteralPath $source)) {
- throw "$backendName backend is missing: $source"
- }
-
- Copy-Item -LiteralPath $source -Destination $backend.Destination -Force
- }
-
- $runtimeFile = Join-Path $backend.Destination 'rexruntime.dll'
- $gpuFile = Join-Path $backend.Destination 'rexgpu-xenos.dll'
-
- $runtimeHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $runtimeFile).Hash
- $gpuHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $gpuFile).Hash
-
- if ($runtimeHash -ne $backend.RuntimeHash) {
- throw "$backendName rexruntime.dll hash mismatch. Expected $($backend.RuntimeHash), got $runtimeHash"
- }
-
- if ($gpuHash -ne $backend.GpuHash) {
- throw "$backendName rexgpu-xenos.dll hash mismatch. Expected $($backend.GpuHash), got $gpuHash"
- }
-}
-
-# Keep the Vulkan import libraries in the SDK used to compile the game.
-# The runtime DLLs themselves are installed from sdk\backends.
-foreach ($name in @('rexruntime.lib','rexgpu-xenos.lib')) {
- Copy-Item -LiteralPath (Join-Path $vulkan $name) -Destination (Join-Path $stage 'sdk\lib') -Force
-}
-Copy-Item -LiteralPath (Join-Path $projectRoot 'ReXGlue\include\rex') -Destination (Join-Path $stage 'sdk\include') -Recurse -Force
-Get-ChildItem -LiteralPath (Join-Path $stage 'sdk\bin') -Filter 'rexglue.before*' | Remove-Item
-New-Item -ItemType Directory -Path (Join-Path $stage 'compiler\bin') -Force | Out-Null
-foreach ($name in @('clang.exe','clang++.exe','lld-link.exe','llvm-rc.exe','llvm-mt.exe')) { Copy-Item -LiteralPath (Join-Path $LLVMRoot "bin\$name") -Destination (Join-Path $stage 'compiler\bin') }
-New-Item -ItemType Directory -Path (Join-Path $stage 'compiler\lib\clang') -Force | Out-Null
-Copy-Item -LiteralPath (Join-Path $LLVMRoot "lib\clang\$ClangResourceVersion") -Destination (Join-Path $stage 'compiler\lib\clang') -Recurse
-foreach ($name in @('cmake.exe','cmcldeps.exe')) { Copy-Item -LiteralPath (Join-Path $CMakeRoot "bin\$name") -Destination (Join-Path $stage 'compiler\bin') }
-Copy-Item -LiteralPath (Join-Path $CMakeRoot 'share') -Destination (Join-Path $stage 'compiler\share') -Recurse
-Copy-Item -LiteralPath $NinjaPath -Destination (Join-Path $stage 'compiler\bin')
-New-Item -ItemType Directory -Path (Join-Path $stage 'licenses') -Force | Out-Null
-Copy-Item -LiteralPath (Join-Path $projectRoot 'licenses\bundled-tools') -Destination (Join-Path $stage 'licenses\bundled-tools') -Recurse
-Copy-Item -LiteralPath (Join-Path $root 'FifaStreetSetupTool\ThirdParty\MonoGame-LICENSE.txt') -Destination (Join-Path $stage 'licenses\MonoGame-LZX-MS-PL.txt')
-Copy-Item -LiteralPath (Join-Path $projectRoot 'ReXGlue\LICENSE') -Destination (Join-Path $stage 'licenses\ReXGlue.txt')
-Copy-Item -LiteralPath (Join-Path $CMakeRoot 'doc\cmake\LICENSE.rst') -Destination (Join-Path $stage 'licenses\CMake.rst')
-$thirdPartyRoot = Join-Path $projectRoot 'ReXGlue\thirdparty'
-Get-ChildItem -LiteralPath $thirdPartyRoot -Recurse -File | Where-Object { $_.Name -match '^(LICENSE|COPYING|NOTICE|COPYRIGHT)(\..*)?$' } | ForEach-Object {
- $relative = $_.FullName.Substring($thirdPartyRoot.Length + 1)
- $target = Join-Path (Join-Path $stage 'licenses\ReXGlue-thirdparty') $relative
- New-Item -ItemType Directory -Path (Split-Path $target -Parent) -Force | Out-Null
- Copy-Item -LiteralPath $_.FullName -Destination $target
-}
-
-$forbidden = Get-ChildItem -LiteralPath $stage -Recurse -File | Where-Object { $_.Name -match '\.(iso|xex|big|bh)$|\.xex\.dll$|^fifastreet\.exe$|^fifastreet_.*_xex\.dll$|^fifastreet_recomp' }
-if ($forbidden) { throw 'O pacote contem ficheiros do jogo ou codigo recompilado.' }
-Add-Type -AssemblyName System.IO.Compression.FileSystem
-$bundle = Join-Path $root 'FifaStreetSetupTool\bundle.zip'
-if (Test-Path -LiteralPath $bundle) { Remove-Item -LiteralPath $bundle }
-[IO.Compression.ZipFile]::CreateFromDirectory($stage, $bundle, [IO.Compression.CompressionLevel]::Optimal, $false)
-$publish = Join-Path $stage 'published'
-dotnet publish (Join-Path $root 'FifaStreetSetupTool\FifaStreetSetupTool.csproj') -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:RuntimeFrameworkVersion=8.0.31 -o $publish
-if ($LASTEXITCODE -ne 0) { throw 'Falha ao publicar instalador.' }
-$Output = [IO.Path]::GetFullPath($Output)
-New-Item -ItemType Directory -Path (Split-Path $Output -Parent) -Force | Out-Null
-Copy-Item -LiteralPath (Join-Path $publish 'FifaStreetSetup.exe') -Destination $Output -Force
-Write-Host "Instalador unico criado: $Output"
-Write-Host "Pasta de verificacao: $stage"
+param(
+ [Parameter(Mandatory = $true)][string]$Output,
+ [string]$LLVMRoot = 'C:\Program Files\LLVM',
+ [string]$CMakeRoot = 'C:\Program Files\CMake',
+ [string]$NinjaPath = (Get-Command ninja.exe -ErrorAction Stop).Source,
+ [string]$ReXGlueRoot,
+ [string]$BackendManifest,
+ [string]$ClangResourceVersion
+)
+$ErrorActionPreference = 'Stop'
+if (-not $ClangResourceVersion) {
+ $ClangResourceVersion = (Get-ChildItem -LiteralPath (Join-Path $LLVMRoot 'lib\clang') -Directory |
+ Sort-Object { if ($_.Name.Contains('.')) { [version]$_.Name } else { [version]($_.Name + '.0') } } -Descending | Select-Object -First 1).Name
+}
+if (-not $ClangResourceVersion) { throw 'Clang resource directory was not found.' }
+$root = $PSScriptRoot
+$projectRoot = Split-Path $root -Parent
+. (Join-Path $root "BuildIntegrity.ps1")
+if (!$ReXGlueRoot) { $ReXGlueRoot = Join-Path $projectRoot "ReXGlue" }
+if (!$BackendManifest) { $BackendManifest = Join-Path $root "backend-manifest.json" }
+$backendInputs = Get-Content -LiteralPath $BackendManifest -Raw | ConvertFrom-Json
+$stage = Join-Path $env:TEMP ('FifaStreetPackage_' + [guid]::NewGuid().ToString('N'))
+$utf8 = [Text.UTF8Encoding]::new($false)
+New-Item -ItemType Directory -Path $stage | Out-Null
+foreach ($name in @('BuildFifaStreet.ps1', 'BuildIntegrity.ps1', 'README.md')) { Copy-Item -LiteralPath (Join-Path $root $name) -Destination $stage }
+$template = Join-Path $stage 'recomp-template'
+foreach ($name in @('', 'config', 'src', 'generated')) { New-Item -ItemType Directory -Path (Join-Path $template $name) -Force | Out-Null }
+foreach ($name in @('CMakeLists.txt','CMakePresets.json','fifastreet_manifest.toml','config\fifadllzf_overrides.toml','config\footballcompeng_overrides.toml','src\main.cpp','src\fifastreet_app.h','src\stubs.cpp','generated\rexglue.cmake')) {
+ Copy-Item -LiteralPath (Join-Path $root "recomp-template\$name") -Destination (Join-Path $template $name)
+}
+Copy-Item -LiteralPath (Join-Path $root 'recomp-template\src\fifastreet.ico') -Destination (Join-Path $template 'src\fifastreet.ico')
+[IO.File]::WriteAllText((Join-Path $template 'src\fifastreet.rc'), '1 ICON "fifastreet.ico"', $utf8)
+New-Item -ItemType Directory -Path (Join-Path $stage 'tools') | Out-Null
+Copy-Item -LiteralPath (Join-Path $root 'tools\extract-xiso.exe') -Destination (Join-Path $stage 'tools')
+New-Item -ItemType Directory -Path (Join-Path $stage 'payload\Game') -Force | Out-Null
+Copy-Item -LiteralPath (Join-Path $root 'payload\Game\fifastreet.toml') -Destination (Join-Path $stage 'payload\Game')
+dotnet publish (Join-Path $projectRoot 'Launcher\FifaStreetLauncher\FifaStreetLauncher.csproj') -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:RuntimeFrameworkVersion=8.0.31 -o (Join-Path $stage 'payload')
+if ($LASTEXITCODE -ne 0) { throw 'Falha ao publicar o launcher.' }
+Get-ChildItem -LiteralPath (Join-Path $stage 'payload') -Filter '*.pdb' | Remove-Item
+
+# Use the installed public SDK layout, with the current runtime and code generator.
+Copy-Item -LiteralPath (Join-Path $ReXGlueRoot 'out\install\win-amd64') -Destination (Join-Path $stage 'sdk') -Recurse
+$current = Join-Path $ReXGlueRoot 'out\win-amd64'
+$backendRuntime = Join-Path $ReXGlueRoot $backendInputs.backends.Vulkan.source
+foreach ($name in @('rexglue.exe','rexruntime.dll','rexgpu-xenos.dll','TracyClient.dll')) { Copy-Item -LiteralPath (Join-Path $current $name) -Destination (Join-Path $stage 'sdk\bin') -Force }
+Get-ChildItem -LiteralPath $current -Filter '*.lib' | Copy-Item -Destination (Join-Path $stage 'sdk\lib') -Force
+foreach ($name in @('rexruntime.dll','rexgpu-xenos.dll')) { Copy-Item -LiteralPath (Join-Path $backendRuntime $name) -Destination (Join-Path $stage 'sdk\bin') -Force }
+# Package both graphics backends validated with FIFA Street.
+$backendRoot = Join-Path $stage 'sdk\backends'
+$d3d12Package = Join-Path $backendRoot 'D3D12'
+$vulkanPackage = Join-Path $backendRoot 'Vulkan'
+
+New-Item -ItemType Directory -Path $d3d12Package -Force | Out-Null
+New-Item -ItemType Directory -Path $vulkanPackage -Force | Out-Null
+
+$vulkan = Join-Path $ReXGlueRoot $backendInputs.backends.Vulkan.source
+$expectedBackends = @{}
+foreach ($backendName in @('D3D12', 'Vulkan')) {
+ $inputBackend = $backendInputs.backends.$backendName
+ if (!$inputBackend -or $inputBackend.runtimeHash -notmatch '^[a-fA-F0-9]{64}$' -or $inputBackend.gpuHash -notmatch '^[a-fA-F0-9]{64}$') { throw "Invalid backend integrity manifest: $backendName" }
+ $expectedBackends[$backendName] = @{
+ Source = Join-Path $ReXGlueRoot $inputBackend.source
+ Destination = Join-Path $backendRoot $backendName
+ RuntimeHash = $inputBackend.runtimeHash
+ GpuHash = $inputBackend.gpuHash
+ }
+}
+
+foreach ($backendName in @('D3D12', 'Vulkan')) {
+ $backend = $expectedBackends[$backendName]
+
+ foreach ($name in @('rexruntime.dll', 'rexgpu-xenos.dll')) {
+ $source = Join-Path $backend.Source $name
+
+ if (!(Test-Path -LiteralPath $source)) {
+ throw "$backendName backend is missing: $source"
+ }
+
+ Copy-Item -LiteralPath $source -Destination $backend.Destination -Force
+ }
+
+ $runtimeFile = Join-Path $backend.Destination 'rexruntime.dll'
+ $gpuFile = Join-Path $backend.Destination 'rexgpu-xenos.dll'
+
+ $runtimeHash = (Get-InputSha256 $runtimeFile)
+ $gpuHash = (Get-InputSha256 $gpuFile)
+
+ if ($runtimeHash -ne $backend.RuntimeHash) {
+ throw "$backendName rexruntime.dll hash mismatch. Expected $($backend.RuntimeHash), got $runtimeHash"
+ }
+
+ if ($gpuHash -ne $backend.GpuHash) {
+ throw "$backendName rexgpu-xenos.dll hash mismatch. Expected $($backend.GpuHash), got $gpuHash"
+ }
+}
+
+# Keep the Vulkan import libraries in the SDK used to compile the game.
+# The runtime DLLs themselves are installed from sdk\backends.
+foreach ($name in @('rexruntime.lib','rexgpu-xenos.lib')) {
+ Copy-Item -LiteralPath (Join-Path $vulkan $name) -Destination (Join-Path $stage 'sdk\lib') -Force
+}
+Copy-Item -LiteralPath (Join-Path $ReXGlueRoot 'include\rex') -Destination (Join-Path $stage 'sdk\include') -Recurse -Force
+Get-ChildItem -LiteralPath (Join-Path $stage 'sdk\bin') -Filter 'rexglue.before*' | Remove-Item
+New-Item -ItemType Directory -Path (Join-Path $stage 'compiler\bin') -Force | Out-Null
+foreach ($name in @('clang.exe','clang++.exe','lld-link.exe','llvm-rc.exe','llvm-mt.exe')) { Copy-Item -LiteralPath (Join-Path $LLVMRoot "bin\$name") -Destination (Join-Path $stage 'compiler\bin') }
+New-Item -ItemType Directory -Path (Join-Path $stage 'compiler\lib\clang') -Force | Out-Null
+Copy-Item -LiteralPath (Join-Path $LLVMRoot "lib\clang\$ClangResourceVersion") -Destination (Join-Path $stage 'compiler\lib\clang') -Recurse
+foreach ($name in @('cmake.exe','cmcldeps.exe')) { Copy-Item -LiteralPath (Join-Path $CMakeRoot "bin\$name") -Destination (Join-Path $stage 'compiler\bin') }
+Copy-Item -LiteralPath (Join-Path $CMakeRoot 'share') -Destination (Join-Path $stage 'compiler\share') -Recurse
+Copy-Item -LiteralPath $NinjaPath -Destination (Join-Path $stage 'compiler\bin')
+New-Item -ItemType Directory -Path (Join-Path $stage 'licenses') -Force | Out-Null
+Copy-Item -LiteralPath (Join-Path $projectRoot 'licenses\bundled-tools') -Destination (Join-Path $stage 'licenses\bundled-tools') -Recurse
+Copy-Item -LiteralPath (Join-Path $root 'FifaStreetSetupTool\ThirdParty\MonoGame-LICENSE.txt') -Destination (Join-Path $stage 'licenses\MonoGame-LZX-MS-PL.txt')
+Copy-Item -LiteralPath (Join-Path $ReXGlueRoot 'LICENSE') -Destination (Join-Path $stage 'licenses\ReXGlue.txt')
+Copy-Item -LiteralPath (Join-Path $CMakeRoot 'doc\cmake\LICENSE.rst') -Destination (Join-Path $stage 'licenses\CMake.rst')
+$thirdPartyRoot = Join-Path $ReXGlueRoot 'thirdparty'
+Get-ChildItem -LiteralPath $thirdPartyRoot -Recurse -File | Where-Object { $_.Name -match '^(LICENSE|COPYING|NOTICE|COPYRIGHT)(\..*)?$' } | ForEach-Object {
+ $relative = $_.FullName.Substring($thirdPartyRoot.Length + 1)
+ $target = Join-Path (Join-Path $stage 'licenses\ReXGlue-thirdparty') $relative
+ New-Item -ItemType Directory -Path (Split-Path $target -Parent) -Force | Out-Null
+ Copy-Item -LiteralPath $_.FullName -Destination $target
+}
+
+$forbidden = Get-ChildItem -LiteralPath $stage -Recurse -File | Where-Object { $_.Name -match '\.(iso|xex|big|bh)$|\.xex\.dll$|^fifastreet\.exe$|^fifastreet_.*_xex\.dll$|^fifastreet_recomp' }
+if ($forbidden) { throw 'O pacote contem ficheiros do jogo ou codigo recompilado.' }
+Add-Type -AssemblyName System.IO.Compression.FileSystem
+$bundle = Join-Path $root 'FifaStreetSetupTool\bundle.zip'
+if (Test-Path -LiteralPath $bundle) { Remove-Item -LiteralPath $bundle }
+[IO.Compression.ZipFile]::CreateFromDirectory($stage, $bundle, [IO.Compression.CompressionLevel]::Optimal, $false)
+$publish = Join-Path $stage 'published'
+dotnet publish (Join-Path $root 'FifaStreetSetupTool\FifaStreetSetupTool.csproj') -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:RuntimeFrameworkVersion=8.0.31 -o $publish
+if ($LASTEXITCODE -ne 0) { throw 'Falha ao publicar instalador.' }
+$Output = [IO.Path]::GetFullPath($Output)
+New-Item -ItemType Directory -Path (Split-Path $Output -Parent) -Force | Out-Null
+Copy-Item -LiteralPath (Join-Path $publish 'FifaStreetSetup.exe') -Destination $Output -Force
+Write-Host "Instalador unico criado: $Output"
+Write-Host "Pasta de verificacao: $stage"
diff --git a/Installer/FifaStreetSetupTool/CreditPatch.cs b/Installer/FifaStreetSetupTool/CreditPatch.cs
index 2ac82d4..967a3d0 100644
--- a/Installer/FifaStreetSetupTool/CreditPatch.cs
+++ b/Installer/FifaStreetSetupTool/CreditPatch.cs
@@ -1,169 +1,167 @@
-using System.Buffers.Binary;
-using System.IO.Compression;
-using System.Reflection;
-using System.Security.Cryptography;
-using System.Text;
-using System.Text.Json;
-using Microsoft.Xna.Framework.Content;
-
-namespace FifaStreetSetupTool;
-
-internal static class CreditPatch
-{
- sealed record Edit(string Name, string SourceHash, string DecodedHash, string OutputHash, int Length, byte[] Xor);
- sealed record Recipe(string Name, string SourceHash, string OutputHash, Edit[] Edits);
- sealed record Entry(string Name, int Offset, int Length, int TablePosition);
- static int U(byte[] b, int p) => checked((int)BinaryPrimitives.ReadUInt32BigEndian(b.AsSpan(p, 4)));
- static void Put(byte[] b, int p, int n) => BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(p, 4), checked((uint)n));
- static string Hash(byte[] b) => Convert.ToHexString(SHA256.HashData(b)).ToLowerInvariant();
- static void Require(bool ok, string message) { if (!ok) throw new InvalidDataException(message); }
-
- static List<Entry> Index(byte[] b, long fileLength)
- {
- Require(b.Length >= 16 && (Encoding.ASCII.GetString(b, 0, 4) is "BIG4" or "BIGF"), "Unsupported BIG archive.");
- int count = U(b, 8), end = U(b, 12), p = 16;
- Require(count <= 100000 && end <= b.Length, "Invalid BIG directory.");
- var entries = new List<Entry>();
- for (int i = 0; i < count; i++)
- {
- Require(p + 8 < end, "Truncated BIG directory.");
- int offset = U(b, p), length = U(b, p + 4), zero = Array.IndexOf(b, (byte)0, p + 8, end - p - 8);
- Require(zero >= 0 && offset >= end && (long)offset + length <= fileLength, "Invalid BIG entry.");
- entries.Add(new(Encoding.UTF8.GetString(b, p + 8, zero - p - 8), offset, length, p)); p = zero + 1;
- }
- return entries;
- }
-
- internal static byte[] DecodeChunk(byte[] b)
- {
- Require(b.Length > 48 && Encoding.ASCII.GetString(b, 0, 8) == "chunklzx" && U(b, 8) == 2, "Unsupported menu compression.");
- int full = U(b, 12), chunk = U(b, 16), p = 40;
- Require(full <= 16 * 1024 * 1024 && chunk is > 0 and <= 1024 * 1024, "Invalid menu size.");
- using var output = new MemoryStream();
- while (output.Length < full)
- {
- InstallerEngine.CancellationToken.ThrowIfCancellationRequested();
- p = (p + 7) / 16 * 16 + 8;
- int n = U(b, p), kind = U(b, p + 4); p += 8;
- Require(n > 0 && p + (long)n <= b.Length, "Truncated menu chunk.");
- int target = Math.Min(chunk, full - (int)output.Length), end = p + n;
- if (kind == 4) { Require(n == target, "Invalid raw chunk."); output.Write(b, p, n); p = end; continue; }
- Require(kind == 3, "Unknown menu chunk type.");
- var decoder = new LzxDecoder(17); int produced = 0;
- while (p < end && produced < target)
- {
- int outSize = 32768, inSize;
- if (b[p] == 255) { Require(p + 5 <= end, "Truncated LZX frame."); outSize = (b[p + 1] << 8) | b[p + 2]; inSize = (b[p + 3] << 8) | b[p + 4]; p += 5; }
- else { Require(p + 2 <= end, "Truncated LZX frame."); inSize = (b[p] << 8) | b[p + 1]; p += 2; }
- Require(inSize > 0 && p + inSize <= end && outSize > 0 && produced + outSize <= target, "Invalid LZX frame.");
- using var input = new MemoryStream(b, p, inSize, false);
- Require(decoder.Decompress(input, inSize, output, outSize) == 0, "Menu decompression failed.");
- p += inSize; produced += outSize;
- }
- Require(produced == target, "Incomplete menu chunk."); p = end;
- }
- Require(output.Length == full, "Incomplete menu archive."); return output.ToArray();
- }
-
- static byte[] DecodeRefPack(byte[] b)
- {
- if (b.Length < 5 || b[0] != 0x10 || b[1] != 0xfb) return b;
- int length = (b[2] << 16) | (b[3] << 8) | b[4], p = 5, at = 0;
- Require(length <= 16 * 1024 * 1024, "Invalid texture size."); var result = new byte[length];
- while (at < length)
- {
- int c = b[p++], literals, copies = 0, distance = 0;
- if (c < 0x80) { int d = b[p++]; literals = c & 3; copies = ((c & 0x1c) >> 2) + 3; distance = ((c & 0x60) << 3) + d + 1; }
- else if (c < 0xc0) { int d = b[p++], e = b[p++]; literals = d >> 6; copies = (c & 0x3f) + 4; distance = ((d & 0x3f) << 8) + e + 1; }
- else if (c < 0xe0) { int d = b[p++], e = b[p++], f = b[p++]; literals = c & 3; copies = ((c & 0x0c) << 6) + f + 5; distance = ((c & 0x10) << 12) + (d << 8) + e + 1; }
- else if (c < 0xfc) literals = ((c & 0x1f) << 2) + 4;
- else literals = c & 3;
- Require(p + literals <= b.Length && at + literals + copies <= length, "Invalid texture data.");
- Buffer.BlockCopy(b, p, result, at, literals); p += literals; at += literals;
- Require(copies == 0 || distance <= at, "Invalid texture reference.");
- for (int i = 0; i < copies; i++) { result[at] = result[at - distance]; at++; }
- if (c >= 0xfc) break;
- }
- Require(at == length, "Incomplete texture data."); return result;
- }
-
- static byte[] Modify(byte[] compressed, Recipe recipe)
- {
- if (Hash(compressed) == recipe.OutputHash) return compressed;
- Require(Hash(compressed) == recipe.SourceHash, "This FIFA Street ISO version is not supported by the menu credit patch.");
- byte[] original = DecodeChunk(compressed); var entries = Index(original, original.Length);
- var data = entries.ToDictionary(e => e.Name, e => original.AsSpan(e.Offset, e.Length).ToArray());
- foreach (var edit in recipe.Edits)
- {
- byte[] source = data[edit.Name]; Require(Hash(source) == edit.SourceHash, "Unexpected menu asset.");
- source = DecodeRefPack(source); Require(Hash(source) == edit.DecodedHash, "Unexpected decoded menu asset.");
- Require(edit.Length >= source.Length && edit.Xor.Length == edit.Length, "Invalid credit recipe.");
- var changed = new byte[edit.Length]; source.CopyTo(changed, 0);
- for (int i = 0; i < changed.Length; i++) changed[i] ^= edit.Xor[i];
- Require(Hash(changed) == edit.OutputHash, "Credit asset verification failed."); data[edit.Name] = changed;
- }
- int headerLength = 16 + entries.Sum(e => 9 + Encoding.UTF8.GetByteCount(e.Name));
- using var output = new MemoryStream(); output.SetLength((headerLength + 63) & ~63); output.Position = output.Length;
- var header = new byte[headerLength]; Encoding.ASCII.GetBytes("BIGF").CopyTo(header, 0); Put(header, 8, entries.Count); Put(header, 12, headerLength);
- int p = 16;
- foreach (var e in entries)
- {
- byte[] asset = data[e.Name], name = Encoding.UTF8.GetBytes(e.Name);
- Put(header, p, (int)output.Position); Put(header, p + 4, asset.Length); name.CopyTo(header, p + 8); p += 9 + name.Length;
- output.Write(asset); int padding = (int)((-output.Position) & 63); output.Write(new byte[padding]);
- }
- BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(4, 4), (uint)output.Length);
- output.Position = 0; output.Write(header); byte[] result = output.ToArray();
- Require(Hash(result) == recipe.OutputHash, "Menu archive verification failed."); return result;
- }
-
- internal static void Apply(string gameData)
- {
- using var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream("credit-patch.json.gz")!;
- using var gzip = new GZipStream(resource, CompressionMode.Decompress);
- Recipe[] recipes = JsonSerializer.Deserialize<Recipe[]>(gzip)!;
- string big = Path.Combine(gameData, "data1.big"), bh = Path.Combine(gameData, "data1.bh");
- string staged = big + ".credit.tmp", stagedBh = bh + ".credit.tmp", backup = big + ".credit.rollback";
- Require(!File.Exists(staged) && !File.Exists(stagedBh) && !File.Exists(backup), "An interrupted menu patch needs recovery before retrying.");
- byte[] index = File.ReadAllBytes(bh), header;
- var replacements = new List<(Entry Entry, byte[] Data, int BhPosition)>();
- using (var input = new FileStream(big, FileMode.Open, FileAccess.Read, FileShare.Read))
- {
- header = new byte[16]; input.ReadExactly(header); int tableEnd = U(header, 12);
- Require(tableEnd <= 8 * 1024 * 1024, "Invalid archive directory size."); Array.Resize(ref header, tableEnd); input.ReadExactly(header.AsSpan(16));
- var entries = Index(header, input.Length);
- foreach (var recipe in recipes)
- {
- Entry e = entries.Single(x => x.Name == recipe.Name); byte[] data = new byte[e.Length]; input.Position = e.Offset; input.ReadExactly(data);
- if (Hash(data) == recipe.OutputHash) continue;
- byte[] modified = Modify(data, recipe); var matches = new List<int>();
- for (int i = 16; i + 8 <= index.Length; i += 20) if (U(index, i) == e.Offset && U(index, i + 4) == e.Length) matches.Add(i);
- Require(matches.Count == 1, "The companion archive index does not match this ISO."); replacements.Add((e, modified, matches[0]));
- }
- }
- if (replacements.Count == 0) { Console.WriteLine("Menu credits already applied."); return; }
- bool committed = false;
- try
- {
- using (var input = File.OpenRead(big))
- using (var output = new FileStream(staged, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None))
- {
- byte[] buffer = new byte[1024 * 1024]; int n;
- while ((n = input.Read(buffer)) > 0) { InstallerEngine.CancellationToken.ThrowIfCancellationRequested(); output.Write(buffer, 0, n); }
- foreach (var item in replacements)
- {
- output.Write(new byte[(int)((-output.Position) & 63)]); int offset = checked((int)output.Position); output.Write(item.Data);
- Put(header, item.Entry.TablePosition, offset); Put(header, item.Entry.TablePosition + 4, item.Data.Length);
- Put(index, item.BhPosition, offset); Put(index, item.BhPosition + 4, item.Data.Length);
- }
- BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(4, 4), checked((uint)output.Length)); output.Position = 0; output.Write(header); output.Flush(true);
- }
- File.WriteAllBytes(stagedBh, index); InstallerEngine.CancellationToken.ThrowIfCancellationRequested();
- File.Replace(staged, big, backup); committed = true;
- File.Move(stagedBh, bh, true); File.Delete(backup);
- Console.WriteLine("PORTED BY: SAMUELITODAVILA applied to the start screen and main menu.");
- }
- catch { if (committed && File.Exists(backup)) File.Move(backup, big, true); throw; }
- finally { if (File.Exists(staged)) File.Delete(staged); if (File.Exists(stagedBh)) File.Delete(stagedBh); }
- }
-}
+using System.Buffers.Binary;
+using System.IO.Compression;
+using System.Reflection;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using Microsoft.Xna.Framework.Content;
+
+namespace FifaStreetSetupTool;
+
+internal static class CreditPatch
+{
+ sealed record Edit(string Name, string SourceHash, string DecodedHash, string OutputHash, int Length, byte[] Xor);
+ sealed record Recipe(string Name, string SourceHash, string OutputHash, Edit[] Edits);
+ sealed record Entry(string Name, int Offset, int Length, int TablePosition);
+ static int U(byte[] b, int p) => checked((int)BinaryPrimitives.ReadUInt32BigEndian(b.AsSpan(p, 4)));
+ static void Put(byte[] b, int p, int n) => BinaryPrimitives.WriteUInt32BigEndian(b.AsSpan(p, 4), checked((uint)n));
+ static string Hash(byte[] b) => Convert.ToHexString(SHA256.HashData(b)).ToLowerInvariant();
+ static void Require(bool ok, string message) { if (!ok) throw new InvalidDataException(message); }
+
+ static List<Entry> Index(byte[] b, long fileLength)
+ {
+ Require(b.Length >= 16 && (Encoding.ASCII.GetString(b, 0, 4) is "BIG4" or "BIGF"), "Unsupported BIG archive.");
+ int count = U(b, 8), end = U(b, 12), p = 16;
+ Require(count <= 100000 && end <= b.Length, "Invalid BIG directory.");
+ var entries = new List<Entry>();
+ for (int i = 0; i < count; i++)
+ {
+ Require(p + 8 < end, "Truncated BIG directory.");
+ int offset = U(b, p), length = U(b, p + 4), zero = Array.IndexOf(b, (byte)0, p + 8, end - p - 8);
+ Require(zero >= 0 && offset >= end && (long)offset + length <= fileLength, "Invalid BIG entry.");
+ entries.Add(new(Encoding.UTF8.GetString(b, p + 8, zero - p - 8), offset, length, p)); p = zero + 1;
+ }
+ return entries;
+ }
+
+ internal static byte[] DecodeChunk(byte[] b)
+ {
+ Require(b.Length > 48 && Encoding.ASCII.GetString(b, 0, 8) == "chunklzx" && U(b, 8) == 2, "Unsupported menu compression.");
+ int full = U(b, 12), chunk = U(b, 16), p = 40;
+ Require(full <= 16 * 1024 * 1024 && chunk is > 0 and <= 1024 * 1024, "Invalid menu size.");
+ using var output = new MemoryStream();
+ while (output.Length < full)
+ {
+ InstallerEngine.CancellationToken.ThrowIfCancellationRequested();
+ p = (p + 7) / 16 * 16 + 8;
+ int n = U(b, p), kind = U(b, p + 4); p += 8;
+ Require(n > 0 && p + (long)n <= b.Length, "Truncated menu chunk.");
+ int target = Math.Min(chunk, full - (int)output.Length), end = p + n;
+ if (kind == 4) { Require(n == target, "Invalid raw chunk."); output.Write(b, p, n); p = end; continue; }
+ Require(kind == 3, "Unknown menu chunk type.");
+ var decoder = new LzxDecoder(17); int produced = 0;
+ while (p < end && produced < target)
+ {
+ int outSize = 32768, inSize;
+ if (b[p] == 255) { Require(p + 5 <= end, "Truncated LZX frame."); outSize = (b[p + 1] << 8) | b[p + 2]; inSize = (b[p + 3] << 8) | b[p + 4]; p += 5; }
+ else { Require(p + 2 <= end, "Truncated LZX frame."); inSize = (b[p] << 8) | b[p + 1]; p += 2; }
+ Require(inSize > 0 && p + inSize <= end && outSize > 0 && produced + outSize <= target, "Invalid LZX frame.");
+ using var input = new MemoryStream(b, p, inSize, false);
+ Require(decoder.Decompress(input, inSize, output, outSize) == 0, "Menu decompression failed.");
+ p += inSize; produced += outSize;
+ }
+ Require(produced == target, "Incomplete menu chunk."); p = end;
+ }
+ Require(output.Length == full, "Incomplete menu archive."); return output.ToArray();
+ }
+
+ static byte[] DecodeRefPack(byte[] b)
+ {
+ if (b.Length < 5 || b[0] != 0x10 || b[1] != 0xfb) return b;
+ int length = (b[2] << 16) | (b[3] << 8) | b[4], p = 5, at = 0;
+ Require(length <= 16 * 1024 * 1024, "Invalid texture size."); var result = new byte[length];
+ while (at < length)
+ {
+ int c = b[p++], literals, copies = 0, distance = 0;
+ if (c < 0x80) { int d = b[p++]; literals = c & 3; copies = ((c & 0x1c) >> 2) + 3; distance = ((c & 0x60) << 3) + d + 1; }
+ else if (c < 0xc0) { int d = b[p++], e = b[p++]; literals = d >> 6; copies = (c & 0x3f) + 4; distance = ((d & 0x3f) << 8) + e + 1; }
+ else if (c < 0xe0) { int d = b[p++], e = b[p++], f = b[p++]; literals = c & 3; copies = ((c & 0x0c) << 6) + f + 5; distance = ((c & 0x10) << 12) + (d << 8) + e + 1; }
+ else if (c < 0xfc) literals = ((c & 0x1f) << 2) + 4;
+ else literals = c & 3;
+ Require(p + literals <= b.Length && at + literals + copies <= length, "Invalid texture data.");
+ Buffer.BlockCopy(b, p, result, at, literals); p += literals; at += literals;
+ Require(copies == 0 || distance <= at, "Invalid texture reference.");
+ for (int i = 0; i < copies; i++) { result[at] = result[at - distance]; at++; }
+ if (c >= 0xfc) break;
+ }
+ Require(at == length, "Incomplete texture data."); return result;
+ }
+
+ static byte[] Modify(byte[] compressed, Recipe recipe)
+ {
+ if (Hash(compressed) == recipe.OutputHash) return compressed;
+ Require(Hash(compressed) == recipe.SourceHash, "This FIFA Street ISO version is not supported by the menu credit patch.");
+ byte[] original = DecodeChunk(compressed); var entries = Index(original, original.Length);
+ var data = entries.ToDictionary(e => e.Name, e => original.AsSpan(e.Offset, e.Length).ToArray());
+ foreach (var edit in recipe.Edits)
+ {
+ byte[] source = data[edit.Name]; Require(Hash(source) == edit.SourceHash, "Unexpected menu asset.");
+ source = DecodeRefPack(source); Require(Hash(source) == edit.DecodedHash, "Unexpected decoded menu asset.");
+ Require(edit.Length >= source.Length && edit.Xor.Length == edit.Length, "Invalid credit recipe.");
+ var changed = new byte[edit.Length]; source.CopyTo(changed, 0);
+ for (int i = 0; i < changed.Length; i++) changed[i] ^= edit.Xor[i];
+ Require(Hash(changed) == edit.OutputHash, "Credit asset verification failed."); data[edit.Name] = changed;
+ }
+ int headerLength = 16 + entries.Sum(e => 9 + Encoding.UTF8.GetByteCount(e.Name));
+ using var output = new MemoryStream(); output.SetLength((headerLength + 63) & ~63); output.Position = output.Length;
+ var header = new byte[headerLength]; Encoding.ASCII.GetBytes("BIGF").CopyTo(header, 0); Put(header, 8, entries.Count); Put(header, 12, headerLength);
+ int p = 16;
+ foreach (var e in entries)
+ {
+ byte[] asset = data[e.Name], name = Encoding.UTF8.GetBytes(e.Name);
+ Put(header, p, (int)output.Position); Put(header, p + 4, asset.Length); name.CopyTo(header, p + 8); p += 9 + name.Length;
+ output.Write(asset); int padding = (int)((-output.Position) & 63); output.Write(new byte[padding]);
+ }
+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(4, 4), (uint)output.Length);
+ output.Position = 0; output.Write(header); byte[] result = output.ToArray();
+ Require(Hash(result) == recipe.OutputHash, "Menu archive verification failed."); return result;
+ }
+
+ internal static void Apply(string gameData)
+ {
+ using var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream("credit-patch.json.gz")!;
+ using var gzip = new GZipStream(resource, CompressionMode.Decompress);
+ Recipe[] recipes = JsonSerializer.Deserialize<Recipe[]>(gzip)!;
+ string big = Path.Combine(gameData, "data1.big"), bh = Path.Combine(gameData, "data1.bh");
+ string staged = big + ".credit.tmp", stagedBh = bh + ".credit.tmp", backup = big + ".credit.rollback";
+ FilePairTransaction.Recover(big, bh);
+ Require(!File.Exists(staged) && !File.Exists(stagedBh) && !File.Exists(backup), "An interrupted menu patch needs recovery before retrying.");
+ byte[] index = File.ReadAllBytes(bh), header;
+ var replacements = new List<(Entry Entry, byte[] Data, int BhPosition)>();
+ using (var input = new FileStream(big, FileMode.Open, FileAccess.Read, FileShare.Read))
+ {
+ header = new byte[16]; input.ReadExactly(header); int tableEnd = U(header, 12);
+ Require(tableEnd <= 8 * 1024 * 1024, "Invalid archive directory size."); Array.Resize(ref header, tableEnd); input.ReadExactly(header.AsSpan(16));
+ var entries = Index(header, input.Length);
+ foreach (var recipe in recipes)
+ {
+ Entry e = entries.Single(x => x.Name == recipe.Name); byte[] data = new byte[e.Length]; input.Position = e.Offset; input.ReadExactly(data);
+ if (Hash(data) == recipe.OutputHash) continue;
+ byte[] modified = Modify(data, recipe); var matches = new List<int>();
+ for (int i = 16; i + 8 <= index.Length; i += 20) if (U(index, i) == e.Offset && U(index, i + 4) == e.Length) matches.Add(i);
+ Require(matches.Count == 1, "The companion archive index does not match this ISO."); replacements.Add((e, modified, matches[0]));
+ }
+ }
+ if (replacements.Count == 0) { Console.WriteLine("Menu credits already applied."); return; }
+ try
+ {
+ using (var input = File.OpenRead(big))
+ using (var output = new FileStream(staged, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None))
+ {
+ byte[] buffer = new byte[1024 * 1024]; int n;
+ while ((n = input.Read(buffer)) > 0) { InstallerEngine.CancellationToken.ThrowIfCancellationRequested(); output.Write(buffer, 0, n); }
+ foreach (var item in replacements)
+ {
+ output.Write(new byte[(int)((-output.Position) & 63)]); int offset = checked((int)output.Position); output.Write(item.Data);
+ Put(header, item.Entry.TablePosition, offset); Put(header, item.Entry.TablePosition + 4, item.Data.Length);
+ Put(index, item.BhPosition, offset); Put(index, item.BhPosition + 4, item.Data.Length);
+ }
+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(4, 4), checked((uint)output.Length)); output.Position = 0; output.Write(header); output.Flush(true);
+ }
+ File.WriteAllBytes(stagedBh, index); InstallerEngine.CancellationToken.ThrowIfCancellationRequested();
+ FilePairTransaction.Commit(big, staged, bh, stagedBh);
+ Console.WriteLine("PORTED BY: SAMUELITODAVILA applied to the start screen and main menu.");
+ }
+ finally { FilePairTransaction.TryDelete(staged); FilePairTransaction.TryDelete(stagedBh); }
+ }
+}
diff --git a/Installer/FifaStreetSetupTool/FifaStreetSetupTool.csproj b/Installer/FifaStreetSetupTool/FifaStreetSetupTool.csproj
index bec80d8..5ef6530 100644
--- a/Installer/FifaStreetSetupTool/FifaStreetSetupTool.csproj
+++ b/Installer/FifaStreetSetupTool/FifaStreetSetupTool.csproj
@@ -13,7 +13,9 @@
<EmbeddedResource Include="cover.jpg" LogicalName="cover.jpg" />
<EmbeddedResource Include="credit-patch.json.gz" LogicalName="credit-patch.json.gz" />
<EmbeddedResource Include="..\recomp-template\src\fifastreet.ico" LogicalName="fifastreet.ico" />
- <EmbeddedResource Include="bundle.zip" LogicalName="bundle.zip" Condition="Exists('bundle.zip')" />
+ <EmbeddedResource Include="bundle.zip" LogicalName="bundle.zip" Condition="'$(BundlePath)' == '' and Exists('bundle.zip')" />
+ <EmbeddedResource Include="$(BundlePath)" LogicalName="bundle.zip" Condition="'$(BundlePath)' != ''" />
+ <EmbeddedResource Include="$(PrecompiledManifest)" LogicalName="precompiled-mode" Condition="'$(PrecompiledManifest)' != ''" />
</ItemGroup>
</Project>
diff --git a/Installer/FifaStreetSetupTool/FilePairTransaction.cs b/Installer/FifaStreetSetupTool/FilePairTransaction.cs
new file mode 100644
index 0000000..c9ee479
--- /dev/null
+++ b/Installer/FifaStreetSetupTool/FilePairTransaction.cs
@@ -0,0 +1,84 @@
+namespace FifaStreetSetupTool;
+
+// A recoverable transaction for the BIG archive and its companion index.
+// Recovery copies backups (rather than moving them), so recovery itself can
+// be interrupted and repeated without losing either original.
+internal static class FilePairTransaction
+{
+ static void WriteState(string marker, string state)
+ {
+ string temporary = marker + ".tmp";
+ using (var file = new FileStream(temporary, FileMode.Create, FileAccess.Write, FileShare.None))
+ {
+ byte[] bytes = System.Text.Encoding.ASCII.GetBytes(state);
+ file.Write(bytes);
+ file.Flush(true);
+ }
+ File.Move(temporary, marker, true);
+ }
+
+ internal static bool TryDelete(string path)
+ {
+ try { File.Delete(path); return true; }
+ catch (IOException error) { Console.WriteLine("Cleanup pending: " + error.Message); return false; }
+ catch (UnauthorizedAccessException error) { Console.WriteLine("Cleanup pending: " + error.Message); return false; }
+ }
+
+ static void Cleanup(string first, string second, string marker)
+ {
+ bool cleaned = TryDelete(first + ".credit.rollback");
+ cleaned &= TryDelete(second + ".credit.rollback");
+ cleaned &= TryDelete(first + ".credit.tmp");
+ cleaned &= TryDelete(second + ".credit.tmp");
+ cleaned &= TryDelete(marker + ".tmp");
+ // Retain the state until cleanup is finished. A cleanup failure must
+ // never turn a successfully committed new pair back into an old pair.
+ if (cleaned) TryDelete(marker);
+ }
+
+ internal static void Recover(string first, string second)
+ {
+ string marker = first + ".credit.transaction";
+ if (!File.Exists(marker)) return;
+ string state = File.ReadAllText(marker);
+ if (state == "prepared")
+ {
+ foreach (string target in new[] { first, second })
+ {
+ string backup = target + ".credit.rollback";
+ if (File.Exists(backup)) File.Copy(backup, target, true);
+ }
+ // After both originals are restored, a crash during cleanup is
+ // safe: the following startup only needs to finish cleanup.
+ WriteState(marker, "recovered");
+ }
+ else if (state != "committed" && state != "recovered")
+ throw new InvalidDataException("Unknown menu patch recovery state.");
+ Cleanup(first, second, marker);
+ }
+
+ internal static void Commit(string first, string stagedFirst, string second,
+ string stagedSecond, Action<string>? checkpoint = null)
+ {
+ Recover(first, second);
+ string marker = first + ".credit.transaction";
+ if (File.Exists(marker) || File.Exists(first + ".credit.rollback") ||
+ File.Exists(second + ".credit.rollback"))
+ throw new IOException("Previous menu patch recovery must finish before retrying.");
+ WriteState(marker, "prepared");
+ try
+ {
+ File.Replace(stagedFirst, first, first + ".credit.rollback");
+ checkpoint?.Invoke("after-first");
+ File.Replace(stagedSecond, second, second + ".credit.rollback");
+ checkpoint?.Invoke("after-second");
+ WriteState(marker, "committed");
+ }
+ catch
+ {
+ Recover(first, second);
+ throw;
+ }
+ Cleanup(first, second, marker);
+ }
+}
diff --git a/Installer/FifaStreetSetupTool/InstallationUpdate.cs b/Installer/FifaStreetSetupTool/InstallationUpdate.cs
new file mode 100644
index 0000000..97c5618
--- /dev/null
+++ b/Installer/FifaStreetSetupTool/InstallationUpdate.cs
@@ -0,0 +1,77 @@
+namespace FifaStreetSetupTool;
+
+internal static class InstallationUpdate
+{
+ internal static bool IsInstallation(string root) =>
+ File.Exists(Path.Combine(root, "Game", "fifastreet.exe")) &&
+ File.Exists(Path.Combine(root, "GameData", "default.xex"));
+
+ internal static void Apply(string bundle, string root)
+ {
+ root = Path.GetFullPath(root);
+ if (!IsInstallation(root)) throw new IOException("Select the existing installation folder containing Game and GameData.");
+ Console.WriteLine("Checking the installed game version and update files...");
+ var package = PrecompiledPackage.Validate(bundle, Path.Combine(root, "GameData"));
+ var files = package.Payload.Keys.Where(name => !name.Equals("Game/fifastreet.toml", StringComparison.OrdinalIgnoreCase) || !File.Exists(Path.Combine(root, name))).ToArray();
+ // Validate all paths and locks before changing any installed file.
+ foreach (string name in files)
+ {
+ string target = Path.GetFullPath(Path.Combine(root, name));
+ for (var folder = new DirectoryInfo(Path.GetDirectoryName(target)!); folder != null; folder = folder.Parent)
+ {
+ if (folder.Exists && (folder.Attributes & FileAttributes.ReparsePoint) != 0)
+ throw new IOException("Updates cannot follow linked installation folders.");
+ }
+ if (File.Exists(target))
+ {
+ if ((File.GetAttributes(target) & FileAttributes.ReparsePoint) != 0) throw new IOException("Updates cannot replace linked files.");
+ using var locked = new FileStream(target, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
+ }
+ }
+ string backupRoot = Path.Combine(root, ".updates");
+ if (Directory.Exists(backupRoot) && (File.GetAttributes(backupRoot) & FileAttributes.ReparsePoint) != 0)
+ throw new IOException("Updates cannot use a linked backup folder.");
+ string backup = Path.Combine(backupRoot, DateTime.UtcNow.ToString("yyyyMMdd-HHmmss") + "-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(backup);
+ var touched = new List<(string Target, string? Saved)>();
+ try
+ {
+ Console.WriteLine("Installing update. Saves, game data and preferences are preserved...");
+ foreach (string name in files)
+ {
+ InstallerEngine.CancellationToken.ThrowIfCancellationRequested();
+ string target = Path.Combine(root, name), saved = Path.Combine(backup, name);
+ bool existed = File.Exists(target);
+ if (existed)
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(saved)!);
+ File.Copy(target, saved);
+ }
+ touched.Add((target, existed ? saved : null));
+ Directory.CreateDirectory(Path.GetDirectoryName(target)!);
+ File.Copy(Path.Combine(bundle, "payload", name), target, true);
+ Console.WriteLine("Updated " + name);
+ }
+ InstallerEngine.CancellationToken.ThrowIfCancellationRequested();
+ File.WriteAllText(Path.Combine(backup, "update-complete.txt"), "Previous binaries retained. GameData and user preferences were not modified.");
+ Console.WriteLine("Update complete. Previous files saved at: " + backup);
+ }
+ catch (Exception original)
+ {
+ // Roll back without consulting cancellation: restoration must finish.
+ var failures = new List<Exception>();
+ foreach (var file in touched.AsEnumerable().Reverse())
+ try
+ {
+ if (file.Saved != null) File.Copy(file.Saved, file.Target, true);
+ else if (File.Exists(file.Target)) File.Delete(file.Target);
+ }
+ catch (Exception error) { failures.Add(error); }
+ if (failures.Count != 0)
+ throw new IOException("The update failed and some files could not be restored. Keep the backup at: " + backup,
+ new AggregateException(new[] { original }.Concat(failures)));
+ Console.WriteLine("Update stopped. Previous files restored.");
+ throw;
+ }
+ }
+}
diff --git a/Installer/FifaStreetSetupTool/PrecompiledPackage.cs b/Installer/FifaStreetSetupTool/PrecompiledPackage.cs
new file mode 100644
index 0000000..a6b86b0
--- /dev/null
+++ b/Installer/FifaStreetSetupTool/PrecompiledPackage.cs
@@ -0,0 +1,54 @@
+using System.Security.Cryptography;
+using System.Text.Json;
+using System.Reflection;
+
+namespace FifaStreetSetupTool;
+
+internal sealed class PrecompiledPackage
+{
+ public int Format { get; set; }
+ public string Version { get; set; } = "";
+ public Dictionary<string, string> Inputs { get; set; } = new();
+ public Dictionary<string, string> Payload { get; set; } = new();
+
+ internal static bool Enabled => Assembly.GetExecutingAssembly().GetManifestResourceInfo("precompiled-mode") != null;
+
+ internal static PrecompiledPackage Validate(string bundleRoot, string gameRoot)
+ {
+ var package = JsonSerializer.Deserialize<PrecompiledPackage>(File.ReadAllText(Path.Combine(bundleRoot, "precompiled.json")))
+ ?? throw new IOException("The precompiled package manifest is missing.");
+ string[] inputs = { "default.xex", "fifadllzf.xex.dll", "dlc/dlc_FootballCompEng/dlc/FootballCompEng/FootballCompEngzf.xex.dll" };
+ string[] required = { "FifaStreetLauncher.exe", "Game/fifastreet.exe", "Game/fifastreet_fifadllzf_xex.dll", "Game/fifastreet_FootballCompEngzf_xex.dll", "Game/fifastreet.toml", "Game/rexruntime.dll", "Game/rexgpu-xenos.dll", "Game/TracyClient.dll", "Game/msvcp140.dll", "Game/msvcp140_atomic_wait.dll", "Game/vcruntime140.dll", "Game/vcruntime140_1.dll" };
+ if (package.Format != 1 || package.Inputs.Count != inputs.Length || inputs.Any(x => !package.Inputs.ContainsKey(x)) || required.Any(x => !package.Payload.ContainsKey(x)))
+ throw new IOException("The precompiled package manifest is incomplete.");
+ foreach (string backend in new[] { "D3D12", "Vulkan" })
+ foreach (string name in new[] { "rexruntime.dll", "rexgpu-xenos.dll", "TracyClient.dll" })
+ if (!package.Payload.ContainsKey($"Game/Backends/{backend}/{name}"))
+ throw new IOException($"The {backend} graphics backend is incomplete.");
+ foreach (var input in package.Inputs)
+ if (!Matches(gameRoot, input.Key, input.Value))
+ throw new IOException($"This ISO version is not supported by this installer ({input.Key} differs). No compilation tools will be installed. Use the source installer for other versions.");
+ string payload = Path.Combine(bundleRoot, "payload");
+ foreach (var file in package.Payload)
+ if (!Matches(payload, file.Key, file.Value))
+ throw new IOException($"The installer package is damaged: {file.Key}. Download a fresh copy.");
+ foreach (string file in Directory.EnumerateFiles(payload, "*", SearchOption.AllDirectories))
+ if (!package.Payload.ContainsKey(Path.GetRelativePath(payload, file).Replace('\\', '/')))
+ throw new IOException("The installer contains an unexpected payload file.");
+ return package;
+ }
+
+ static bool Matches(string root, string relative, string expected)
+ {
+ InstallerEngine.CancellationToken.ThrowIfCancellationRequested();
+ string prefix = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
+ string path = Path.GetFullPath(Path.Combine(prefix, relative));
+ if (Path.IsPathRooted(relative) || !path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) || expected.Length != 64 || !expected.All(Uri.IsHexDigit))
+ throw new IOException("Invalid path or checksum in the installer manifest.");
+ if (!File.Exists(path)) return false;
+ using var stream = File.OpenRead(path);
+ string actual = Convert.ToHexString(SHA256.HashData(stream));
+ InstallerEngine.CancellationToken.ThrowIfCancellationRequested();
+ return actual.Equals(expected, StringComparison.OrdinalIgnoreCase);
+ }
+}
diff --git a/Installer/FifaStreetSetupTool/Program.cs b/Installer/FifaStreetSetupTool/Program.cs
index 254a361..8e5318a 100644
--- a/Installer/FifaStreetSetupTool/Program.cs
+++ b/Installer/FifaStreetSetupTool/Program.cs
@@ -1,332 +1,349 @@
-using System;
-using System.Diagnostics;
-using System.IO;
-
-namespace FifaStreetSetupTool;
-
-internal class InstallerEngine
-{
- internal static string? BundleRoot;
- internal static System.Threading.CancellationToken CancellationToken;
- internal static int Run(string[] args)
- {
- CancellationToken.ThrowIfCancellationRequested();
-
- Console.WriteLine("=======================================");
- Console.WriteLine(" FIFA STREET PC SETUP TOOL");
- Console.WriteLine("=======================================");
- Console.WriteLine();
-
- if (args.Length < 2)
- {
- Console.WriteLine("Usage:");
- Console.WriteLine();
- Console.WriteLine("FifaStreetSetupTool.exe <ISO> <InstallationFolder> [BuildWorkspace]");
- Console.WriteLine();
- Console.WriteLine("Example:");
- Console.WriteLine(@"FifaStreetSetupTool.exe ""D:\FIFASTREET.iso"" ""C:\Games\FIFA Street PC""");
- return 1;
- }
-
- string isoPath = Path.GetFullPath(args[0]);
- string installFolder = Path.GetFullPath(args[1]);
- string? extractorPath = FindExtractor();
-
- if (extractorPath == null)
- {
- Console.WriteLine("ERROR:");
- Console.WriteLine("extract-xiso.exe was not found.");
- Console.WriteLine();
- Console.WriteLine("Expected at:");
- Console.WriteLine(@"Installer\tools\extract-xiso.exe");
- return 2;
- }
-
- if (!File.Exists(isoPath))
- {
- Console.WriteLine("ERROR:");
- Console.WriteLine("The selected ISO does not exist.");
- Console.WriteLine();
- Console.WriteLine(isoPath);
- return 3;
- }
-
- if (!isoPath.EndsWith(".iso", StringComparison.OrdinalIgnoreCase))
- {
- Console.WriteLine("ERROR: The selected file is not an ISO.");
- return 4;
- }
-
- string tempFolder = Path.Combine(Path.GetTempPath(), "FifaStreetSetup_" + Guid.NewGuid().ToString("N"));
-
- try
- {
- Directory.CreateDirectory(tempFolder);
- Console.WriteLine($"ISO:");
- Console.WriteLine(isoPath);
- Console.WriteLine();
- Console.WriteLine($"Destination:");
- Console.WriteLine(installFolder);
- Console.WriteLine();
- Console.WriteLine("Extracting the FIFA Street ISO...");
- Console.WriteLine();
-
- int extractResult = ExtractIso(extractorPath, isoPath, tempFolder);
- if (extractResult != 0)
- {
- Console.WriteLine();
- Console.WriteLine($"ERROR: extract-xiso exited with code {extractResult}.");
- return 5;
- }
-
- Console.WriteLine();
- Console.WriteLine("Extraction complete.");
- Console.WriteLine();
- Console.WriteLine("Locating FIFA Street files...");
-
- string? gameRoot = FindGameRoot(tempFolder);
- if (gameRoot == null)
- {
- Console.WriteLine();
- Console.WriteLine("ERROR: default.xex was not found in the ISO.");
- Console.WriteLine("The selected image may not be a supported version of FIFA Street.");
- return 6;
- }
-
- Console.WriteLine($"Files found at: {gameRoot}");
- Console.WriteLine();
-
- if (!ValidateGame(gameRoot)) return 7;
-
- Console.WriteLine("FIFA Street files validated.");
- Console.WriteLine();
-
- Directory.CreateDirectory(installFolder);
- string gameDataFolder = Path.Combine(installFolder, "GameData");
- string gameFolder = Path.Combine(installFolder, "Game");
-
- Console.WriteLine("Installing game data...");
- Console.WriteLine();
-
- if (Directory.Exists(gameDataFolder))
- {
- Console.WriteLine("An existing GameData installation was found.");
- Console.WriteLine("Existing files will be updated.");
- Console.WriteLine();
- }
-
- CopyDirectory(gameRoot, gameDataFolder);
- Directory.CreateDirectory(gameFolder);
-
- string installerRoot = FindInstallerRoot()
- ?? throw new Exception("The installer folder containing BuildFifaStreet.ps1 was not found.");
- string payload = Path.Combine(installerRoot, "payload");
- if (!Directory.Exists(payload))
- throw new Exception("The payload folder was not found.");
- CopyDirectory(payload, installFolder);
-
- Console.WriteLine("Applying the start screen and main menu credits...");
- CreditPatch.Apply(gameDataFolder);
-
- Console.WriteLine("Recompiling the game on your PC. This may take some time.");
- var buildInfo = new ProcessStartInfo
- {
- FileName = "powershell.exe",
- UseShellExecute = false,
- RedirectStandardOutput = true,
- RedirectStandardError = true,
- CreateNoWindow = true
- };
- foreach (string argument in new[] {
- "-NoProfile", "-ExecutionPolicy", "Bypass", "-File",
- Path.Combine(installerRoot, "BuildFifaStreet.ps1"),
- "-GameData", gameDataFolder, "-Output", gameFolder })
- buildInfo.ArgumentList.Add(argument);
- if (args.Length >= 3)
- {
- buildInfo.ArgumentList.Add("-Workspace");
- buildInfo.ArgumentList.Add(Path.GetFullPath(args[2]));
- }
-
- int buildResult = RunProcess(buildInfo);
- if (buildResult != 0)
- throw new Exception($"Recompilation failed with code {buildResult}. Check the build log for details.");
-
- foreach (string binary in new[] {
- "fifastreet.exe",
- "fifastreet_fifadllzf_xex.dll",
- "fifastreet_FootballCompEngzf_xex.dll"
- })
- if (!File.Exists(Path.Combine(gameFolder, binary)))
- throw new Exception($"The build did not create {binary}.");
-
- Console.WriteLine();
- Console.WriteLine("Game files installed successfully.");
- Console.WriteLine();
- Console.WriteLine("=======================================");
- Console.WriteLine(" INSTALLATION COMPLETE");
- Console.WriteLine("=======================================");
- Console.WriteLine();
- Console.WriteLine("Installation folder:");
- Console.WriteLine();
- Console.WriteLine(installFolder);
- Console.WriteLine();
- return 0;
- }
- catch (OperationCanceledException)
- {
- Console.WriteLine("Installation cancelled.");
- return 1223;
- }
- catch (Exception ex)
- {
- Console.WriteLine();
- Console.WriteLine("UNEXPECTED ERROR:");
- Console.WriteLine(ex.Message);
- return 100;
- }
- finally
- {
- try
- {
- if (Directory.Exists(tempFolder))
- {
- Console.WriteLine();
- Console.WriteLine("Cleaning temporary files...");
- Directory.Delete(tempFolder, true);
- }
- }
- catch
- {
- Console.WriteLine("Warning: Some temporary files could not be removed.");
- }
- }
- }
-
- static string? FindExtractor()
- {
- string? installerRoot = FindInstallerRoot();
- if (installerRoot != null)
- {
- string extractor = Path.Combine(installerRoot, "tools", "extract-xiso.exe");
- if (File.Exists(extractor)) return extractor;
- }
-
- string exeFolder = AppContext.BaseDirectory;
- string[] candidates =
- {
- Path.Combine(exeFolder, "tools", "extract-xiso.exe"),
- Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), "..", "tools", "extract-xiso.exe")),
- Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), "tools", "extract-xiso.exe"))
- };
-
- foreach (string candidate in candidates)
- if (File.Exists(candidate)) return candidate;
- return null;
- }
-
- static string? FindInstallerRoot()
- {
- if (BundleRoot != null) return BundleRoot;
- foreach (string start in new[] { AppContext.BaseDirectory, Directory.GetCurrentDirectory() })
- for (DirectoryInfo? folder = new DirectoryInfo(start); folder != null; folder = folder.Parent)
- if (File.Exists(Path.Combine(folder.FullName, "BuildFifaStreet.ps1")))
- return folder.FullName;
- return null;
- }
-
- static int ExtractIso(string extractor, string iso, string destination)
- {
- var startInfo = new ProcessStartInfo
- {
- FileName = extractor,
- UseShellExecute = false,
- RedirectStandardOutput = true,
- RedirectStandardError = true,
- CreateNoWindow = true
- };
- startInfo.ArgumentList.Add("-x");
- startInfo.ArgumentList.Add("-d");
- startInfo.ArgumentList.Add(destination);
- startInfo.ArgumentList.Add(iso);
- return RunProcess(startInfo);
- }
-
- internal static int RunProcess(ProcessStartInfo startInfo)
- {
- CancellationToken.ThrowIfCancellationRequested();
- using Process? process = Process.Start(startInfo);
- if (process == null) throw new Exception($"Could not start {startInfo.FileName}.");
-
- using var cancellation = CancellationToken.Register(() =>
- {
- try { if (!process.HasExited) process.Kill(entireProcessTree: true); }
- catch (InvalidOperationException) { }
- });
-
- process.OutputDataReceived += (_, e) =>
- {
- if (!string.IsNullOrWhiteSpace(e.Data)) Console.WriteLine(e.Data);
- };
- process.ErrorDataReceived += (_, e) =>
- {
- if (!string.IsNullOrWhiteSpace(e.Data)) Console.WriteLine(e.Data);
- };
-
- process.BeginOutputReadLine();
- process.BeginErrorReadLine();
- process.WaitForExit();
- CancellationToken.ThrowIfCancellationRequested();
- return process.ExitCode;
- }
-
- static string? FindGameRoot(string folder)
- {
- string directXex = Path.Combine(folder, "default.xex");
- if (File.Exists(directXex)) return folder;
-
- foreach (string file in Directory.EnumerateFiles(folder, "default.xex", SearchOption.AllDirectories))
- return Path.GetDirectoryName(file);
- return null;
- }
-
- static bool ValidateGame(string folder)
- {
- string[] requiredFiles = { "default.xex", "fifadllzf.xex.dll", "data0.big", "data1.big" };
- foreach (string required in requiredFiles)
- {
- string path = Path.Combine(folder, required);
- if (!File.Exists(path))
- {
- Console.WriteLine($"ERROR: Required file missing: {required}");
- return false;
- }
- }
-
- string worldTourModule = Path.Combine(folder, "dlc", "dlc_FootballCompEng", "dlc", "FootballCompEng", "FootballCompEngzf.xex.dll");
- if (!File.Exists(worldTourModule))
- {
- Console.WriteLine("ERROR: Required World Tour module missing: FootballCompEngzf.xex.dll");
- return false;
- }
-
- return true;
- }
-
- static void CopyDirectory(string sourceDir, string destinationDir)
- {
- CancellationToken.ThrowIfCancellationRequested();
- Directory.CreateDirectory(destinationDir);
-
- foreach (string file in Directory.GetFiles(sourceDir))
- {
- CancellationToken.ThrowIfCancellationRequested();
- File.Copy(file, Path.Combine(destinationDir, Path.GetFileName(file)), overwrite: true);
- }
-
- foreach (string directory in Directory.GetDirectories(sourceDir))
- {
- CopyDirectory(directory, Path.Combine(destinationDir, Path.GetFileName(directory)));
- }
- }
-}
+using System;
+using System.Diagnostics;
+using System.IO;
+
+namespace FifaStreetSetupTool;
+
+internal class InstallerEngine
+{
+ internal static string? BundleRoot;
+ internal static System.Threading.CancellationToken CancellationToken;
+ internal static int Run(string[] args)
+ {
+ CancellationToken.ThrowIfCancellationRequested();
+
+ Console.WriteLine("=======================================");
+ Console.WriteLine(" FIFA STREET PC SETUP TOOL");
+ Console.WriteLine("=======================================");
+ Console.WriteLine();
+
+ if (args.Length < 2)
+ {
+ Console.WriteLine("Usage:");
+ Console.WriteLine();
+ Console.WriteLine("FifaStreetSetupTool.exe <ISO> <InstallationFolder> [BuildWorkspace]");
+ Console.WriteLine();
+ Console.WriteLine("Example:");
+ Console.WriteLine(@"FifaStreetSetupTool.exe ""D:\FIFASTREET.iso"" ""C:\Games\FIFA Street PC""");
+ return 1;
+ }
+
+ string isoPath = Path.GetFullPath(args[0]);
+ string installFolder = Path.GetFullPath(args[1]);
+ string? extractorPath = FindExtractor();
+
+ if (extractorPath == null)
+ {
+ Console.WriteLine("ERROR:");
+ Console.WriteLine("extract-xiso.exe was not found.");
+ Console.WriteLine();
+ Console.WriteLine("Expected at:");
+ Console.WriteLine(@"Installer\tools\extract-xiso.exe");
+ return 2;
+ }
+
+ if (!File.Exists(isoPath))
+ {
+ Console.WriteLine("ERROR:");
+ Console.WriteLine("The selected ISO does not exist.");
+ Console.WriteLine();
+ Console.WriteLine(isoPath);
+ return 3;
+ }
+
+ if (!isoPath.EndsWith(".iso", StringComparison.OrdinalIgnoreCase))
+ {
+ Console.WriteLine("ERROR: The selected file is not an ISO.");
+ return 4;
+ }
+
+ string tempFolder = Path.Combine(installFolder, ".extract-" + Guid.NewGuid().ToString("N"));
+
+ try
+ {
+ Directory.CreateDirectory(tempFolder);
+ Console.WriteLine($"ISO:");
+ Console.WriteLine(isoPath);
+ Console.WriteLine();
+ Console.WriteLine($"Destination:");
+ Console.WriteLine(installFolder);
+ Console.WriteLine();
+ Console.WriteLine("Extracting the FIFA Street ISO...");
+ Console.WriteLine();
+
+ int extractResult = ExtractIso(extractorPath, isoPath, tempFolder);
+ if (extractResult != 0)
+ {
+ Console.WriteLine();
+ Console.WriteLine($"ERROR: extract-xiso exited with code {extractResult}.");
+ return 5;
+ }
+
+ Console.WriteLine();
+ Console.WriteLine("Extraction complete.");
+ Console.WriteLine();
+ Console.WriteLine("Locating FIFA Street files...");
+
+ string? gameRoot = FindGameRoot(tempFolder);
+ if (gameRoot == null)
+ {
+ Console.WriteLine();
+ Console.WriteLine("ERROR: default.xex was not found in the ISO.");
+ Console.WriteLine("The selected image may not be a supported version of FIFA Street.");
+ return 6;
+ }
+
+ Console.WriteLine($"Files found at: {gameRoot}");
+ Console.WriteLine();
+
+ if (!ValidateGame(gameRoot)) return 7;
+
+ string installerRoot = FindInstallerRoot()
+ ?? throw new Exception("The installer package was not found.");
+ if (PrecompiledPackage.Enabled)
+ {
+ Console.WriteLine("Checking ISO version and installation files...");
+ var package = PrecompiledPackage.Validate(installerRoot, gameRoot);
+ Console.WriteLine($"Supported game version: {package.Version}");
+ }
+
+ Console.WriteLine("FIFA Street files validated.");
+ Console.WriteLine();
+
+ Directory.CreateDirectory(installFolder);
+ string gameDataFolder = Path.Combine(installFolder, "GameData");
+ string gameFolder = Path.Combine(installFolder, "Game");
+
+ Console.WriteLine("Installing game data...");
+ Console.WriteLine();
+
+ if (Directory.Exists(gameDataFolder))
+ {
+ Console.WriteLine("An existing GameData installation was found.");
+ Console.WriteLine("Existing files will be updated.");
+ Console.WriteLine();
+ }
+
+ CancellationToken.ThrowIfCancellationRequested();
+ if (!Directory.Exists(gameDataFolder))
+ Directory.Move(gameRoot, gameDataFolder);
+ else
+ CopyDirectory(gameRoot, gameDataFolder);
+ Directory.CreateDirectory(gameFolder);
+
+ string payload = Path.Combine(installerRoot, "payload");
+ if (!Directory.Exists(payload))
+ throw new Exception("The payload folder was not found.");
+ CopyDirectory(payload, installFolder);
+
+ Console.WriteLine("Applying the start screen and main menu credits...");
+ CreditPatch.Apply(gameDataFolder);
+
+ if (!PrecompiledPackage.Enabled)
+ {
+ Console.WriteLine("Recompiling the game on your PC. This may take some time.");
+ var buildInfo = new ProcessStartInfo
+ {
+ FileName = "powershell.exe",
+ UseShellExecute = false,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ CreateNoWindow = true
+ };
+ foreach (string argument in new[] {
+ "-NoProfile", "-ExecutionPolicy", "Bypass", "-File",
+ Path.Combine(installerRoot, "BuildFifaStreet.ps1"),
+ "-GameData", gameDataFolder, "-Output", gameFolder })
+ buildInfo.ArgumentList.Add(argument);
+ if (args.Length >= 3)
+ {
+ buildInfo.ArgumentList.Add("-Workspace");
+ buildInfo.ArgumentList.Add(Path.GetFullPath(args[2]));
+ }
+
+ int buildResult = RunProcess(buildInfo);
+ if (buildResult != 0)
+ throw new Exception($"Recompilation failed with code {buildResult}. Check the build log for details.");
+ }
+ else
+ Console.WriteLine("Installing precompiled game files. No compiler is required.");
+
+ foreach (string binary in new[] {
+ "fifastreet.exe",
+ "fifastreet_fifadllzf_xex.dll",
+ "fifastreet_FootballCompEngzf_xex.dll"
+ })
+ if (!File.Exists(Path.Combine(gameFolder, binary)))
+ throw new Exception($"The build did not create {binary}.");
+
+ Console.WriteLine();
+ Console.WriteLine("Game files installed successfully.");
+ Console.WriteLine();
+ Console.WriteLine("=======================================");
+ Console.WriteLine(" INSTALLATION COMPLETE");
+ Console.WriteLine("=======================================");
+ Console.WriteLine();
+ Console.WriteLine("Installation folder:");
+ Console.WriteLine();
+ Console.WriteLine(installFolder);
+ Console.WriteLine();
+ return 0;
+ }
+ catch (OperationCanceledException)
+ {
+ Console.WriteLine("Installation cancelled.");
+ return 1223;
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine();
+ Console.WriteLine("UNEXPECTED ERROR:");
+ Console.WriteLine(ex.Message);
+ return 100;
+ }
+ finally
+ {
+ try
+ {
+ if (Directory.Exists(tempFolder))
+ {
+ Console.WriteLine();
+ Console.WriteLine("Cleaning temporary files...");
+ Directory.Delete(tempFolder, true);
+ }
+ }
+ catch
+ {
+ Console.WriteLine("Warning: Some temporary files could not be removed.");
+ }
+ }
+ }
+
+ static string? FindExtractor()
+ {
+ string? installerRoot = FindInstallerRoot();
+ if (installerRoot != null)
+ {
+ string extractor = Path.Combine(installerRoot, "tools", "extract-xiso.exe");
+ if (File.Exists(extractor)) return extractor;
+ }
+
+ string exeFolder = AppContext.BaseDirectory;
+ string[] candidates =
+ {
+ Path.Combine(exeFolder, "tools", "extract-xiso.exe"),
+ Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), "..", "tools", "extract-xiso.exe")),
+ Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), "tools", "extract-xiso.exe"))
+ };
+
+ foreach (string candidate in candidates)
+ if (File.Exists(candidate)) return candidate;
+ return null;
+ }
+
+ static string? FindInstallerRoot()
+ {
+ if (BundleRoot != null) return BundleRoot;
+ foreach (string start in new[] { AppContext.BaseDirectory, Directory.GetCurrentDirectory() })
+ for (DirectoryInfo? folder = new DirectoryInfo(start); folder != null; folder = folder.Parent)
+ if (File.Exists(Path.Combine(folder.FullName, "BuildFifaStreet.ps1")) ||
+ (PrecompiledPackage.Enabled && File.Exists(Path.Combine(folder.FullName, "precompiled.json"))))
+ return folder.FullName;
+ return null;
+ }
+
+ static int ExtractIso(string extractor, string iso, string destination)
+ {
+ var startInfo = new ProcessStartInfo
+ {
+ FileName = extractor,
+ UseShellExecute = false,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ CreateNoWindow = true
+ };
+ startInfo.ArgumentList.Add("-x");
+ startInfo.ArgumentList.Add("-d");
+ startInfo.ArgumentList.Add(destination);
+ startInfo.ArgumentList.Add(iso);
+ return RunProcess(startInfo);
+ }
+
+ internal static int RunProcess(ProcessStartInfo startInfo)
+ {
+ CancellationToken.ThrowIfCancellationRequested();
+ using Process? process = Process.Start(startInfo);
+ if (process == null) throw new Exception($"Could not start {startInfo.FileName}.");
+
+ using var cancellation = CancellationToken.Register(() =>
+ {
+ try { if (!process.HasExited) process.Kill(entireProcessTree: true); }
+ catch (InvalidOperationException) { }
+ });
+
+ process.OutputDataReceived += (_, e) =>
+ {
+ if (!string.IsNullOrWhiteSpace(e.Data)) Console.WriteLine(e.Data);
+ };
+ process.ErrorDataReceived += (_, e) =>
+ {
+ if (!string.IsNullOrWhiteSpace(e.Data)) Console.WriteLine(e.Data);
+ };
+
+ process.BeginOutputReadLine();
+ process.BeginErrorReadLine();
+ process.WaitForExit();
+ CancellationToken.ThrowIfCancellationRequested();
+ return process.ExitCode;
+ }
+
+ static string? FindGameRoot(string folder)
+ {
+ string directXex = Path.Combine(folder, "default.xex");
+ if (File.Exists(directXex)) return folder;
+
+ foreach (string file in Directory.EnumerateFiles(folder, "default.xex", SearchOption.AllDirectories))
+ return Path.GetDirectoryName(file);
+ return null;
+ }
+
+ static bool ValidateGame(string folder)
+ {
+ string[] requiredFiles = { "default.xex", "fifadllzf.xex.dll", "data0.big", "data1.big", "data1.bh" };
+ foreach (string required in requiredFiles)
+ {
+ string path = Path.Combine(folder, required);
+ if (!File.Exists(path))
+ {
+ Console.WriteLine($"ERROR: Required file missing: {required}");
+ return false;
+ }
+ }
+
+ string worldTourModule = Path.Combine(folder, "dlc", "dlc_FootballCompEng", "dlc", "FootballCompEng", "FootballCompEngzf.xex.dll");
+ if (!File.Exists(worldTourModule))
+ {
+ Console.WriteLine("ERROR: Required World Tour module missing: FootballCompEngzf.xex.dll");
+ return false;
+ }
+
+ return true;
+ }
+
+ static void CopyDirectory(string sourceDir, string destinationDir)
+ {
+ CancellationToken.ThrowIfCancellationRequested();
+ Directory.CreateDirectory(destinationDir);
+
+ foreach (string file in Directory.GetFiles(sourceDir))
+ {
+ CancellationToken.ThrowIfCancellationRequested();
+ File.Copy(file, Path.Combine(destinationDir, Path.GetFileName(file)), overwrite: true);
+ }
+
+ foreach (string directory in Directory.GetDirectories(sourceDir))
+ {
+ CopyDirectory(directory, Path.Combine(destinationDir, Path.GetFileName(directory)));
+ }
+ }
+}
diff --git a/Installer/FifaStreetSetupTool/SetupForm.cs b/Installer/FifaStreetSetupTool/SetupForm.cs
index f6c9a85..d9fae80 100644
--- a/Installer/FifaStreetSetupTool/SetupForm.cs
+++ b/Installer/FifaStreetSetupTool/SetupForm.cs
@@ -1,405 +1,473 @@
-using System.Diagnostics;
-using System.Drawing;
-using System.IO.Compression;
-using System.Reflection;
-using System.Text;
-using System.Windows.Forms;
-
-namespace FifaStreetSetupTool;
-
-internal static class Program
-{
- [STAThread]
- static int Main(string[] args)
- {
+using System.Diagnostics;
+using System.Drawing;
+using System.IO.Compression;
+using System.Reflection;
+using System.Text;
+using System.Windows.Forms;
+
+namespace FifaStreetSetupTool;
+
+internal static class Program
+{
+ [STAThread]
+ static int Main(string[] args)
+ {
ApplicationConfiguration.Initialize();
- if (args.Length == 2 && args[0] == "--cancel-self-test")
+ if (args.Length == 2 && args[0] == "--update-test")
{
- using var cancellation = new System.Threading.CancellationTokenSource();
- InstallerEngine.CancellationToken = cancellation.Token;
- cancellation.CancelAfter(750);
- var clock = Stopwatch.StartNew();
- var child = new ProcessStartInfo("cmd.exe") { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true };
- child.ArgumentList.Add("/c");
- child.ArgumentList.Add("ping -n 30 127.0.0.1 >nul");
- try { InstallerEngine.RunProcess(child); return 1; }
- catch (OperationCanceledException)
- {
- File.WriteAllText(args[1], $"Cancellation passed in {clock.Elapsed.TotalSeconds:F2} seconds.");
- return clock.Elapsed < TimeSpan.FromSeconds(10) ? 0 : 2;
- }
- }
- if (args.Length == 3 && args[0] == "--credit-test")
- {
- using var log = new StreamWriter(args[2]);
+ using var log = new StreamWriter(args[1] + ".update-test.log") { AutoFlush = true };
Console.SetOut(log);
- try { CreditPatch.Apply(args[1]); return 0; }
+ try { SetupForm.PrepareBundle(); InstallationUpdate.Apply(InstallerEngine.BundleRoot!, Path.GetFullPath(args[1])); return 0; }
catch (Exception error) { Console.WriteLine(error); return 100; }
}
- if (args.Length == 2 && args[0] == "--preview")
- {
- using var form = new SetupForm();
- form.Show();
- Application.DoEvents();
- using var bitmap = new Bitmap(form.Width, form.Height);
- form.DrawToBitmap(bitmap, new Rectangle(Point.Empty, form.Size));
- bitmap.Save(args[1]);
- return 0;
- }
- if (args.Length >= 3 && args[0] == "--install-test")
- {
- using var log = new StreamWriter(args[2] + ".setup.log", false, new UTF8Encoding(false)) { AutoFlush = true };
- Console.SetOut(TextWriter.Synchronized(log));
- try
- {
- SetupForm.PrepareBundle();
- return InstallerEngine.Run(args.Skip(1).ToArray());
- }
- catch (Exception error) { Console.WriteLine(error); return 100; }
- }
- Application.Run(new SetupForm());
- return 0;
- }
-}
-
-internal sealed class SetupForm : Form
-{
- readonly TextBox iso = new();
- readonly TextBox destination = new();
- readonly TextBox details = new();
- readonly Button install = new();
- readonly Button cancel = new();
- System.Threading.CancellationTokenSource? cancellation;
- readonly ProgressBar progress = new();
- readonly Label status = new();
- readonly List<Control> inputs = new();
- readonly System.Windows.Forms.Timer timer = new() { Interval = 200 };
- readonly System.Collections.Concurrent.ConcurrentQueue<string> messages = new();
- bool busy;
- bool completed;
- string installedPath = "";
- static readonly Color Accent = Color.FromArgb(133, 255, 72);
- internal const string Credit = "PORTED BY: SAMUELITODAVILA";
-
- internal SetupForm()
- {
- Text = "FIFA Street PC — Setup";
- using (var icon = Assembly.GetExecutingAssembly().GetManifestResourceStream("fifastreet.ico")!)
- Icon = new Icon(icon);
- ClientSize = new Size(930, 610);
- MinimumSize = MaximumSize = Size;
- StartPosition = FormStartPosition.CenterScreen;
- FormBorderStyle = FormBorderStyle.FixedSingle;
- MaximizeBox = false;
- BackColor = Color.FromArgb(10, 12, 16);
- ForeColor = Color.White;
- Font = new Font("Segoe UI", 10);
- AutoScaleMode = AutoScaleMode.Dpi;
-
- using var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream("cover.jpg")
- ?? throw new InvalidOperationException("The installer artwork is missing.");
- using var source = Image.FromStream(resource);
- var artwork = new MessiPicture { Bounds = new Rectangle(0, 0, 310, 610), Image = new Bitmap(source), BackColor = Color.Black };
- Controls.Add(artwork);
- Controls.Add(Label("FIFA STREET", 340, 27, 550, 50, 30, Accent));
- Controls.Add(Label("PC INSTALLER", 343, 80, 540, 30, 12, Color.LightGray));
- Controls.Add(Label(Credit, 343, 118, 545, 30, 11, Accent));
- Controls.Add(Label("Select your FIFA Street ISO and choose where to install the game.", 343, 169, 548, 28));
- AddPath("FIFA Street ISO", iso, 209, () =>
- {
- using var dialog = new OpenFileDialog { Title = "Select FIFA Street ISO", Filter = "ISO image (*.iso)|*.iso", CheckFileExists = true };
- if (dialog.ShowDialog(this) == DialogResult.OK) iso.Text = dialog.FileName;
- });
- destination.Text = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Games", "FIFA Street PC");
- AddPath("Installation folder", destination, 288, () =>
- {
- using var dialog = new FolderBrowserDialog { Description = "Choose installation folder", UseDescriptionForTitle = true, SelectedPath = destination.Text };
- if (dialog.ShowDialog(this) == DialogResult.OK) destination.Text = dialog.SelectedPath;
- });
- status.SetBounds(343, 373, 550, 43);
- status.Text = "Game files will be created on your PC from your ISO.";
- Controls.Add(status);
- progress.SetBounds(343, 423, 548, 10);
- Controls.Add(progress);
- var note = Label("An Internet connection may be needed to set up Windows components.", 343, 448, 548, 35, 9, Color.Silver);
- Controls.Add(note);
- install.SetBounds(343, 500, 548, 46);
- install.Text = "INSTALL FIFA STREET";
- install.BackColor = Accent;
- install.ForeColor = Color.Black;
- install.FlatStyle = FlatStyle.Flat;
- install.Font = new Font("Segoe UI", 11, FontStyle.Bold);
- install.Click += async (_, _) => await Install();
- AcceptButton = install;
- Controls.Add(install);
- var showDetails = new Button { Text = "Show details", Bounds = new Rectangle(343, 559, 130, 30), FlatStyle = FlatStyle.Flat, ForeColor = Color.LightGray };
- showDetails.Click += (_, _) =>
- {
- details.Visible = !details.Visible;
- showDetails.Text = details.Visible ? "Hide details" : "Show details";
- MaximumSize = Size.Empty;
- Height += details.Visible ? 180 : -180;
- MaximumSize = Size;
- };
- Controls.Add(showDetails);
- cancel.Text = "Cancel";
- cancel.SetBounds(761, 559, 130, 30);
- cancel.FlatStyle = FlatStyle.Flat;
- cancel.Enabled = false;
- cancel.Click += (_, _) =>
- {
- if (!completed) { CancelInstallation(); return; }
+ if (args.Length == 2 && args[0] == "--cancel-self-test")
+ {
+ using var cancellation = new System.Threading.CancellationTokenSource();
+ InstallerEngine.CancellationToken = cancellation.Token;
+ cancellation.CancelAfter(750);
+ var clock = Stopwatch.StartNew();
+ var child = new ProcessStartInfo("cmd.exe") { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true };
+ child.ArgumentList.Add("/c");
+ child.ArgumentList.Add("ping -n 30 127.0.0.1 >nul");
+ try { InstallerEngine.RunProcess(child); return 1; }
+ catch (OperationCanceledException)
+ {
+ File.WriteAllText(args[1], $"Cancellation passed in {clock.Elapsed.TotalSeconds:F2} seconds.");
+ return clock.Elapsed < TimeSpan.FromSeconds(10) ? 0 : 2;
+ }
+ }
+ if (args.Length == 3 && args[0] == "--credit-test")
+ {
+ using var log = new StreamWriter(args[2]);
+ Console.SetOut(log);
+ try { CreditPatch.Apply(args[1]); return 0; }
+ catch (Exception error) { Console.WriteLine(error); return 100; }
+ }
+ if (args.Length == 2 && args[0] == "--preview")
+ {
+ using var form = new SetupForm();
+ form.Show();
+ Application.DoEvents();
+ using var bitmap = new Bitmap(form.Width, form.Height);
+ form.DrawToBitmap(bitmap, new Rectangle(Point.Empty, form.Size));
+ bitmap.Save(args[1]);
+ return 0;
+ }
+ if (args.Length >= 3 && args[0] == "--install-test")
+ {
+ using var log = new StreamWriter(args[2] + ".setup.log", false, new UTF8Encoding(false)) { AutoFlush = true };
+ Console.SetOut(TextWriter.Synchronized(log));
+ try
+ {
+ SetupForm.PrepareBundle();
+ return InstallerEngine.Run(args.Skip(1).ToArray());
+ }
+ catch (Exception error) { Console.WriteLine(error); return 100; }
+ }
+ Application.Run(new SetupForm());
+ return 0;
+ }
+}
+
+internal sealed class SetupForm : Form
+{
+ readonly TextBox iso = new();
+ readonly TextBox destination = new();
+ readonly TextBox details = new();
+ readonly Button install = new();
+ readonly Button cancel = new();
+ System.Threading.CancellationTokenSource? cancellation;
+ readonly ProgressBar progress = new();
+ readonly Label status = new();
+ readonly List<Control> inputs = new();
+ readonly System.Windows.Forms.Timer timer = new() { Interval = 200 };
+ readonly System.Collections.Concurrent.ConcurrentQueue<string> messages = new();
+ bool busy;
+ bool completed;
+ string installedPath = "";
+ static readonly Color Accent = Color.FromArgb(133, 255, 72);
+ internal const string Credit = "PORTED BY: SAMUELITODAVILA";
+
+ internal SetupForm()
+ {
+ Text = "FIFA Street PC — Setup";
+ using (var icon = Assembly.GetExecutingAssembly().GetManifestResourceStream("fifastreet.ico")!)
+ Icon = new Icon(icon);
+ ClientSize = new Size(930, 610);
+ MinimumSize = MaximumSize = Size;
+ StartPosition = FormStartPosition.CenterScreen;
+ FormBorderStyle = FormBorderStyle.FixedSingle;
+ MaximizeBox = false;
+ BackColor = Color.FromArgb(10, 12, 16);
+ ForeColor = Color.White;
+ Font = new Font("Segoe UI", 10);
+ AutoScaleMode = AutoScaleMode.Dpi;
+
+ using var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream("cover.jpg")
+ ?? throw new InvalidOperationException("The installer artwork is missing.");
+ using var source = Image.FromStream(resource);
+ var artwork = new MessiPicture { Bounds = new Rectangle(0, 0, 310, 610), Image = new Bitmap(source), BackColor = Color.Black };
+ Controls.Add(artwork);
+ Controls.Add(Label("FIFA STREET", 340, 27, 550, 50, 30, Accent));
+ Controls.Add(Label("PC INSTALLER", 343, 80, 540, 30, 12, Color.LightGray));
+ Controls.Add(Label(Credit + "\nContributions: Emran_Ahm3d", 343, 113, 545, 40, 10, Accent));
+ Controls.Add(Label(PrecompiledPackage.Enabled
+ ? "New installation: select your ISO. To update, choose your existing game folder below (the folder containing Game and GameData)."
+ : "Select your FIFA Street ISO and choose where to install the game.", 343, 158, 548, 48, 9));
+ AddPath("FIFA Street ISO", iso, 209, () =>
+ {
+ using var dialog = new OpenFileDialog { Title = "Select FIFA Street ISO", Filter = "ISO image (*.iso)|*.iso", CheckFileExists = true };
+ if (dialog.ShowDialog(this) == DialogResult.OK) iso.Text = dialog.FileName;
+ });
+ destination.Text = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Games", "FIFA Street PC");
+ AddPath(PrecompiledPackage.Enabled ? "Installation folder / existing game folder to update" : "Installation folder", destination, 288, () =>
+ {
+ string initialFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
try
{
- CreateDesktopShortcut(installedPath);
- cancel.Text = "Desktop shortcut created";
- cancel.Enabled = false;
+ var folder = new DirectoryInfo(Path.GetFullPath(destination.Text));
+ while (folder != null && !folder.Exists) folder = folder.Parent;
+ if (folder != null) initialFolder = folder.FullName;
}
- catch (Exception error)
+ catch (Exception error) when (error is ArgumentException or IOException or NotSupportedException)
{
- MessageBox.Show(this, "The desktop shortcut could not be created.\n\n" + error.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
+ // A manually entered invalid path must not prevent browsing.
}
- };
- Controls.Add(cancel);
- details.SetBounds(20, 620, 885, 155);
- details.Multiline = true;
- details.ReadOnly = true;
- details.ScrollBars = ScrollBars.Vertical;
- details.BackColor = Color.FromArgb(18, 22, 28);
- details.ForeColor = Color.Gainsboro;
- details.Visible = false;
- Controls.Add(details);
- timer.Tick += (_, _) => DrainMessages();
- timer.Start();
- FormClosing += (_, e) =>
- {
- if (!busy) return;
- e.Cancel = true;
- CancelInstallation();
- };
+ using var dialog = new FolderBrowserDialog { Description = PrecompiledPackage.Enabled ? "Choose a new installation folder, or your existing game folder to update (containing Game and GameData)." : "Choose installation folder", UseDescriptionForTitle = true, InitialDirectory = initialFolder };
+ if (dialog.ShowDialog(this) == DialogResult.OK) destination.Text = dialog.SelectedPath;
+ });
+ destination.TextChanged += (_, _) => RefreshInstallMode();
+ status.SetBounds(343, 373, 550, 43);
+ status.Text = PrecompiledPackage.Enabled ? "Your ISO supplies the game data. Ready-to-play binaries are included." : "Game files will be created on your PC from your ISO.";
+ Controls.Add(status);
+ progress.SetBounds(343, 423, 548, 10);
+ Controls.Add(progress);
+ var note = Label(PrecompiledPackage.Enabled ? "No compiler, Visual Studio or Internet connection required." : "An Internet connection may be needed to set up Windows components.", 343, 448, 548, 35, 9, Color.Silver);
+ Controls.Add(note);
+ install.SetBounds(343, 500, 548, 46);
+ install.Text = "INSTALL FIFA STREET";
+ install.BackColor = Accent;
+ install.ForeColor = Color.Black;
+ install.FlatStyle = FlatStyle.Flat;
+ install.Font = new Font("Segoe UI", 11, FontStyle.Bold);
+ install.Click += async (_, _) => await Install();
+ AcceptButton = install;
+ Controls.Add(install);
+ var showDetails = new Button { Text = "Show details", Bounds = new Rectangle(343, 559, 130, 30), FlatStyle = FlatStyle.Flat, ForeColor = Color.LightGray };
+ showDetails.Click += (_, _) =>
+ {
+ details.Visible = !details.Visible;
+ showDetails.Text = details.Visible ? "Hide details" : "Show details";
+ MaximumSize = Size.Empty;
+ Height += details.Visible ? 180 : -180;
+ MaximumSize = Size;
+ };
+ Controls.Add(showDetails);
+ cancel.Text = "Cancel";
+ cancel.SetBounds(761, 559, 130, 30);
+ cancel.FlatStyle = FlatStyle.Flat;
+ cancel.Enabled = false;
+ cancel.Click += (_, _) =>
+ {
+ if (!completed) { CancelInstallation(); return; }
+ try
+ {
+ CreateDesktopShortcut(installedPath);
+ cancel.Text = "Desktop shortcut created";
+ cancel.Enabled = false;
+ }
+ catch (Exception error)
+ {
+ MessageBox.Show(this, "The desktop shortcut could not be created.\n\n" + error.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
+ };
+ Controls.Add(cancel);
+ details.SetBounds(20, 620, 885, 155);
+ details.Multiline = true;
+ details.ReadOnly = true;
+ details.ScrollBars = ScrollBars.Vertical;
+ details.BackColor = Color.FromArgb(18, 22, 28);
+ details.ForeColor = Color.Gainsboro;
+ details.Visible = false;
+ Controls.Add(details);
+ timer.Tick += (_, _) => DrainMessages();
+ timer.Start();
+ FormClosing += (_, e) =>
+ {
+ if (!busy) return;
+ e.Cancel = true;
+ CancelInstallation();
+ };
FormClosed += (_, _) => { timer.Dispose(); artwork.Image?.Dispose(); };
+ RefreshInstallMode();
}
- static Label Label(string text, int x, int y, int width, int height, float size = 10, Color? color = null) =>
- new() { Text = text, Bounds = new Rectangle(x, y, width, height), Font = new Font("Segoe UI", size, size >= 20 ? FontStyle.Bold : FontStyle.Regular), ForeColor = color ?? Color.White };
-
- void AddPath(string label, TextBox box, int y, Action browse)
+ void RefreshInstallMode()
{
- Controls.Add(Label(label, 343, y, 548, 25));
- box.SetBounds(343, y + 28, 432, 30);
- box.BackColor = Color.FromArgb(25, 29, 36);
- box.ForeColor = Color.White;
- box.AccessibleName = label;
- Controls.Add(box);
- var button = new Button { Text = "Browse…", Bounds = new Rectangle(785, y + 25, 106, 33), FlatStyle = FlatStyle.Flat };
- button.AccessibleName = "Browse " + label;
- button.Click += (_, _) => browse();
- Controls.Add(button);
- inputs.Add(box);
- inputs.Add(button);
+ if (busy || completed || !PrecompiledPackage.Enabled) return;
+ bool updating = InstallationUpdate.IsInstallation(destination.Text);
+ install.Text = updating ? "UPDATE FIFA STREET" : "INSTALL FIFA STREET";
+ iso.Enabled = !updating;
+ inputs[1].Enabled = !updating;
+ status.Text = updating ? "Existing installation found. Click UPDATE FIFA STREET. No ISO required; saves and preferences are preserved." : "Select your ISO for a new installation, or choose your existing game folder to update.";
}
-
- async Task Install()
- {
- if (completed)
- {
- Process.Start(new ProcessStartInfo(Path.Combine(installedPath, "FifaStreetLauncher.exe")) { UseShellExecute = true, WorkingDirectory = installedPath });
- Close();
- return;
- }
- if (!File.Exists(iso.Text) || !iso.Text.EndsWith(".iso", StringComparison.OrdinalIgnoreCase))
- {
- MessageBox.Show(this, "Select a valid FIFA Street ISO image.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
- return;
- }
- string target;
- try
- {
- target = Path.GetFullPath(destination.Text);
- if (target == Path.GetPathRoot(target)) throw new IOException("Choose a game folder instead of the root of a drive.");
- if (Directory.Exists(target) && Directory.EnumerateFileSystemEntries(target).Any())
- throw new IOException("The selected folder contains files. Choose a new or empty folder to install the game.");
- Directory.CreateDirectory(target);
- if (new DriveInfo(Path.GetPathRoot(target)!).AvailableFreeSpace < 12L * 1024 * 1024 * 1024)
- throw new IOException("At least 12 GB of free space is required on the destination drive.");
- }
- catch (Exception error) { MessageBox.Show(this, error.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; }
- busy = true;
- cancellation = new System.Threading.CancellationTokenSource();
- InstallerEngine.CancellationToken = cancellation.Token;
- cancel.Enabled = true;
- foreach (var input in inputs) input.Enabled = false;
- install.Enabled = false;
- install.Text = "INSTALLING…";
- progress.Style = ProgressBarStyle.Marquee;
- status.Text = "Preparing installation…";
- string selectedIso = iso.Text;
- string logPath = Path.Combine(target, "installation.log");
- using var log = new StreamWriter(logPath, false, new UTF8Encoding(false)) { AutoFlush = true };
- var previousWriter = Console.Out;
- Console.SetOut(new ProgressWriter(log, messages));
- int result;
- try
- {
- result = await Task.Run(async () =>
+
+ static Label Label(string text, int x, int y, int width, int height, float size = 10, Color? color = null) =>
+ new() { Text = text, Bounds = new Rectangle(x, y, width, height), Font = new Font("Segoe UI", size, size >= 20 ? FontStyle.Bold : FontStyle.Regular), ForeColor = color ?? Color.White };
+
+ void AddPath(string label, TextBox box, int y, Action browse)
+ {
+ Controls.Add(Label(label, 343, y, 548, 25));
+ box.SetBounds(343, y + 28, 432, 30);
+ box.BackColor = Color.FromArgb(25, 29, 36);
+ box.ForeColor = Color.White;
+ box.AccessibleName = label;
+ Controls.Add(box);
+ var button = new Button { Text = "Browse…", Bounds = new Rectangle(785, y + 25, 106, 33), FlatStyle = FlatStyle.Flat };
+ button.AccessibleName = "Browse " + label;
+ button.Click += (_, _) => browse();
+ Controls.Add(button);
+ inputs.Add(box);
+ inputs.Add(button);
+ }
+
+ async Task Install()
+ {
+ if (completed)
+ {
+ try
{
- Console.WriteLine("Preparing installation tools…");
- PrepareBundle();
- cancellation.Token.ThrowIfCancellationRequested();
- await EnsureWindowsTools();
+ Process.Start(new ProcessStartInfo(Path.Combine(installedPath, "FifaStreetLauncher.exe")) { UseShellExecute = true, WorkingDirectory = installedPath });
+ Close();
+ }
+ catch (Exception error) { MessageBox.Show(this, "The launcher could not be opened.\n\n" + error.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error); }
+ return;
+ }
+ bool updating = PrecompiledPackage.Enabled && InstallationUpdate.IsInstallation(destination.Text);
+ if (!updating && (!File.Exists(iso.Text) || !iso.Text.EndsWith(".iso", StringComparison.OrdinalIgnoreCase)))
+ {
+ MessageBox.Show(this, "Select a valid FIFA Street ISO image.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
+ return;
+ }
+ string target;
+ try
+ {
+ target = Path.GetFullPath(destination.Text);
+ if (target == Path.GetPathRoot(target)) throw new IOException("Choose a game folder instead of the root of a drive.");
+ if (!updating && Directory.Exists(target) && Directory.EnumerateFileSystemEntries(target).Any())
+ throw new IOException("The selected folder contains files. Choose a new or empty folder to install the game.");
+ Directory.CreateDirectory(target);
+ long requiredSpace = (updating ? 2L : 12L) * 1024 * 1024 * 1024;
+ if (new DriveInfo(Path.GetPathRoot(target)!).AvailableFreeSpace < requiredSpace)
+ throw new IOException(updating ? "At least 2 GB of free space is required for the update and backup." : "At least 12 GB of free space is required on the destination drive.");
+ }
+ catch (Exception error) { MessageBox.Show(this, error.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; }
+ busy = true;
+ cancellation = new System.Threading.CancellationTokenSource();
+ InstallerEngine.CancellationToken = cancellation.Token;
+ cancel.Enabled = true;
+ foreach (var input in inputs) input.Enabled = false;
+ install.Enabled = false;
+ install.Text = "INSTALLING…";
+ progress.Style = ProgressBarStyle.Marquee;
+ status.Text = "Preparing installation…";
+ string selectedIso = iso.Text;
+ string logPath = Path.Combine(target, updating ? "update.log" : "installation.log");
+ StreamWriter? log = null;
+ var previousWriter = Console.Out;
+ int result;
+ try
+ {
+ log = new StreamWriter(logPath, false, new UTF8Encoding(false)) { AutoFlush = true };
+ Console.SetOut(new ProgressWriter(log, messages));
+ result = await Task.Run(async () =>
+ {
+ Console.WriteLine("Preparing installation tools…");
+ PrepareBundle();
+ cancellation.Token.ThrowIfCancellationRequested();
+ if (!PrecompiledPackage.Enabled) await EnsureWindowsTools(cancellation.Token);
cancellation.Token.ThrowIfCancellationRequested();
+ if (updating)
+ {
+ InstallationUpdate.Apply(InstallerEngine.BundleRoot!, target);
+ return 0;
+ }
return InstallerEngine.Run(new[] { selectedIso, target });
- });
- }
- catch (OperationCanceledException) { Console.WriteLine("Installation cancelled."); result = 1223; }
- catch (Exception error) { Console.WriteLine(error.Message); result = 100; }
- finally { Console.SetOut(previousWriter); }
- DrainMessages();
- busy = false;
- cancel.Enabled = false;
- cancellation.Dispose();
- cancellation = null;
- InstallerEngine.CancellationToken = default;
- progress.Style = ProgressBarStyle.Continuous;
- install.Enabled = true;
- if (result == 0)
+ });
+ }
+ catch (OperationCanceledException) { messages.Enqueue("Installation cancelled."); result = 1223; }
+ catch (Exception error)
{
- completed = true;
- installedPath = target;
- progress.Value = 100;
- status.Text = "Installation complete. You can now launch the game.";
- install.Text = "OPEN LAUNCHER";
- cancel.SetBounds(620, 559, 271, 30);
- cancel.Text = "Create desktop shortcut";
- cancel.Enabled = true;
- File.WriteAllText(Path.Combine(target, "Play FIFA Street.cmd"), "@echo off\r\ncd /d \"%~dp0\"\r\nstart \"\" \"%~dp0FifaStreetLauncher.exe\"\r\n", Encoding.ASCII);
+ messages.Enqueue(error.Message);
+ try { log?.WriteLine(error); }
+ catch (IOException) { /* The original error remains visible in the form. */ }
+ result = 100;
}
- else if (result == 1223)
- {
- status.Text = "Installation cancelled. Incomplete files remain in the selected folder.";
- install.Text = "INSTALL FIFA STREET";
- foreach (var input in inputs) input.Enabled = true;
- }
- else
- {
- status.Text = "Installation failed. Check the details and installation.log.";
- install.Text = "TRY AGAIN";
+ finally
+ {
+ Console.SetOut(previousWriter);
+ busy = false;
+ cancel.Enabled = false;
+ cancellation.Dispose();
+ cancellation = null;
+ InstallerEngine.CancellationToken = default;
+ progress.Style = ProgressBarStyle.Continuous;
+ install.Enabled = true;
+ try { log?.Dispose(); }
+ catch (IOException error) { messages.Enqueue("Could not finish writing the installation log: " + error.Message); }
+ }
+ DrainMessages();
+ if (result == 0)
+ {
+ completed = true;
+ installedPath = target;
+ progress.Value = 100;
+ status.Text = updating ? "Update complete. Saves and preferences preserved." : "Installation complete. You can now launch the game.";
+ install.Text = "OPEN LAUNCHER";
+ cancel.SetBounds(620, 559, 271, 30);
+ cancel.Text = "Create desktop shortcut";
+ cancel.Enabled = true;
+ try { File.WriteAllText(Path.Combine(target, "Play FIFA Street.cmd"), "@echo off\r\ncd /d \"%~dp0\"\r\nstart \"\" \"%~dp0FifaStreetLauncher.exe\"\r\n", Encoding.ASCII); }
+ catch (IOException error) { MessageBox.Show(this, "The game was installed, but the launch shortcut could not be written.\n\n" + error.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); }
+ catch (UnauthorizedAccessException error) { MessageBox.Show(this, "The game was installed, but the launch shortcut could not be written.\n\n" + error.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); }
+ }
+ else if (result == 1223)
+ {
+ status.Text = updating ? "Update cancelled. Previous files restored." : "Installation cancelled. Incomplete files remain in the selected folder.";
+ install.Text = "INSTALL FIFA STREET";
foreach (var input in inputs) input.Enabled = true;
- MessageBox.Show(this, $"Installation did not finish (code {result}).\n\nLog: {logPath}\nChoose an empty folder before trying again.", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- }
-
- void CancelInstallation()
- {
- if (!busy || cancellation == null || cancellation.IsCancellationRequested) return;
- if (MessageBox.Show(this, "Cancel installation? The game will not be ready to play. Incomplete files will remain in the selected folder.", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return;
- status.Text = "Cancelling installation…";
- cancel.Enabled = false;
- cancellation.Cancel();
- }
-
- internal static void CreateDesktopShortcut(string installFolder)
- {
- string launcher = Path.Combine(installFolder, "FifaStreetLauncher.exe");
- if (!File.Exists(launcher)) throw new FileNotFoundException("The installed launcher was not found.", launcher);
- string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
- string shortcutPath = Path.Combine(desktop, "FIFA Street PC.lnk");
- object? shell = null;
- object? shortcut = null;
- try
- {
- shell = Activator.CreateInstance(Type.GetTypeFromProgID("WScript.Shell")!);
- dynamic automation = shell!;
- shortcut = automation.CreateShortcut(shortcutPath);
- dynamic link = shortcut;
- link.TargetPath = launcher;
- link.WorkingDirectory = installFolder;
- link.IconLocation = launcher + ",0";
- link.Description = "FIFA Street PC — " + Credit;
- link.Save();
- }
- finally
- {
- if (shortcut != null) System.Runtime.InteropServices.Marshal.FinalReleaseComObject(shortcut);
- if (shell != null) System.Runtime.InteropServices.Marshal.FinalReleaseComObject(shell);
- }
- }
-
- void DrainMessages()
- {
- var text = new StringBuilder();
- while (messages.TryDequeue(out var line))
- {
- text.AppendLine(line);
- if (line.StartsWith("Preparing ") || line.StartsWith("Extracting ") || line.StartsWith("Installing ") || line.StartsWith("Recompiling ") || line.Contains("/6]")) status.Text = line;
- }
- if (text.Length == 0) return;
- if (details.TextLength > 50000) details.Clear();
- details.AppendText(text.ToString());
- }
-
- internal static void PrepareBundle()
- {
- string root = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FifaStreetSetup", Assembly.GetExecutingAssembly().ManifestModule.ModuleVersionId.ToString("N"));
- string ready = Path.Combine(root, ".ready");
- if (!File.Exists(ready))
- {
- Directory.CreateDirectory(root);
- using var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream("bundle.zip")
- ?? throw new IOException("The installer does not contain the required tools.");
- using var zip = new ZipArchive(resource);
- zip.ExtractToDirectory(root, true);
- File.Copy(Path.Combine(root, "compiler", "bin", "clang.exe"), Path.Combine(root, "compiler", "bin", "clang++.exe"), true);
- File.WriteAllText(ready, "ready");
- }
- InstallerEngine.BundleRoot = root;
- Environment.SetEnvironmentVariable("FIFA_BUILD_ROOT", Path.Combine(Path.GetTempPath(), "FSB"));
- }
-
- static async Task EnsureWindowsTools()
- {
- string vswhere = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Microsoft Visual Studio", "Installer", "vswhere.exe");
- if (File.Exists(vswhere))
- {
- var info = new ProcessStartInfo(vswhere) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true };
- foreach (string arg in new[] { "-latest", "-products", "*", "-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath" }) info.ArgumentList.Add(arg);
- using var check = Process.Start(info)!;
- string location = await check.StandardOutput.ReadToEndAsync();
- await check.WaitForExitAsync();
- if (!string.IsNullOrWhiteSpace(location)) return;
- }
- Console.WriteLine("Preparing Windows components. Accept the Windows prompt to continue.");
- string bootstrapper = Path.Combine(Path.GetTempPath(), "FifaStreet-vs-buildtools.exe");
- using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(10) };
- using (var stream = await http.GetStreamAsync("https://aka.ms/vs/17/release/vs_buildtools.exe"))
- using (var file = File.Create(bootstrapper)) await stream.CopyToAsync(file);
- using var setup = Process.Start(new ProcessStartInfo(bootstrapper, "--passive --wait --norestart --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended") { UseShellExecute = true, Verb = "runas" })!;
- await setup.WaitForExitAsync();
- if (setup.ExitCode != 0 && setup.ExitCode != 3010) throw new IOException($"Windows components could not be installed (code {setup.ExitCode}).");
- if (setup.ExitCode == 3010) throw new IOException("Restart Windows and run the installer again to continue.");
- }
-
- sealed class ProgressWriter(StreamWriter log, System.Collections.Concurrent.ConcurrentQueue<string> queue) : TextWriter
- {
- readonly object gate = new();
- public override Encoding Encoding => Encoding.UTF8;
- public override void WriteLine(string? value)
- {
- lock (gate) { log.WriteLine(value); queue.Enqueue(value ?? ""); }
- }
- public override void WriteLine() => WriteLine("");
- }
-
- sealed class MessiPicture : PictureBox
- {
- protected override void OnPaint(PaintEventArgs e)
- {
- if (Image == null) return;
- e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
- // Show Messi at full panel height, excluding the cover header and footer.
- var crop = new RectangleF(Image.Width * 100f / 1280f, Image.Height * 225f / 1819f,
- Image.Width * 640f / 1280f, Image.Height * 1260f / 1819f);
- e.Graphics.DrawImage(Image, ClientRectangle, crop, GraphicsUnit.Pixel);
- }
- }
-}
+ RefreshInstallMode();
+ }
+ else
+ {
+ status.Text = updating ? "Update failed. Check the details and update.log." : "Installation failed. Check the details and installation.log.";
+ install.Text = "TRY AGAIN";
+ foreach (var input in inputs) input.Enabled = true;
+ RefreshInstallMode();
+ MessageBox.Show(this, $"Installation did not finish (code {result}).\n\nLog: {logPath}\n" + (updating ? "Keep your installation and check the log before trying again." : "Choose an empty folder before trying again."), Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
+ }
+
+ void CancelInstallation()
+ {
+ if (!busy || cancellation == null || cancellation.IsCancellationRequested) return;
+ bool updating = PrecompiledPackage.Enabled && InstallationUpdate.IsInstallation(destination.Text);
+ string question = updating ? "Cancel update? The installer will restore the previous files. Keep the installer open until restoration finishes." : "Cancel installation? The game will not be ready to play. Incomplete files will remain in the selected folder.";
+ if (MessageBox.Show(this, question, Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return;
+ status.Text = "Cancelling installation…";
+ cancel.Enabled = false;
+ cancellation.Cancel();
+ }
+
+ internal static void CreateDesktopShortcut(string installFolder)
+ {
+ string launcher = Path.Combine(installFolder, "FifaStreetLauncher.exe");
+ if (!File.Exists(launcher)) throw new FileNotFoundException("The installed launcher was not found.", launcher);
+ string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
+ string shortcutPath = Path.Combine(desktop, "FIFA Street PC.lnk");
+ object? shell = null;
+ object? shortcut = null;
+ try
+ {
+ shell = Activator.CreateInstance(Type.GetTypeFromProgID("WScript.Shell")!);
+ dynamic automation = shell!;
+ shortcut = automation.CreateShortcut(shortcutPath);
+ dynamic link = shortcut;
+ link.TargetPath = launcher;
+ link.WorkingDirectory = installFolder;
+ link.IconLocation = launcher + ",0";
+ link.Description = "FIFA Street PC — " + Credit;
+ link.Save();
+ }
+ finally
+ {
+ if (shortcut != null) System.Runtime.InteropServices.Marshal.FinalReleaseComObject(shortcut);
+ if (shell != null) System.Runtime.InteropServices.Marshal.FinalReleaseComObject(shell);
+ }
+ }
+
+ void DrainMessages()
+ {
+ var text = new StringBuilder();
+ while (messages.TryDequeue(out var line))
+ {
+ text.AppendLine(line);
+ if (line.StartsWith("Preparing ") || line.StartsWith("Checking ") || line.StartsWith("Extracting ") || line.StartsWith("Installing ") || line.StartsWith("Recompiling ") || line.Contains("/6]")) status.Text = line;
+ }
+ if (text.Length == 0) return;
+ if (details.TextLength > 50000) details.Clear();
+ details.AppendText(text.ToString());
+ }
+
+ internal static void PrepareBundle()
+ {
+ string root = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FifaStreetSetup", Assembly.GetExecutingAssembly().ManifestModule.ModuleVersionId.ToString("N"));
+ string ready = Path.Combine(root, ".ready");
+ if (!File.Exists(ready))
+ {
+ Directory.CreateDirectory(root);
+ using var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream("bundle.zip")
+ ?? throw new IOException("The installer does not contain the required tools.");
+ using var zip = new ZipArchive(resource);
+ zip.ExtractToDirectory(root, true);
+ if (!PrecompiledPackage.Enabled)
+ File.Copy(Path.Combine(root, "compiler", "bin", "clang.exe"), Path.Combine(root, "compiler", "bin", "clang++.exe"), true);
+ File.WriteAllText(ready, "ready");
+ }
+ InstallerEngine.BundleRoot = root;
+ Environment.SetEnvironmentVariable("FIFA_BUILD_ROOT", Path.Combine(Path.GetTempPath(), "FSB"));
+ }
+
+ static async Task EnsureWindowsTools(System.Threading.CancellationToken token)
+ {
+ string vswhere = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Microsoft Visual Studio", "Installer", "vswhere.exe");
+ if (File.Exists(vswhere))
+ {
+ var info = new ProcessStartInfo(vswhere) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true };
+ foreach (string arg in new[] { "-latest", "-products", "*", "-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath" }) info.ArgumentList.Add(arg);
+ using var check = Process.Start(info)!;
+ string location = await check.StandardOutput.ReadToEndAsync(token);
+ await check.WaitForExitAsync(token);
+ if (!string.IsNullOrWhiteSpace(location)) return;
+ }
+ Console.WriteLine("Preparing Windows components. Accept the Windows prompt to continue.");
+ string bootstrapper = Path.Combine(Path.GetTempPath(), "FifaStreet-vs-buildtools.exe");
+ using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(10) };
+ using (var stream = await http.GetStreamAsync("https://aka.ms/vs/17/release/vs_buildtools.exe", token))
+ using (var file = File.Create(bootstrapper)) await stream.CopyToAsync(file, token);
+ token.ThrowIfCancellationRequested();
+ // The elevated Microsoft installer manages shared system components.
+ // Keep this stage explicit instead of pretending the local Cancel
+ // button can safely terminate it midway through a system installation.
+ Console.WriteLine("Installing Windows components. This stage must finish before cancellation can complete.");
+ using var setup = Process.Start(new ProcessStartInfo(bootstrapper, "--passive --wait --norestart --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended") { UseShellExecute = true, Verb = "runas" })!;
+ await setup.WaitForExitAsync();
+ token.ThrowIfCancellationRequested();
+ if (setup.ExitCode != 0 && setup.ExitCode != 3010) throw new IOException($"Windows components could not be installed (code {setup.ExitCode}).");
+ if (setup.ExitCode == 3010) throw new IOException("Restart Windows and run the installer again to continue.");
+ }
+
+ sealed class ProgressWriter(StreamWriter log, System.Collections.Concurrent.ConcurrentQueue<string> queue) : TextWriter
+ {
+ readonly object gate = new();
+ public override Encoding Encoding => Encoding.UTF8;
+ public override void WriteLine(string? value)
+ {
+ lock (gate) { log.WriteLine(value); queue.Enqueue(value ?? ""); }
+ }
+ public override void WriteLine() => WriteLine("");
+ }
+
+ sealed class MessiPicture : PictureBox
+ {
+ protected override void OnPaint(PaintEventArgs e)
+ {
+ if (Image == null) return;
+ e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
+ // Show Messi at full panel height, excluding the cover header and footer.
+ var crop = new RectangleF(Image.Width * 100f / 1280f, Image.Height * 225f / 1819f,
+ Image.Width * 640f / 1280f, Image.Height * 1260f / 1819f);
+ e.Graphics.DrawImage(Image, ClientRectangle, crop, GraphicsUnit.Pixel);
+ }
+ }
+}
diff --git a/Installer/PRECOMPILED.md b/Installer/PRECOMPILED.md
new file mode 100644
index 0000000..6bf5c40
--- /dev/null
+++ b/Installer/PRECOMPILED.md
@@ -0,0 +1,11 @@
+# Precompiled installation (local candidate)
+
+The precompiled installer asks for an ISO and a destination. It extracts the ISO on the destination volume, checks SHA-256 hashes of the three original executable modules, validates the entire runtime payload, moves the extracted data into `GameData`, applies the existing credits patch, and installs the launcher and both graphics backends. It does not install Visual Studio or run code generation or compilation.
+
+The existing source installer remains available. A precompiled installer accepts only the executable version recorded in its manifest; an unrecognised ISO is rejected before the extracted data and runtime payload are installed. Region names are not inferred from those hashes.
+
+`BuildPrecompiled.py` takes explicit paths to a tested runtime, the original module inputs, extract-xiso, an existing license bundle, and the official x64 CRT redistributable folder and notices. It builds into a new output directory and never overwrites the tested runtime. It bundles the CRT locally with the game and extraction tool. Windows 10/11 and appropriate graphics drivers are still required. The launcher and setup include their .NET runtime.
+
+The build creates `precompiled.json`, a self-contained setup executable, and `build.json` with the setup hash and complete payload manifest. No ISO or extracted game assets are packaged. Recompiled executable code is included; its redistribution rights need a separate review before publication. This candidate must remain local until that review and gameplay validation are complete.
+
+Validation: run the setup with `--install-test <ISO> <new destination>` for a logged installation without opening the form. Run the installed launcher afterwards to validate gameplay and World Tour. Installer timing depends on storage, caching, antivirus and the ISO; a local installation measurement is not a guarantee for other machines.
diff --git a/Installer/backend-manifest.json b/Installer/backend-manifest.json
new file mode 100644
index 0000000..67ce1c5
--- /dev/null
+++ b/Installer/backend-manifest.json
@@ -0,0 +1,15 @@
+{
+ "version": "v0.4.0-candidate",
+ "backends": {
+ "D3D12": {
+ "source": "out/win-amd64/Release",
+ "runtimeHash": "cf737323bdeb0351cb9099574e16128ad5ded93876b8fb1ba9f6fe472572678b",
+ "gpuHash": "22ab97adf3da623ed74222e8d056f4db3ef2fefa45826855e61b6e48a4b96e6b"
+ },
+ "Vulkan": {
+ "source": "out/win-amd64-vulkan/Release",
+ "runtimeHash": "dec0334865571c14fde48fe4674d30ab74887c1d48253976ec05fb2027d62c16",
+ "gpuHash": "7ad2b33ba133e8bea425f678b69bf5332a3ffab3d1b58d0d522cb2a43a7f888b"
+ }
+ }
+}
diff --git a/Installer/recomp-template/CMakeLists.txt b/Installer/recomp-template/CMakeLists.txt
index 49eb2b0..df8086f 100644
--- a/Installer/recomp-template/CMakeLists.txt
+++ b/Installer/recomp-template/CMakeLists.txt
@@ -1,72 +1,72 @@
-# fifastreet - ReXGlue Recompiled Project
-#
-# SDK boilerplate lives in generated/rexglue.cmake.
-
-cmake_minimum_required(VERSION 3.25)
-project(fifastreet LANGUAGES CXX)
-
-set(CMAKE_CXX_STANDARD 23)
-set(CMAKE_CXX_STANDARD_REQUIRED ON)
-
-include(generated/rexglue.cmake)
-
-# Sources
-set(FIFASTREET_SOURCES
- src/main.cpp
-)
-
-if(WIN32)
- enable_language(RC)
- add_executable(fifastreet WIN32 ${FIFASTREET_SOURCES})
- target_sources(fifastreet PRIVATE src/fifastreet.rc)
-
- if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
- set_source_files_properties(src/fifastreet.rc PROPERTIES
- COMPILE_OPTIONS "-P"
- )
- target_include_directories(fifastreet PRIVATE
- "${CMAKE_CURRENT_SOURCE_DIR}/src"
- )
- endif()
-else()
- add_executable(fifastreet ${FIFASTREET_SOURCES})
-endif()
-
-rexglue_setup_target(fifastreet GPU_PLUGINS xenos)
-target_include_directories(fifastreet PRIVATE src)
-
-# The source SDK keeps ImGui private to rexruntime; its public UI headers
-# still require the include directory when compiling the host application.
-# Propagate headers only, keeping the ImGui objects in the shared runtime.
-if(TARGET imgui::imgui)
- target_include_directories(fifastreet PRIVATE
- $<TARGET_PROPERTY:imgui::imgui,INTERFACE_INCLUDE_DIRECTORIES>)
-endif()
-
-# Guest SIMD code must be optimized even when using the debug runtime. Keep
-# debug symbols and checked runtime libraries while avoiding unoptimized SIMD
-# wrappers in the game and its separately compiled DLL.
-if(CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU")
- target_compile_options(fifastreet PRIVATE -O2)
- if(TARGET fifastreet_recomp)
- target_compile_options(fifastreet_recomp PRIVATE -O2)
- endif()
-endif()
-
-# FIFA Street DLL-specific kernel stubs.
-if(TARGET fifastreet_fifadllzf_xex)
- if(CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU")
- target_compile_options(fifastreet_fifadllzf_xex PRIVATE -O2)
- endif()
- target_sources(fifastreet_fifadllzf_xex PRIVATE
- src/stubs.cpp
- )
-endif()
-
-# World Tour competition engine DLL. Keep it optimized, but do not attach
-# fifadllzf-specific stubs to this independent guest module.
-if(TARGET fifastreet_FootballCompEngzf_xex)
- if(CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU")
- target_compile_options(fifastreet_FootballCompEngzf_xex PRIVATE -O2)
- endif()
-endif()
+# fifastreet - ReXGlue Recompiled Project
+#
+# SDK boilerplate lives in generated/rexglue.cmake.
+
+cmake_minimum_required(VERSION 3.25)
+project(fifastreet LANGUAGES CXX)
+
+set(CMAKE_CXX_STANDARD 23)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+
+include(generated/rexglue.cmake)
+
+# Sources
+set(FIFASTREET_SOURCES
+ src/main.cpp
+)
+
+if(WIN32)
+ enable_language(RC)
+ add_executable(fifastreet WIN32 ${FIFASTREET_SOURCES})
+ target_sources(fifastreet PRIVATE src/fifastreet.rc)
+
+ if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
+ set_source_files_properties(src/fifastreet.rc PROPERTIES
+ COMPILE_OPTIONS "/nologo"
+ )
+ target_include_directories(fifastreet PRIVATE
+ "${CMAKE_CURRENT_SOURCE_DIR}/src"
+ )
+ endif()
+else()
+ add_executable(fifastreet ${FIFASTREET_SOURCES})
+endif()
+
+rexglue_setup_target(fifastreet GPU_PLUGINS xenos)
+target_include_directories(fifastreet PRIVATE src)
+
+# The source SDK keeps ImGui private to rexruntime; its public UI headers
+# still require the include directory when compiling the host application.
+# Propagate headers only, keeping the ImGui objects in the shared runtime.
+if(TARGET imgui::imgui)
+ target_include_directories(fifastreet PRIVATE
+ $<TARGET_PROPERTY:imgui::imgui,INTERFACE_INCLUDE_DIRECTORIES>)
+endif()
+
+# Guest SIMD code must be optimized even when using the debug runtime. Keep
+# debug symbols and checked runtime libraries while avoiding unoptimized SIMD
+# wrappers in the game and its separately compiled DLL.
+if(CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU")
+ target_compile_options(fifastreet PRIVATE -O2)
+ if(TARGET fifastreet_recomp)
+ target_compile_options(fifastreet_recomp PRIVATE -O2)
+ endif()
+endif()
+
+# FIFA Street DLL-specific kernel stubs.
+if(TARGET fifastreet_fifadllzf_xex)
+ if(CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU")
+ target_compile_options(fifastreet_fifadllzf_xex PRIVATE -O2)
+ endif()
+ target_sources(fifastreet_fifadllzf_xex PRIVATE
+ src/stubs.cpp
+ )
+endif()
+
+# World Tour competition engine DLL. Keep it optimized, but do not attach
+# fifadllzf-specific stubs to this independent guest module.
+if(TARGET fifastreet_FootballCompEngzf_xex)
+ if(CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU")
+ target_compile_options(fifastreet_FootballCompEngzf_xex PRIVATE -O2)
+ endif()
+endif()
diff --git a/Installer/recomp-template/config/footballcompeng_overrides.toml b/Installer/recomp-template/config/footballcompeng_overrides.toml
new file mode 100644
index 0000000..4ce1814
--- /dev/null
+++ b/Installer/recomp-template/config/footballcompeng_overrides.toml
@@ -0,0 +1,6 @@
+# Function boundary overrides for FootballCompEngzf codegen.
+# Generated by the Recomp Hub.
+
+[functions]
+
+"0x880540F8" = { end = 0x880541A0 }
diff --git a/Installer/recomp-template/fifastreet_manifest.toml b/Installer/recomp-template/fifastreet_manifest.toml
index 0c809a0..40c383c 100644
--- a/Installer/recomp-template/fifastreet_manifest.toml
+++ b/Installer/recomp-template/fifastreet_manifest.toml
@@ -1,23 +1,23 @@
-# Generated by ReXGlue v0.10.0.2-dev.gc94f5eb on 2026-09-30 00:37:42 UTC.
-
-[project]
-name = "fifastreet"
-sdk_version = "0.10.0"
-game_root = "../fifastreetrecomp/private"
-
-[entrypoint]
-file_path = "../fifastreetrecomp/private/default.xex"
-out_directory_path = "generated/default"
-includes = []
-
-[[modules]]
-guest_path = "game:\\fifadllzf.xex.dll"
-file_path = "../fifastreetrecomp/private/fifadllzf.xex.dll"
-out_directory_path = "generated/fifadllzf_xex"
-includes = ["config/fifadllzf_overrides.toml"]
-
-[[modules]]
-guest_path = "game:\\FootballCompEngzf.xex.dll"
-file_path = "../fifastreetrecomp/private/FootballCompEngzf.xex.dll"
-out_directory_path = "generated/FootballCompEngzf_xex"
-includes = []
+# Generated by ReXGlue v0.10.0.2-dev.gc94f5eb on 2026-09-30 00:37:42 UTC.
+
+[project]
+name = "fifastreet"
+sdk_version = "0.10.0"
+game_root = "../fifastreetrecomp/private"
+
+[entrypoint]
+file_path = "../fifastreetrecomp/private/default.xex"
+out_directory_path = "generated/default"
+includes = []
+
+[[modules]]
+guest_path = "game:\\fifadllzf.xex.dll"
+file_path = "../fifastreetrecomp/private/fifadllzf.xex.dll"
+out_directory_path = "generated/fifadllzf_xex"
+includes = ["config/fifadllzf_overrides.toml"]
+
+[[modules]]
+guest_path = "game:\\FootballCompEngzf.xex.dll"
+file_path = "../fifastreetrecomp/private/FootballCompEngzf.xex.dll"
+out_directory_path = "generated/FootballCompEngzf_xex"
+includes = ["config/footballcompeng_overrides.toml"]
diff --git a/Installer/recomp-template/src/fifastreet_app.h b/Installer/recomp-template/src/fifastreet_app.h
index 3ba8419..0a78fc8 100644
--- a/Installer/recomp-template/src/fifastreet_app.h
+++ b/Installer/recomp-template/src/fifastreet_app.h
@@ -1,59 +1,65 @@
-// fifastreet - ReXGlue Recompiled Project
-//
-// Customize your app by overriding virtual hooks from rex::ReXApp.
-
-#pragma once
-
-#include <rex/rex_app.h>
-#include <rex/cvar.h>
-#include <rex/filesystem.h>
-#include <rex/ui/window.h>
-
-class FifastreetApp : public rex::ReXApp {
- public:
- using rex::ReXApp::ReXApp;
-
- static std::unique_ptr<rex::ui::WindowedApp> Create(
- rex::ui::WindowedAppContext& ctx) {
- return std::unique_ptr<FifastreetApp>(new FifastreetApp(ctx, "fifastreet",
- PPCImageConfig));
- }
-
- void OnPreSetup(rex::RuntimeConfig& config) override {
- if (config.gpu_plugin.empty()) {
- config.gpu_plugin = "xenos";
- }
- }
-
- void OnConfigurePaths(rex::PathConfig& paths) override {
- if (paths.game_data_root.empty()) {
- auto bundled_data = rex::filesystem::GetExecutableFolder().parent_path() / "GameData";
- if (std::filesystem::exists(bundled_data / "default.xex")) {
- paths.game_data_root = bundled_data;
- }
- }
- }
-
- void OnCreateDialogs(rex::ui::ImGuiDrawer*) override {
- window()->SetTitle("FIFA Street PC");
- }
-
- void OnPostSetup() override {
- // FIFA Street uses texture fetch descriptors with the invalid-texture tag.
- // Their address and format fields are still valid and must be decoded.
- rex::cvar::SetFlagByName("gpu_allow_invalid_fetch_constants", "true");
- }
-
- // Override virtual hooks for customization:
- // void OnPostInitLogging() override {}
- // void OnPreSetup(rex::RuntimeConfig& config) override {}
- // void OnLoadXexImage(std::string& xex_image) override {}
- // void OnPostLoadXexImage() override {}
- // void OnPostSetup() override {}
- // void OnCreateDialogs(rex::ui::ImGuiDrawer* drawer) override {}
- // std::unique_ptr<rex::ui::ImGuiDialog> CreateAchievementsOverlay() override;
- // std::unique_ptr<rex::ui::AchievementNotificationDialog>
- // CreateAchievementNotificationDialog() override;
- // void OnShutdown() override {}
- // void OnConfigurePaths(rex::PathConfig& paths) override {}
-};
+// fifastreet - ReXGlue Recompiled Project
+//
+// Customize your app by overriding virtual hooks from rex::ReXApp.
+
+#pragma once
+
+#include <rex/rex_app.h>
+#include <rex/cvar.h>
+#include <rex/filesystem.h>
+#include <rex/ui/window.h>
+
+class FifastreetApp : public rex::ReXApp {
+ public:
+ using rex::ReXApp::ReXApp;
+
+ static std::unique_ptr<rex::ui::WindowedApp> Create(
+ rex::ui::WindowedAppContext& ctx) {
+ return std::unique_ptr<FifastreetApp>(new FifastreetApp(ctx, "fifastreet",
+ PPCImageConfig));
+ }
+
+ void OnPreSetup(rex::RuntimeConfig& config) override {
+ if (config.gpu_plugin.empty()) {
+ config.gpu_plugin = "xenos";
+ }
+ }
+
+ void OnConfigurePaths(rex::PathConfig& paths) override {
+ if (paths.game_data_root.empty()) {
+ const auto executable_folder = rex::filesystem::GetExecutableFolder();
+ for (const auto& candidate : {executable_folder, executable_folder / "GameData",
+ executable_folder.parent_path() / "GameData",
+ executable_folder.parent_path()}) {
+ std::error_code error;
+ if (std::filesystem::is_regular_file(candidate / "default.xex", error)) {
+ paths.game_data_root = candidate;
+ break;
+ }
+ }
+ }
+ }
+
+ void OnCreateDialogs(rex::ui::ImGuiDrawer*) override {
+ window()->SetTitle("FIFA Street PC");
+ }
+
+ void OnPostSetup() override {
+ // FIFA Street uses texture fetch descriptors with the invalid-texture tag.
+ // Their address and format fields are still valid and must be decoded.
+ rex::cvar::SetFlagByName("gpu_allow_invalid_fetch_constants", "true");
+ }
+
+ // Override virtual hooks for customization:
+ // void OnPostInitLogging() override {}
+ // void OnPreSetup(rex::RuntimeConfig& config) override {}
+ // void OnLoadXexImage(std::string& xex_image) override {}
+ // void OnPostLoadXexImage() override {}
+ // void OnPostSetup() override {}
+ // void OnCreateDialogs(rex::ui::ImGuiDrawer* drawer) override {}
+ // std::unique_ptr<rex::ui::ImGuiDialog> CreateAchievementsOverlay() override;
+ // std::unique_ptr<rex::ui::AchievementNotificationDialog>
+ // CreateAchievementNotificationDialog() override;
+ // void OnShutdown() override {}
+ // void OnConfigurePaths(rex::PathConfig& paths) override {}
+};
diff --git a/Launcher/FifaStreetLauncher/LauncherForm.cs b/Launcher/FifaStreetLauncher/LauncherForm.cs
index 8c18cc3..1379873 100644
--- a/Launcher/FifaStreetLauncher/LauncherForm.cs
+++ b/Launcher/FifaStreetLauncher/LauncherForm.cs
@@ -1,1621 +1,1795 @@
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Drawing;
-using System.Drawing.Drawing2D;
-using System.IO;
-using System.Linq;
-using System.Runtime.InteropServices;
-using System.Text.Json;
-using System.Windows.Forms;
-
-namespace FifaStreetLauncher;
-
-public class LauncherForm : Form
-{
- private readonly Color Bg = Color.FromArgb(10, 12, 16);
- private readonly Color Surface = Color.FromArgb(18, 22, 28);
- private readonly Color SurfaceAlt = Color.FromArgb(24, 29, 36);
- private readonly Color Border = Color.FromArgb(48, 57, 68);
- private readonly Color Accent = Color.FromArgb(133, 255, 72);
- private readonly Color AccentHover = Color.FromArgb(111, 229, 53);
- private readonly Color TextPrimary = Color.FromArgb(245, 247, 250);
- private readonly Color TextSecondary = Color.FromArgb(151, 161, 175);
-
- private readonly ComboBox resolutionBox = new();
- private readonly ComboBox refreshBox = new();
- private readonly ComboBox displayModeBox = new();
- private readonly ComboBox monitorBox = new();
- private readonly ComboBox graphicsApiBox = new();
- private readonly ComboBox gpuBox = new();
- private readonly List<int> gpuAdapterIndices = new();
- private readonly ComboBox postEffectBox = new();
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Drawing;
+using System.Drawing.Drawing2D;
+using System.IO;
+using System.Linq;
+using System.Runtime.InteropServices;
+using System.Text.Json;
+using System.Windows.Forms;
+
+namespace FifaStreetLauncher;
+
+public class LauncherForm : Form
+{
+ private readonly Color Bg = Color.FromArgb(10, 12, 16);
+ private readonly Color Surface = Color.FromArgb(18, 22, 28);
+ private readonly Color SurfaceAlt = Color.FromArgb(24, 29, 36);
+ private readonly Color Border = Color.FromArgb(48, 57, 68);
+ private readonly Color Accent = Color.FromArgb(133, 255, 72);
+ private readonly Color AccentHover = Color.FromArgb(111, 229, 53);
+ private readonly Color TextPrimary = Color.FromArgb(245, 247, 250);
+ private readonly Color TextSecondary = Color.FromArgb(151, 161, 175);
+
+ private readonly ComboBox resolutionBox = new();
+ private readonly ComboBox refreshBox = new();
+ private readonly ComboBox displayModeBox = new();
+ private readonly ComboBox monitorBox = new();
+ private readonly ComboBox graphicsApiBox = new();
+ private readonly ComboBox gpuBox = new();
+ private readonly List<int> gpuAdapterIndices = new();
+ private readonly ComboBox postEffectBox = new();
private readonly ComboBox internalResolutionBox = new();
-
- private readonly CheckBox vsyncBox = new();
- private readonly CheckBox vrrBox = new();
- private readonly CheckBox msaaBox = new();
- private readonly CheckBox readbackMemexportBox = new();
- private readonly CheckBox readbackMemexportFastBox = new();
- private readonly CheckBox clearMemoryPageStateBox = new();
- private readonly CheckBox occlusionQueryBox = new();
- private readonly CheckBox asyncShadersBox = new();
-
- private readonly TextBox gamePathBox = new();
- private readonly TextBox exePathBox = new();
-
- private readonly Label statusLabel = new();
- private readonly Label hardwareLabel = new();
- private readonly Label advancedChevron = new();
-
- private readonly RoundedPanel advancedPanel = new();
- private readonly ModernButton advancedButton = new();
- private readonly RoundedPanel compatibilityPanel = new();
- private readonly ModernButton compatibilityButton = new();
-
- private bool advancedVisible;
- private bool compatibilityVisible;
-
- private string SettingsPath =>
- Path.Combine(AppContext.BaseDirectory, "settings.json");
-
- public LauncherForm()
- {
- Text = "FIFA Street Launcher";
- using (var icon = typeof(LauncherForm).Assembly.GetManifestResourceStream("fifastreet.ico")!)
- Icon = new Icon(icon);
- ClientSize = new Size(1250, 720);
- MinimumSize = new Size(1266, 759);
- MaximumSize = new Size(1266, 960);
- StartPosition = FormStartPosition.CenterScreen;
- FormBorderStyle = FormBorderStyle.FixedSingle;
- MaximizeBox = false;
- BackColor = Bg;
- ForeColor = TextPrimary;
- Font = new Font("Segoe UI", 10F);
- AutoScaleMode = AutoScaleMode.Dpi;
-
- BuildInterface();
- WireEvents();
- LoadDefaults();
- LoadSettings();
- UpdateSummary();
- UpdateStatus("Ready to play", true);
- }
-
- private void BuildInterface()
- {
- SuspendLayout();
-
- var brand = new Label
- {
- Text = "FIFA STREET",
- Font = new Font("Segoe UI", 30F, FontStyle.Bold),
- ForeColor = TextPrimary,
- AutoSize = true,
- Location = new Point(40, 30)
- };
- Controls.Add(brand);
-
- var subtitle = new Label
- {
- Text = "NATIVE PC RECOMP",
- Font = new Font("Segoe UI Semibold", 9F),
- ForeColor = Accent,
- AutoSize = true,
- Location = new Point(44, 84)
- };
- Controls.Add(subtitle);
-
- var topLine = new Panel
- {
- BackColor = Accent,
- Location = new Point(40, 112),
- Size = new Size(860, 2)
- };
- Controls.Add(topLine);
-
- var readyDot = new Label
- {
- Text = "●",
- ForeColor = Accent,
- AutoSize = true,
- Font = new Font("Segoe UI", 10F, FontStyle.Bold),
- Location = new Point(726, 45)
- };
- Controls.Add(readyDot);
-
- statusLabel.AutoSize = true;
- statusLabel.Font = new Font("Segoe UI Semibold", 9.5F);
- statusLabel.ForeColor = TextSecondary;
- statusLabel.Location = new Point(746, 46);
- Controls.Add(statusLabel);
-
- hardwareLabel.Text = "Detecting hardware...";
- hardwareLabel.ForeColor = TextSecondary;
- hardwareLabel.Font = new Font("Segoe UI", 9.5F);
- hardwareLabel.AutoEllipsis = true;
- hardwareLabel.TextAlign = ContentAlignment.MiddleRight;
- hardwareLabel.Location = new Point(455, 72);
- hardwareLabel.Size = new Size(445, 24);
- Controls.Add(hardwareLabel);
-
- var displayCard = CreateCard(new Point(40, 145), new Size(420, 360));
- Controls.Add(displayCard);
-
- AddSectionHeader(displayCard, "DISPLAY", "Display settings", 24, 20);
-
- AddFieldLabel(displayCard, "Resolution", 24, 82);
- ConfigureCombo(resolutionBox, 24, 106, 372);
- displayCard.Controls.Add(resolutionBox);
-
- AddFieldLabel(displayCard, "Refresh rate", 24, 150);
- ConfigureCombo(refreshBox, 24, 174, 180);
- displayCard.Controls.Add(refreshBox);
-
- AddFieldLabel(displayCard, "Display mode", 216, 150);
- ConfigureCombo(displayModeBox, 216, 174, 180);
- displayCard.Controls.Add(displayModeBox);
-
- AddFieldLabel(displayCard, "Monitor", 24, 218);
- ConfigureCombo(monitorBox, 24, 242, 372);
+ private readonly ComboBox gameLanguageBox = new();
+ private static readonly int[] GameLanguageIds = { 1, 5, 4, 3, 6 };
+
+ private readonly CheckBox vsyncBox = new();
+ private readonly CheckBox vrrBox = new();
+ private readonly CheckBox msaaBox = new();
+ private readonly CheckBox readbackMemexportBox = new();
+ private readonly CheckBox readbackMemexportFastBox = new();
+ private readonly CheckBox clearMemoryPageStateBox = new();
+ private readonly CheckBox occlusionQueryBox = new();
+ private readonly CheckBox asyncShadersBox = new();
+
+ private readonly TextBox gamePathBox = new();
+ private readonly TextBox exePathBox = new();
+
+ private readonly Label statusLabel = new();
+ private readonly Label hardwareLabel = new();
+ private readonly Label advancedChevron = new();
+
+ private readonly RoundedPanel advancedPanel = new();
+ private readonly ModernButton advancedButton = new();
+ private readonly RoundedPanel compatibilityPanel = new();
+ private readonly ModernButton compatibilityButton = new();
+
+ private bool gameRunning;
+ private bool closeAfterGame;
+ private string? changedDisplay;
+ private DEVMODE previousDisplayMode;
+ private bool advancedVisible;
+ private bool compatibilityVisible;
+
+ private string SettingsPath =>
+ Path.Combine(AppContext.BaseDirectory, "settings.json");
+
+ public LauncherForm()
+ {
+ Text = "FIFA Street Launcher";
+ using (var icon = typeof(LauncherForm).Assembly.GetManifestResourceStream("fifastreet.ico")!)
+ Icon = new Icon(icon);
+ ClientSize = new Size(1250, 720);
+ MinimumSize = new Size(1266, 759);
+ MaximumSize = new Size(1266, 960);
+ StartPosition = FormStartPosition.CenterScreen;
+ FormBorderStyle = FormBorderStyle.FixedSingle;
+ MaximizeBox = false;
+ BackColor = Bg;
+ ForeColor = TextPrimary;
+ Font = new Font("Segoe UI", 10F);
+ AutoScaleMode = AutoScaleMode.Dpi;
+
+ BuildInterface();
+ WireEvents();
+ LoadDefaults();
+ LoadSettings();
+ UpdateGraphicsApiState();
+ UpdateRefreshRates();
+ UpdateSummary();
+ UpdateStatus("Ready to play", true);
+ }
+
+ private void BuildInterface()
+ {
+ SuspendLayout();
+
+ var brand = new Label
+ {
+ Text = "FIFA STREET",
+ Font = new Font("Segoe UI", 30F, FontStyle.Bold),
+ ForeColor = TextPrimary,
+ AutoSize = true,
+ Location = new Point(40, 30)
+ };
+ Controls.Add(brand);
+
+ var subtitle = new Label
+ {
+ Text = "NATIVE PC RECOMP",
+ Font = new Font("Segoe UI Semibold", 9F),
+ ForeColor = Accent,
+ AutoSize = true,
+ Location = new Point(44, 84)
+ };
+ Controls.Add(subtitle);
+
+ var topLine = new Panel
+ {
+ BackColor = Accent,
+ Location = new Point(40, 112),
+ Size = new Size(860, 2)
+ };
+ Controls.Add(topLine);
+
+ var readyDot = new Label
+ {
+ Text = "●",
+ ForeColor = Accent,
+ AutoSize = true,
+ Font = new Font("Segoe UI", 10F, FontStyle.Bold),
+ Location = new Point(726, 45)
+ };
+ Controls.Add(readyDot);
+
+ statusLabel.AutoSize = true;
+ statusLabel.Font = new Font("Segoe UI Semibold", 9.5F);
+ statusLabel.ForeColor = TextSecondary;
+ statusLabel.Location = new Point(746, 46);
+ Controls.Add(statusLabel);
+
+ hardwareLabel.Text = "Detecting hardware...";
+ hardwareLabel.ForeColor = TextSecondary;
+ hardwareLabel.Font = new Font("Segoe UI", 9.5F);
+ hardwareLabel.AutoEllipsis = true;
+ hardwareLabel.TextAlign = ContentAlignment.MiddleRight;
+ hardwareLabel.Location = new Point(455, 72);
+ hardwareLabel.Size = new Size(445, 24);
+ Controls.Add(hardwareLabel);
+
+ var displayCard = CreateCard(new Point(40, 145), new Size(420, 360));
+ Controls.Add(displayCard);
+
+ AddSectionHeader(displayCard, "DISPLAY", "Display settings", 24, 20);
+
+ AddFieldLabel(displayCard, "Resolution", 24, 82);
+ ConfigureCombo(resolutionBox, 24, 106, 372);
+ displayCard.Controls.Add(resolutionBox);
+
+ AddFieldLabel(displayCard, "Refresh rate", 24, 150);
+ ConfigureCombo(refreshBox, 24, 174, 180);
+ displayCard.Controls.Add(refreshBox);
+
+ AddFieldLabel(displayCard, "Display mode", 216, 150);
+ ConfigureCombo(displayModeBox, 216, 174, 180);
+ displayCard.Controls.Add(displayModeBox);
+
+ AddFieldLabel(displayCard, "Monitor", 24, 218);
+ ConfigureCombo(monitorBox, 24, 242, 180);
displayCard.Controls.Add(monitorBox);
-
- ConfigureCheck(vsyncBox, "VSync", 24, 300);
- ConfigureCheck(vrrBox, "VRR / Tearing", 216, 300);
- displayCard.Controls.Add(vsyncBox);
- displayCard.Controls.Add(vrrBox);
-
- var graphicsCard = CreateCard(new Point(480, 145), new Size(420, 360));
- Controls.Add(graphicsCard);
-
- AddSectionHeader(graphicsCard, "GRAPHICS", "Quality and presentation", 24, 20);
-
- AddFieldLabel(graphicsCard, "Graphics API", 24, 82);
- ConfigureCombo(graphicsApiBox, 24, 106, 120);
- graphicsCard.Controls.Add(graphicsApiBox);
-
- AddFieldLabel(graphicsCard, "GPU", 156, 82);
- ConfigureCombo(gpuBox, 156, 106, 240);
- graphicsCard.Controls.Add(gpuBox);
-
-AddFieldLabel(graphicsCard, "Post-processing", 24, 150);
-ConfigureCombo(postEffectBox, 24, 174, 372);
-graphicsCard.Controls.Add(postEffectBox);
-
-AddFieldLabel(graphicsCard, "Internal Resolution", 24, 218);
-ConfigureCombo(internalResolutionBox, 24, 242, 372);
-graphicsCard.Controls.Add(internalResolutionBox);
-
-ConfigureCheck(msaaBox, "Native 2x MSAA", 24, 300);
-graphicsCard.Controls.Add(msaaBox);
-
-var fpsTitle = new Label
-{
- Text = "FPS",
- ForeColor = TextPrimary,
- Font = new Font("Segoe UI Semibold", 9F),
- AutoSize = true,
- Location = new Point(24, 330)
-};
-graphicsCard.Controls.Add(fpsTitle);
-
-var fpsInfo = new Label
-{
- Text = "Controlled by the game, VSync and refresh rate",
- ForeColor = TextSecondary,
- Font = new Font("Segoe UI", 8.7F),
- AutoSize = true,
- Location = new Point(67, 331)
- };
- graphicsCard.Controls.Add(fpsInfo);
-
- advancedButton.Text = "ADVANCED SETTINGS";
- advancedButton.Location = new Point(40, 525);
- advancedButton.Size = new Size(205, 40);
- advancedButton.FillColor = SurfaceAlt;
- advancedButton.HoverColor = Color.FromArgb(34, 41, 50);
- advancedButton.BorderColor = Border;
- advancedButton.ForeColor = TextPrimary;
- advancedButton.Font = new Font("Segoe UI Semibold", 9F);
- advancedButton.Radius = 10;
- Controls.Add(advancedButton);
-
- advancedChevron.Text = "⌄";
- advancedChevron.ForeColor = TextSecondary;
- advancedChevron.Font = new Font("Segoe UI", 13F, FontStyle.Bold);
- advancedChevron.AutoSize = true;
- advancedChevron.Location = new Point(219, 533);
- advancedChevron.BackColor = Color.Transparent;
- advancedChevron.Cursor = Cursors.Hand;
- Controls.Add(advancedChevron);
-
- compatibilityButton.Text = "COMPATIBILITY";
- compatibilityButton.Location = new Point(255, 525);
- compatibilityButton.Size = new Size(205, 40);
- compatibilityButton.FillColor = SurfaceAlt;
- compatibilityButton.HoverColor = Color.FromArgb(34, 41, 50);
- compatibilityButton.BorderColor = Border;
- compatibilityButton.ForeColor = TextPrimary;
- compatibilityButton.Font = new Font("Segoe UI Semibold", 9F);
- compatibilityButton.Radius = 10;
- Controls.Add(compatibilityButton);
-
- ConfigureAdvancedPanel();
- Controls.Add(advancedPanel);
-
- ConfigureCompatibilityPanel();
- Controls.Add(compatibilityPanel);
-
- var logsButton = new ModernButton
- {
- Text = "OPEN LOGS",
- Location = new Point(40, 590),
- Size = new Size(150, 42),
- FillColor = SurfaceAlt,
- HoverColor = Color.FromArgb(34, 41, 50),
- BorderColor = Border,
- ForeColor = TextPrimary,
- Font = new Font("Segoe UI Semibold", 9F),
- Radius = 10
- };
- logsButton.Click += (_, _) => OpenLogs();
- Controls.Add(logsButton);
-
- var folderButton = new ModernButton
- {
- Text = "OPEN FOLDER",
- Location = new Point(750, 590),
- Size = new Size(150, 42),
- FillColor = SurfaceAlt,
- HoverColor = Color.FromArgb(34, 41, 50),
- BorderColor = Border,
- ForeColor = TextPrimary,
- Font = new Font("Segoe UI Semibold", 9F),
- Radius = 10
- };
- folderButton.Click += (_, _) => OpenGameFolder();
- Controls.Add(folderButton);
-
- var playButton = new ModernButton
- {
- Text = "PLAY",
- Location = new Point(280, 575),
- Size = new Size(380, 72),
- FillColor = Accent,
- HoverColor = AccentHover,
- BorderColor = Accent,
- ForeColor = Color.FromArgb(9, 14, 8),
- Font = new Font("Segoe UI", 18F, FontStyle.Bold),
- Radius = 14
- };
- playButton.Click += (_, _) => LaunchGame();
- Controls.Add(playButton);
-
- var footer = new Label
- {
- Text = "FIFA Street • Native PC Recomp Launcher",
- ForeColor = Color.FromArgb(92, 102, 116),
- Font = new Font("Segoe UI", 8.5F),
- AutoSize = true,
- Location = new Point(40, 674)
- };
- Controls.Add(footer);
-
- foreach (Control control in Controls) control.Left += 310;
- using var resource = typeof(LauncherForm).Assembly.GetManifestResourceStream("cover.jpg")!;
- using var cover = Image.FromStream(resource);
- var artwork = new MessiPicture
- {
- Image = new Bitmap(cover), Bounds = new Rectangle(0, 0, 310, ClientSize.Height),
- Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left
- };
- Controls.Add(artwork);
- FormClosed += (_, _) => artwork.Image?.Dispose();
- var credit = new Label
- {
- Text = "PORTED BY: SAMUELITODAVILA", AutoSize = true,
- ForeColor = Accent, Font = new Font("Segoe UI", 8.5F),
- Location = new Point(730, 674), Tag = "credit"
- };
- Controls.Add(credit);
-
- ResumeLayout(false);
- PerformLayout();
- }
-
- private void ConfigureAdvancedPanel()
- {
- advancedPanel.Location = new Point(40, 575);
- advancedPanel.Size = new Size(860, 126);
- advancedPanel.FillColor = Surface;
- advancedPanel.BorderColor = Border;
- advancedPanel.Radius = 14;
- advancedPanel.Visible = false;
-
- AddFieldLabel(advancedPanel, "Game executable", 22, 18);
- exePathBox.Location = new Point(22, 42);
- exePathBox.Size = new Size(688, 27);
- StyleTextBox(exePathBox);
- advancedPanel.Controls.Add(exePathBox);
-
- var browseExe = new ModernButton
- {
- Text = "BROWSE",
- Location = new Point(724, 39),
- Size = new Size(112, 34),
- FillColor = SurfaceAlt,
- HoverColor = Color.FromArgb(34, 41, 50),
- BorderColor = Border,
- ForeColor = TextPrimary,
- Font = new Font("Segoe UI Semibold", 8.5F),
- Radius = 8
- };
- browseExe.Click += (_, _) => BrowseExe();
- advancedPanel.Controls.Add(browseExe);
-
- AddFieldLabel(advancedPanel, "Game data folder", 22, 76);
- gamePathBox.Location = new Point(22, 98);
- gamePathBox.Size = new Size(688, 27);
- StyleTextBox(gamePathBox);
- advancedPanel.Controls.Add(gamePathBox);
-
- var browseGame = new ModernButton
- {
- Text = "BROWSE",
- Location = new Point(724, 95),
- Size = new Size(112, 34),
- FillColor = SurfaceAlt,
- HoverColor = Color.FromArgb(34, 41, 50),
- BorderColor = Border,
- ForeColor = TextPrimary,
- Font = new Font("Segoe UI Semibold", 8.5F),
- Radius = 8
- };
- browseGame.Click += (_, _) => BrowseGame();
- advancedPanel.Controls.Add(browseGame);
- }
-
- private void ConfigureCompatibilityPanel()
- {
- compatibilityPanel.Location = new Point(40, 575);
- compatibilityPanel.Size = new Size(860, 182);
- compatibilityPanel.FillColor = Surface;
- compatibilityPanel.BorderColor = Border;
- compatibilityPanel.Radius = 14;
- compatibilityPanel.Visible = false;
-
- AddSectionHeader(
- compatibilityPanel,
- "COMPATIBILITY",
- "Renderer options for textures, lighting, black screens and stutter",
- 22,
- 15
- );
-
- ConfigureCheck(readbackMemexportBox, "Memory Export", 260, 72);
- ConfigureCheck(readbackMemexportFastBox, "Fast MemExport", 430, 72);
- ConfigureCheck(clearMemoryPageStateBox, "Memory Page State", 615, 72);
-
- compatibilityPanel.Controls.Add(readbackMemexportBox);
- compatibilityPanel.Controls.Add(readbackMemexportFastBox);
- compatibilityPanel.Controls.Add(clearMemoryPageStateBox);
-
- ConfigureCheck(occlusionQueryBox, "Occlusion Queries", 260, 112);
- ConfigureCheck(asyncShadersBox, "Async Shaders", 430, 112);
-
- compatibilityPanel.Controls.Add(occlusionQueryBox);
- compatibilityPanel.Controls.Add(asyncShadersBox);
-
- var hint = new Label
- {
- Text = "Readback Resolve is fixed to Full for FIFA Street compatibility.",
- ForeColor = TextSecondary,
- Font = new Font("Segoe UI", 8.5F),
- AutoSize = true,
- Location = new Point(22, 151)
- };
- compatibilityPanel.Controls.Add(hint);
- }
-
- private void WireEvents()
- {
- advancedButton.Click += (_, _) => ToggleAdvanced();
- advancedChevron.Click += (_, _) => ToggleAdvanced();
- compatibilityButton.Click += (_, _) => ToggleCompatibility();
-
- monitorBox.SelectedIndexChanged += (_, _) =>
- {
- DetectDisplayModes();
- UpdateSummary();
- };
-
- graphicsApiBox.SelectedIndexChanged += (_, _) =>
- {
- UpdateGraphicsApiState();
- UpdateSummary();
- };
-
- resolutionBox.SelectedIndexChanged += (_, _) => UpdateSummary();
-internalResolutionBox.SelectedIndexChanged += (_, _) => UpdateSummary();
-refreshBox.SelectedIndexChanged += (_, _) => UpdateSummary();
-gpuBox.SelectedIndexChanged += (_, _) => UpdateSummary();
-
-gpuBox.DropDown += (_, _) =>
-{
- int width = gpuBox.Width;
-
- using Graphics graphics = gpuBox.CreateGraphics();
-
- foreach (var item in gpuBox.Items)
- {
- int itemWidth = (int)Math.Ceiling(
- graphics.MeasureString(
- item?.ToString() ?? string.Empty,
- gpuBox.Font).Width);
-
- width = Math.Max(width, itemWidth + 40);
- }
-
- gpuBox.DropDownWidth = Math.Min(width, 500);
-};
-displayModeBox.SelectedIndexChanged += (_, _) => UpdateSummary();
- }
-
- private void ToggleAdvanced()
- {
- if (compatibilityVisible)
- {
- compatibilityVisible = false;
- compatibilityPanel.Visible = false;
- }
-
- advancedVisible = !advancedVisible;
- advancedPanel.Visible = advancedVisible;
- advancedChevron.Text = advancedVisible ? "⌃" : "⌄";
-
- if (advancedVisible)
- {
- ClientSize = new Size(1250, 846);
- advancedPanel.Location = new Point(350, 575);
- MoveBottomControls(721, 703, 808);
- }
- else
- {
- ClientSize = new Size(1250, 720);
- MoveBottomControls(590, 575, 674);
- }
- }
-
- private void ToggleCompatibility()
- {
- if (advancedVisible)
- {
- advancedVisible = false;
- advancedPanel.Visible = false;
- advancedChevron.Text = "⌄";
- }
-
- compatibilityVisible = !compatibilityVisible;
- compatibilityPanel.Visible = compatibilityVisible;
-
- if (compatibilityVisible)
- {
- ClientSize = new Size(1250, 902);
- compatibilityPanel.Location = new Point(350, 575);
- MoveBottomControls(777, 759, 864);
- }
- else
- {
- ClientSize = new Size(1250, 720);
- MoveBottomControls(590, 575, 674);
- }
- }
-
- private void MoveBottomControls(int secondaryY, int playY, int footerY)
- {
- foreach (Control control in Controls)
- {
- if (control is ModernButton button)
- {
- if (button.Text == "OPEN LOGS" || button.Text == "OPEN FOLDER")
- button.Top = secondaryY;
- else if (button.Text == "PLAY")
- button.Top = playY;
- }
- else if (control is Label label &&
- (label.Text.StartsWith("FIFA Street •", StringComparison.Ordinal) || label.Tag as string == "credit"))
- {
- label.Top = footerY;
- }
- }
- }
-
- private RoundedPanel CreateCard(Point location, Size size)
- {
- return new RoundedPanel
- {
- Location = location,
- Size = size,
- FillColor = Surface,
- BorderColor = Border,
- Radius = 16
- };
- }
-
- private void AddSectionHeader(Control parent, string title, string subtitle, int x, int y)
- {
- var titleLabel = new Label
- {
- Text = title,
- ForeColor = TextPrimary,
- Font = new Font("Segoe UI Semibold", 11F, FontStyle.Bold),
- AutoSize = true,
- Location = new Point(x, y)
- };
- parent.Controls.Add(titleLabel);
-
- var subtitleLabel = new Label
- {
- Text = subtitle,
- ForeColor = TextSecondary,
- Font = new Font("Segoe UI", 8.8F),
- AutoSize = true,
- Location = new Point(x, y + 26)
- };
- parent.Controls.Add(subtitleLabel);
- }
-
- private void AddFieldLabel(Control parent, string text, int x, int y)
- {
- var label = new Label
- {
- Text = text,
- ForeColor = TextSecondary,
- Font = new Font("Segoe UI Semibold", 8.7F),
- AutoSize = true,
- Location = new Point(x, y)
- };
- parent.Controls.Add(label);
- }
-
- private void ConfigureCombo(ComboBox box, int x, int y, int width)
- {
- box.Location = new Point(x, y);
- box.Size = new Size(width, 30);
- box.DropDownStyle = ComboBoxStyle.DropDownList;
- box.FlatStyle = FlatStyle.Flat;
- box.BackColor = SurfaceAlt;
- box.ForeColor = TextPrimary;
- box.Font = new Font("Segoe UI", 9.7F);
- box.DrawMode = DrawMode.OwnerDrawFixed;
- box.ItemHeight = 22;
- box.DrawItem += (_, e) =>
- {
- using var background = new SolidBrush(SurfaceAlt);
- e.Graphics.FillRectangle(background, e.Bounds);
- string text = e.Index >= 0 ? box.Items[e.Index]?.ToString() ?? "" : box.Text;
- TextRenderer.DrawText(e.Graphics, text, box.Font, e.Bounds, TextPrimary,
- TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);
- e.DrawFocusRectangle();
- };
- box.IntegralHeight = false;
- box.DropDownHeight = 240;
- }
-
- private void ConfigureCheck(CheckBox box, string text, int x, int y)
- {
- box.Text = text;
- box.Location = new Point(x, y);
- box.AutoSize = true;
- box.ForeColor = TextPrimary;
- box.BackColor = Color.Transparent;
- box.Font = new Font("Segoe UI Semibold", 9.2F);
- box.Cursor = Cursors.Hand;
- }
-
- private void StyleTextBox(TextBox box)
- {
- box.BackColor = SurfaceAlt;
- box.ForeColor = TextPrimary;
- box.BorderStyle = BorderStyle.FixedSingle;
- box.Font = new Font("Segoe UI", 9F);
- }
-
- private void LoadDefaults()
- {
- exePathBox.Text =
- Path.Combine(AppContext.BaseDirectory, "Game", "fifastreet.exe");
-
- gamePathBox.Text =
- Path.Combine(AppContext.BaseDirectory, "GameData");
-
- displayModeBox.Items.AddRange(new object[]
- {
- "Fullscreen",
- "Windowed"
- });
- displayModeBox.SelectedIndex = 0;
-
- graphicsApiBox.Items.AddRange(new object[]
- {
- "Direct3D 12",
- "Vulkan"
- });
+ AddFieldLabel(displayCard, "Game language", 216, 218);
+ ConfigureCombo(gameLanguageBox, 216, 242, 180);
+ gameLanguageBox.AccessibleName = "Game language";
+ displayCard.Controls.Add(gameLanguageBox);
+
+ ConfigureCheck(vsyncBox, "VSync", 24, 300);
+ vsyncBox.CheckedChanged += (_, _) => UpdateGraphicsApiState();
+ readbackMemexportBox.CheckedChanged += (_, _) => UpdateGraphicsApiState();
+ ConfigureCheck(vrrBox, "VRR / Tearing", 216, 300);
+ displayCard.Controls.Add(vsyncBox);
+ displayCard.Controls.Add(vrrBox);
+
+ var graphicsCard = CreateCard(new Point(480, 145), new Size(420, 360));
+ Controls.Add(graphicsCard);
+
+ AddSectionHeader(graphicsCard, "GRAPHICS", "Quality and presentation", 24, 20);
+
+ AddFieldLabel(graphicsCard, "Graphics API", 24, 82);
+ ConfigureCombo(graphicsApiBox, 24, 106, 120);
+ graphicsCard.Controls.Add(graphicsApiBox);
+
+ AddFieldLabel(graphicsCard, "GPU", 156, 82);
+ ConfigureCombo(gpuBox, 156, 106, 240);
+ graphicsCard.Controls.Add(gpuBox);
+
+AddFieldLabel(graphicsCard, "Post-processing", 24, 150);
+ConfigureCombo(postEffectBox, 24, 174, 372);
+graphicsCard.Controls.Add(postEffectBox);
+
+AddFieldLabel(graphicsCard, "Internal Resolution", 24, 218);
+ConfigureCombo(internalResolutionBox, 24, 242, 372);
+graphicsCard.Controls.Add(internalResolutionBox);
+
+ConfigureCheck(msaaBox, "Native 2x MSAA", 24, 300);
+graphicsCard.Controls.Add(msaaBox);
+
+var fpsTitle = new Label
+{
+ Text = "FPS",
+ ForeColor = TextPrimary,
+ Font = new Font("Segoe UI Semibold", 9F),
+ AutoSize = true,
+ Location = new Point(24, 330)
+};
+graphicsCard.Controls.Add(fpsTitle);
+
+var fpsInfo = new Label
+{
+ Text = "Game frame rate; Hz selects display refresh",
+ ForeColor = TextSecondary,
+ Font = new Font("Segoe UI", 8.7F),
+ AutoSize = true,
+ Location = new Point(67, 331)
+ };
+ graphicsCard.Controls.Add(fpsInfo);
+
+ advancedButton.Text = "ADVANCED SETTINGS";
+ advancedButton.Location = new Point(40, 525);
+ advancedButton.Size = new Size(205, 40);
+ advancedButton.FillColor = SurfaceAlt;
+ advancedButton.HoverColor = Color.FromArgb(34, 41, 50);
+ advancedButton.BorderColor = Border;
+ advancedButton.ForeColor = TextPrimary;
+ advancedButton.Font = new Font("Segoe UI Semibold", 9F);
+ advancedButton.Radius = 10;
+ Controls.Add(advancedButton);
+
+ advancedChevron.Text = "⌄";
+ advancedChevron.ForeColor = TextSecondary;
+ advancedChevron.Font = new Font("Segoe UI", 13F, FontStyle.Bold);
+ advancedChevron.AutoSize = true;
+ advancedChevron.Location = new Point(219, 533);
+ advancedChevron.BackColor = Color.Transparent;
+ advancedChevron.Cursor = Cursors.Hand;
+ Controls.Add(advancedChevron);
+
+ compatibilityButton.Text = "COMPATIBILITY";
+ compatibilityButton.Location = new Point(255, 525);
+ compatibilityButton.Size = new Size(205, 40);
+ compatibilityButton.FillColor = SurfaceAlt;
+ compatibilityButton.HoverColor = Color.FromArgb(34, 41, 50);
+ compatibilityButton.BorderColor = Border;
+ compatibilityButton.ForeColor = TextPrimary;
+ compatibilityButton.Font = new Font("Segoe UI Semibold", 9F);
+ compatibilityButton.Radius = 10;
+ Controls.Add(compatibilityButton);
+
+ ConfigureAdvancedPanel();
+ Controls.Add(advancedPanel);
+
+ ConfigureCompatibilityPanel();
+ Controls.Add(compatibilityPanel);
+
+ var logsButton = new ModernButton
+ {
+ Text = "OPEN LOGS",
+ Location = new Point(40, 590),
+ Size = new Size(150, 42),
+ FillColor = SurfaceAlt,
+ HoverColor = Color.FromArgb(34, 41, 50),
+ BorderColor = Border,
+ ForeColor = TextPrimary,
+ Font = new Font("Segoe UI Semibold", 9F),
+ Radius = 10
+ };
+ logsButton.Click += (_, _) => OpenLogs();
+ Controls.Add(logsButton);
+
+ var folderButton = new ModernButton
+ {
+ Text = "OPEN FOLDER",
+ Location = new Point(750, 590),
+ Size = new Size(150, 42),
+ FillColor = SurfaceAlt,
+ HoverColor = Color.FromArgb(34, 41, 50),
+ BorderColor = Border,
+ ForeColor = TextPrimary,
+ Font = new Font("Segoe UI Semibold", 9F),
+ Radius = 10
+ };
+ folderButton.Click += (_, _) => OpenGameFolder();
+ Controls.Add(folderButton);
+
+ var playButton = new ModernButton
+ {
+ Text = "PLAY",
+ Location = new Point(280, 575),
+ Size = new Size(380, 72),
+ FillColor = Accent,
+ HoverColor = AccentHover,
+ BorderColor = Accent,
+ ForeColor = Color.FromArgb(9, 14, 8),
+ Font = new Font("Segoe UI", 18F, FontStyle.Bold),
+ Radius = 14
+ };
+ playButton.Click += (_, _) => LaunchGame();
+ Controls.Add(playButton);
+
+ var footer = new Label
+ {
+ Text = "FIFA Street • Native PC Recomp Launcher",
+ ForeColor = Color.FromArgb(92, 102, 116),
+ Font = new Font("Segoe UI", 8.5F),
+ AutoSize = true,
+ Location = new Point(40, 674)
+ };
+ Controls.Add(footer);
+
+ foreach (Control control in Controls) control.Left += 310;
+ using var resource = typeof(LauncherForm).Assembly.GetManifestResourceStream("cover.jpg")!;
+ using var cover = Image.FromStream(resource);
+ var artwork = new MessiPicture
+ {
+ Image = new Bitmap(cover), Bounds = new Rectangle(0, 0, 310, ClientSize.Height),
+ Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left
+ };
+ Controls.Add(artwork);
+ FormClosed += (_, _) => artwork.Image?.Dispose();
+ var credit = new Label
+ {
+ Text = "PORTED BY: SAMUELITODAVILA\nContributions: Emran_Ahm3d", AutoSize = true,
+ ForeColor = Accent, Font = new Font("Segoe UI", 8.5F),
+ Location = new Point(730, 674), Tag = "credit"
+ };
+ Controls.Add(credit);
+
+ ResumeLayout(false);
+ PerformLayout();
+ }
+
+ private void ConfigureAdvancedPanel()
+ {
+ advancedPanel.Location = new Point(40, 575);
+ advancedPanel.Size = new Size(860, 126);
+ advancedPanel.FillColor = Surface;
+ advancedPanel.BorderColor = Border;
+ advancedPanel.Radius = 14;
+ advancedPanel.Visible = false;
+
+ AddFieldLabel(advancedPanel, "Game executable", 22, 18);
+ exePathBox.Location = new Point(22, 42);
+ exePathBox.Size = new Size(688, 27);
+ StyleTextBox(exePathBox);
+ advancedPanel.Controls.Add(exePathBox);
+
+ var browseExe = new ModernButton
+ {
+ Text = "BROWSE",
+ Location = new Point(724, 39),
+ Size = new Size(112, 34),
+ FillColor = SurfaceAlt,
+ HoverColor = Color.FromArgb(34, 41, 50),
+ BorderColor = Border,
+ ForeColor = TextPrimary,
+ Font = new Font("Segoe UI Semibold", 8.5F),
+ Radius = 8
+ };
+ browseExe.Click += (_, _) => BrowseExe();
+ advancedPanel.Controls.Add(browseExe);
+
+ AddFieldLabel(advancedPanel, "Game data folder", 22, 76);
+ gamePathBox.Location = new Point(22, 98);
+ gamePathBox.Size = new Size(688, 27);
+ StyleTextBox(gamePathBox);
+ advancedPanel.Controls.Add(gamePathBox);
+
+ var browseGame = new ModernButton
+ {
+ Text = "BROWSE",
+ Location = new Point(724, 95),
+ Size = new Size(112, 34),
+ FillColor = SurfaceAlt,
+ HoverColor = Color.FromArgb(34, 41, 50),
+ BorderColor = Border,
+ ForeColor = TextPrimary,
+ Font = new Font("Segoe UI Semibold", 8.5F),
+ Radius = 8
+ };
+ browseGame.Click += (_, _) => BrowseGame();
+ advancedPanel.Controls.Add(browseGame);
+ }
+
+ private void ConfigureCompatibilityPanel()
+ {
+ compatibilityPanel.Location = new Point(40, 575);
+ compatibilityPanel.Size = new Size(860, 182);
+ compatibilityPanel.FillColor = Surface;
+ compatibilityPanel.BorderColor = Border;
+ compatibilityPanel.Radius = 14;
+ compatibilityPanel.Visible = false;
+
+ AddSectionHeader(
+ compatibilityPanel,
+ "COMPATIBILITY",
+ "Renderer options for textures, lighting, black screens and stutter",
+ 22,
+ 15
+ );
+
+ ConfigureCheck(readbackMemexportBox, "Memory Export", 260, 72);
+ ConfigureCheck(readbackMemexportFastBox, "Fast MemExport", 430, 72);
+ ConfigureCheck(clearMemoryPageStateBox, "Memory Page State", 615, 72);
+
+ compatibilityPanel.Controls.Add(readbackMemexportBox);
+ compatibilityPanel.Controls.Add(readbackMemexportFastBox);
+ compatibilityPanel.Controls.Add(clearMemoryPageStateBox);
+
+ ConfigureCheck(occlusionQueryBox, "Occlusion Queries", 260, 112);
+ ConfigureCheck(asyncShadersBox, "Async Shaders", 430, 112);
+
+ compatibilityPanel.Controls.Add(occlusionQueryBox);
+ compatibilityPanel.Controls.Add(asyncShadersBox);
+
+ var hint = new Label
+ {
+ Text = "Readback Resolve is fixed to Full for FIFA Street compatibility.",
+ ForeColor = TextSecondary,
+ Font = new Font("Segoe UI", 8.5F),
+ AutoSize = true,
+ Location = new Point(22, 151)
+ };
+ compatibilityPanel.Controls.Add(hint);
+ }
+
+ private void WireEvents()
+ {
+ advancedButton.Click += (_, _) => ToggleAdvanced();
+ advancedChevron.Click += (_, _) => ToggleAdvanced();
+ compatibilityButton.Click += (_, _) => ToggleCompatibility();
+
+ monitorBox.SelectedIndexChanged += (_, _) =>
+ {
+ DetectDisplayModes();
+ UpdateSummary();
+ };
+
+ graphicsApiBox.SelectedIndexChanged += (_, _) =>
+ {
+ UpdateGraphicsApiState();
+ UpdateSummary();
+ };
+
+ resolutionBox.SelectedIndexChanged += (_, _) => { UpdateRefreshRates(); UpdateSummary(); };
+internalResolutionBox.SelectedIndexChanged += (_, _) => UpdateSummary();
+refreshBox.SelectedIndexChanged += (_, _) => UpdateSummary();
+gpuBox.SelectedIndexChanged += (_, _) => UpdateSummary();
+
+gpuBox.DropDown += (_, _) =>
+{
+ int width = gpuBox.Width;
+
+ using Graphics graphics = gpuBox.CreateGraphics();
+
+ foreach (var item in gpuBox.Items)
+ {
+ int itemWidth = (int)Math.Ceiling(
+ graphics.MeasureString(
+ item?.ToString() ?? string.Empty,
+ gpuBox.Font).Width);
+
+ width = Math.Max(width, itemWidth + 40);
+ }
+
+ gpuBox.DropDownWidth = Math.Min(width, 500);
+};
+displayModeBox.SelectedIndexChanged += (_, _) => { UpdateRefreshRates(); UpdateSummary(); };
+ }
+
+ private void ToggleAdvanced()
+ {
+ if (compatibilityVisible)
+ {
+ compatibilityVisible = false;
+ compatibilityPanel.Visible = false;
+ }
+
+ advancedVisible = !advancedVisible;
+ advancedPanel.Visible = advancedVisible;
+ advancedChevron.Text = advancedVisible ? "⌃" : "⌄";
+
+ if (advancedVisible)
+ {
+ ClientSize = new Size(1250, 846);
+ advancedPanel.Location = new Point(350, 575);
+ MoveBottomControls(721, 703, 808);
+ }
+ else
+ {
+ ClientSize = new Size(1250, 720);
+ MoveBottomControls(590, 575, 674);
+ }
+ }
+
+ private void ToggleCompatibility()
+ {
+ if (advancedVisible)
+ {
+ advancedVisible = false;
+ advancedPanel.Visible = false;
+ advancedChevron.Text = "⌄";
+ }
+
+ compatibilityVisible = !compatibilityVisible;
+ compatibilityPanel.Visible = compatibilityVisible;
+
+ if (compatibilityVisible)
+ {
+ ClientSize = new Size(1250, 902);
+ compatibilityPanel.Location = new Point(350, 575);
+ MoveBottomControls(777, 759, 864);
+ }
+ else
+ {
+ ClientSize = new Size(1250, 720);
+ MoveBottomControls(590, 575, 674);
+ }
+ }
+
+ private void MoveBottomControls(int secondaryY, int playY, int footerY)
+ {
+ foreach (Control control in Controls)
+ {
+ if (control is ModernButton button)
+ {
+ if (button.Text == "OPEN LOGS" || button.Text == "OPEN FOLDER")
+ button.Top = secondaryY;
+ else if (button.Text == "PLAY")
+ button.Top = playY;
+ }
+ else if (control is Label label &&
+ (label.Text.StartsWith("FIFA Street •", StringComparison.Ordinal) || label.Tag as string == "credit"))
+ {
+ label.Top = footerY;
+ }
+ }
+ }
+
+ private RoundedPanel CreateCard(Point location, Size size)
+ {
+ return new RoundedPanel
+ {
+ Location = location,
+ Size = size,
+ FillColor = Surface,
+ BorderColor = Border,
+ Radius = 16
+ };
+ }
+
+ private void AddSectionHeader(Control parent, string title, string subtitle, int x, int y)
+ {
+ var titleLabel = new Label
+ {
+ Text = title,
+ ForeColor = TextPrimary,
+ Font = new Font("Segoe UI Semibold", 11F, FontStyle.Bold),
+ AutoSize = true,
+ Location = new Point(x, y)
+ };
+ parent.Controls.Add(titleLabel);
+
+ var subtitleLabel = new Label
+ {
+ Text = subtitle,
+ ForeColor = TextSecondary,
+ Font = new Font("Segoe UI", 8.8F),
+ AutoSize = true,
+ Location = new Point(x, y + 26)
+ };
+ parent.Controls.Add(subtitleLabel);
+ }
+
+ private void AddFieldLabel(Control parent, string text, int x, int y)
+ {
+ var label = new Label
+ {
+ Text = text,
+ ForeColor = TextSecondary,
+ Font = new Font("Segoe UI Semibold", 8.7F),
+ AutoSize = true,
+ Location = new Point(x, y)
+ };
+ parent.Controls.Add(label);
+ }
+
+ private void ConfigureCombo(ComboBox box, int x, int y, int width)
+ {
+ box.Location = new Point(x, y);
+ box.Size = new Size(width, 30);
+ box.DropDownStyle = ComboBoxStyle.DropDownList;
+ box.FlatStyle = FlatStyle.Flat;
+ box.BackColor = SurfaceAlt;
+ box.ForeColor = TextPrimary;
+ box.Font = new Font("Segoe UI", 9.7F);
+ box.DrawMode = DrawMode.OwnerDrawFixed;
+ box.ItemHeight = 22;
+ box.DrawItem += (_, e) =>
+ {
+ using var background = new SolidBrush(SurfaceAlt);
+ e.Graphics.FillRectangle(background, e.Bounds);
+ string text = e.Index >= 0 ? box.Items[e.Index]?.ToString() ?? "" : box.Text;
+ TextRenderer.DrawText(e.Graphics, text, box.Font, e.Bounds, TextPrimary,
+ TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);
+ e.DrawFocusRectangle();
+ };
+ box.IntegralHeight = false;
+ box.DropDownHeight = 240;
+ }
+
+ private void ConfigureCheck(CheckBox box, string text, int x, int y)
+ {
+ box.Text = text;
+ box.Location = new Point(x, y);
+ box.AutoSize = true;
+ box.ForeColor = TextPrimary;
+ box.BackColor = Color.Transparent;
+ box.Font = new Font("Segoe UI Semibold", 9.2F);
+ box.Cursor = Cursors.Hand;
+ }
+
+ private void StyleTextBox(TextBox box)
+ {
+ box.BackColor = SurfaceAlt;
+ box.ForeColor = TextPrimary;
+ box.BorderStyle = BorderStyle.FixedSingle;
+ box.Font = new Font("Segoe UI", 9F);
+ }
+
+ private void LoadDefaults()
+ {
+ exePathBox.Text =
+ Path.Combine(AppContext.BaseDirectory, "Game", "fifastreet.exe");
+
+ gamePathBox.Text =
+ Path.Combine(AppContext.BaseDirectory, "GameData");
+
+ displayModeBox.Items.AddRange(new object[]
+ {
+ "Fullscreen",
+ "Windowed"
+ });
+ displayModeBox.SelectedIndex = 0;
+
+ graphicsApiBox.Items.AddRange(new object[]
+ {
+ "Direct3D 12",
+ "Vulkan"
+ });
graphicsApiBox.SelectedIndex = 0;
-
- monitorBox.Items.Clear();
- foreach (var screen in Screen.AllScreens)
- {
- string primary = screen.Primary ? " • Primary" : "";
- monitorBox.Items.Add(
- $"{monitorBox.Items.Count}: {screen.DeviceName}{primary}"
- );
- }
-
- if (monitorBox.Items.Count > 0)
- monitorBox.SelectedIndex = 0;
-
- DetectDisplayModes();
- DetectGpus();
-
- postEffectBox.Items.AddRange(new object[]
-{
- "None",
- "FXAA",
- "FXAA Extreme"
-});
- postEffectBox.SelectedIndex = 0;
-
- internalResolutionBox.Items.AddRange(new object[]
-{
- "1x - Native (1280 x 720)",
- "2x - 2560 x 1440",
- "3x - 3840 x 2160",
- "4x - 5120 x 2880"
-});
- internalResolutionBox.SelectedIndex = 0;
-
-
- readbackMemexportBox.Checked = true;
- readbackMemexportFastBox.Checked = true;
- clearMemoryPageStateBox.Checked = false;
- occlusionQueryBox.Checked = true;
- asyncShadersBox.Checked = false;
-
+ gameLanguageBox.Items.AddRange(new object[] { "English", "Español", "Français", "Deutsch", "Italiano" });
+ gameLanguageBox.SelectedIndex = 0;
+
+ monitorBox.Items.Clear();
+ foreach (var screen in Screen.AllScreens)
+ {
+ string primary = screen.Primary ? " • Primary" : "";
+ monitorBox.Items.Add(
+ $"{monitorBox.Items.Count}: {screen.DeviceName}{primary}"
+ );
+ }
+
+ if (monitorBox.Items.Count > 0)
+ monitorBox.SelectedIndex = Math.Max(0, Array.FindIndex(Screen.AllScreens, screen => screen.Primary));
+
+ DetectDisplayModes();
+ DetectGpus();
+
+ postEffectBox.Items.AddRange(new object[]
+{
+ "None",
+ "FXAA",
+ "FXAA Extreme"
+});
+ postEffectBox.SelectedIndex = 2;
+
+ internalResolutionBox.Items.AddRange(new object[]
+{
+ "1x - Native (1280 x 720)",
+ "2x - 2560 x 1440",
+ "3x - 3840 x 2160",
+ "4x - 5120 x 2880"
+});
+ internalResolutionBox.SelectedIndex = 1;
+
+
+ readbackMemexportBox.Checked = true;
+ readbackMemexportFastBox.Checked = true;
+ clearMemoryPageStateBox.Checked = true;
+ occlusionQueryBox.Checked = true;
+ asyncShadersBox.Checked = true;
+
vsyncBox.Checked = false;
- vrrBox.Checked = false;
- msaaBox.Checked = false;
- }
-
- private void DetectGpus()
- {
- gpuBox.Items.Clear();
- gpuAdapterIndices.Clear();
- gpuBox.Items.Add("Automatic");
- gpuAdapterIndices.Add(-1);
-
- try
- {
- foreach (var gpu in DxgiAdapters.Enumerate())
- {
- gpuBox.Items.Add(
- $"Adapter {gpu.Index}: {gpu.Name}"
- );
- gpuAdapterIndices.Add(checked((int)gpu.Index));
- }
- }
- catch
- {
- // Automatic selection remains available when DXGI enumeration fails.
- }
-
- gpuBox.Items.Add("WARP (Software)");
- gpuAdapterIndices.Add(-2);
- gpuBox.SelectedIndex = 0;
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
- private struct DEVMODE
- {
- private const int CCHDEVICENAME = 32;
- private const int CCHFORMNAME = 32;
-
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHDEVICENAME)]
- public string dmDeviceName;
-
- public short dmSpecVersion;
- public short dmDriverVersion;
- public short dmSize;
- public short dmDriverExtra;
- public int dmFields;
-
- public int dmPositionX;
- public int dmPositionY;
- public int dmDisplayOrientation;
- public int dmDisplayFixedOutput;
-
- public short dmColor;
- public short dmDuplex;
- public short dmYResolution;
- public short dmTTOption;
- public short dmCollate;
-
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHFORMNAME)]
- public string dmFormName;
-
- public short dmLogPixels;
- public int dmBitsPerPel;
- public int dmPelsWidth;
- public int dmPelsHeight;
- public int dmDisplayFlags;
- public int dmDisplayFrequency;
-
- public int dmICMMethod;
- public int dmICMIntent;
- public int dmMediaType;
- public int dmDitherType;
- public int dmReserved1;
- public int dmReserved2;
- public int dmPanningWidth;
- public int dmPanningHeight;
- }
-
- [DllImport("user32.dll", CharSet = CharSet.Ansi)]
- private static extern bool EnumDisplaySettings(
- string deviceName,
- int modeNum,
- ref DEVMODE devMode
- );
-
- private const int ENUM_CURRENT_SETTINGS = -1;
-
- private void DetectDisplayModes()
- {
- string? oldResolution = resolutionBox.SelectedItem?.ToString();
- string? oldRefresh = refreshBox.SelectedItem?.ToString();
-
- resolutionBox.Items.Clear();
- refreshBox.Items.Clear();
-
- var resolutions = new HashSet<string>();
- var refreshRates = new SortedSet<int>();
-
- Screen screen =
- monitorBox.SelectedIndex >= 0 &&
- monitorBox.SelectedIndex < Screen.AllScreens.Length
- ? Screen.AllScreens[monitorBox.SelectedIndex]
- : Screen.PrimaryScreen!;
-
- int modeNum = 0;
-
- while (true)
- {
- DEVMODE mode = CreateDevMode();
-
- if (!EnumDisplaySettings(
- screen.DeviceName,
- modeNum,
- ref mode))
- {
- break;
- }
-
- if (mode.dmPelsWidth >= 1280 &&
- mode.dmPelsHeight >= 720 &&
- mode.dmBitsPerPel >= 32)
- {
- resolutions.Add(
- $"{mode.dmPelsWidth}x{mode.dmPelsHeight}"
- );
-
- if (mode.dmDisplayFrequency > 20 &&
- mode.dmDisplayFrequency < 1000)
- {
- refreshRates.Add(mode.dmDisplayFrequency);
- }
- }
-
- modeNum++;
- }
-
- // Always expose common output resolutions up to 4K,
- // even when the current monitor does not advertise them.
- resolutions.Add("1280x720");
- resolutions.Add("1920x1080");
- resolutions.Add("2560x1440");
- resolutions.Add("3200x1800");
- resolutions.Add("3840x2160");
-
- foreach (string resolution in resolutions
- .OrderBy(x =>
- {
- var p = x.Split('x');
- return int.Parse(p[0]) * int.Parse(p[1]);
- }))
- {
- resolutionBox.Items.Add(resolution);
- }
-
- foreach (int hz in refreshRates)
- {
- refreshBox.Items.Add(hz.ToString());
- }
-
- if (resolutionBox.Items.Count == 0)
- {
- resolutionBox.Items.AddRange(new object[]
- {
- "1280x720",
- "1600x900",
- "1920x1080",
- "2560x1440",
- "3200x1800",
- "3840x2160"
- });
- }
-
- if (refreshBox.Items.Count == 0)
- {
- refreshBox.Items.AddRange(new object[]
- {
- "30", "50", "60", "75", "100",
- "120", "144", "165", "180", "200", "240"
- });
- }
-
- if (!string.IsNullOrWhiteSpace(oldResolution) &&
- resolutionBox.Items.Contains(oldResolution))
- {
- resolutionBox.SelectedItem = oldResolution;
- }
- else
- {
- string currentResolution =
- $"{screen.Bounds.Width}x{screen.Bounds.Height}";
-
- if (resolutionBox.Items.Contains(currentResolution))
- resolutionBox.SelectedItem = currentResolution;
- else if (resolutionBox.Items.Count > 0)
- resolutionBox.SelectedIndex = resolutionBox.Items.Count - 1;
- }
-
- if (!string.IsNullOrWhiteSpace(oldRefresh) &&
- refreshBox.Items.Contains(oldRefresh))
- {
- refreshBox.SelectedItem = oldRefresh;
- }
- else
- {
- DEVMODE currentMode = CreateDevMode();
-
- if (EnumDisplaySettings(
- screen.DeviceName,
- ENUM_CURRENT_SETTINGS,
- ref currentMode))
- {
- string currentHz =
- currentMode.dmDisplayFrequency.ToString();
-
- if (refreshBox.Items.Contains(currentHz))
- refreshBox.SelectedItem = currentHz;
- }
-
- if (refreshBox.SelectedIndex < 0 &&
- refreshBox.Items.Count > 0)
- {
- refreshBox.SelectedIndex = 0;
- }
- }
- }
-
- private static DEVMODE CreateDevMode()
- {
- return new DEVMODE
- {
- dmDeviceName = new string('\0', 32),
- dmFormName = new string('\0', 32),
- dmSize = (short)Marshal.SizeOf<DEVMODE>()
- };
- }
-
- private void UpdateGraphicsApiState()
- {
- bool isD3D12 = graphicsApiBox.SelectedIndex != 1;
-
- // GPU adapter selection is currently specific to the D3D12 backend.
- // Vulkan uses automatic device selection (REX_VULKAN_DEVICE=-1).
- gpuBox.Enabled = isD3D12;
-
- if (!isD3D12)
- {
- gpuBox.BackColor = Color.FromArgb(34, 38, 43);
- }
- else
- {
- gpuBox.BackColor = Color.FromArgb(24, 28, 32);
- }
- }
- private void UpdateSummary()
- {
- string gpu;
-
- if (graphicsApiBox.SelectedIndex == 1)
- {
- gpu = "Automatic GPU (Vulkan)";
- }
- else
- {
- gpu = gpuBox.SelectedItem?.ToString() ?? "Automatic GPU";
-
- if (gpu.StartsWith("Adapter ", StringComparison.Ordinal))
- {
- int colon = gpu.IndexOf(':');
- if (colon >= 0 && colon + 1 < gpu.Length)
- gpu = gpu[(colon + 1)..].Trim();
- }
- }
-
- string resolution = resolutionBox.SelectedItem?.ToString() ?? "Resolution";
- string hz = refreshBox.SelectedItem?.ToString() ?? "--";
-
- hardwareLabel.Text =
- $"{gpu} • {resolution} • {hz} Hz";
- }
-
- private void UpdateStatus(string text, bool ok)
- {
- statusLabel.Text = text;
- statusLabel.ForeColor = ok ? TextSecondary : Color.FromArgb(255, 120, 120);
- }
-
- private void LaunchGame()
- {
- try
- {
- string exe = exePathBox.Text.Trim();
- string gameRoot = gamePathBox.Text.Trim();
-
- if (!File.Exists(exe))
- {
- ShowError("fifastreet.exe was not found.");
- return;
- }
-
- if (!Directory.Exists(gameRoot))
- {
- ShowError("The game data folder does not exist.");
- return;
- }
-
- if (!File.Exists(Path.Combine(gameRoot, "default.xex")))
- {
- MessageBox.Show(
- "The selected folder does not contain default.xex.",
- "Invalid folder",
- MessageBoxButtons.OK,
- MessageBoxIcon.Warning
- );
- return;
- }
-
- // Select the validated ReXGlue graphics backend.
- string graphicsApi = graphicsApiBox.SelectedIndex == 1
- ? "Vulkan"
- : "D3D12";
-
- string backendDirectory = Path.Combine(
- Path.GetDirectoryName(exe)!,
- "Backends",
- graphicsApi);
-
- string backendRuntime = Path.Combine(
- backendDirectory,
- "rexruntime.dll");
-
- string backendGpu = Path.Combine(
- backendDirectory,
- "rexgpu-xenos.dll");
-
- if (!File.Exists(backendRuntime) || !File.Exists(backendGpu))
- {
- MessageBox.Show(
- $"The {graphicsApi} graphics backend is missing.\n\n" +
- $"Expected files in:\n{backendDirectory}",
- "FIFA Street Launcher",
- MessageBoxButtons.OK,
- MessageBoxIcon.Error);
- return;
- }
-
- string executableDirectory = Path.GetDirectoryName(exe)!;
-
- File.Copy(
- backendRuntime,
- Path.Combine(executableDirectory, "rexruntime.dll"),
- true);
-
- File.Copy(
- backendGpu,
- Path.Combine(executableDirectory, "rexgpu-xenos.dll"),
- true);
-
- if (string.IsNullOrWhiteSpace(resolutionBox.Text) ||
- !resolutionBox.Text.Contains('x'))
- {
- ShowError("Select a valid resolution.");
- return;
- }
-
- var resolution = resolutionBox.Text.Split('x');
- int width = int.Parse(resolution[0]);
- int height = int.Parse(resolution[1]);
- string refresh = refreshBox.Text;
-
- bool fullscreen =
- displayModeBox.SelectedItem?.ToString() == "Fullscreen";
-
- int monitor = Math.Max(0, monitorBox.SelectedIndex);
-
- int adapter = gpuBox.SelectedIndex >= 0
- ? gpuAdapterIndices[gpuBox.SelectedIndex] : -1;
-
- string postEffect = postEffectBox.SelectedIndex switch
- {
- 1 => "fxaa",
- 2 => "fxaa_extreme",
- _ => "none"
- };
-
-
- string logsDir = Path.Combine(
- Path.GetDirectoryName(exe)!,
- "Logs"
- );
-
- Directory.CreateDirectory(logsDir);
-
- string logFile =
- Path.Combine(logsDir, "fifastreet.log");
-
- var startInfo = new ProcessStartInfo
- {
- FileName = exe,
- WorkingDirectory = Path.GetDirectoryName(exe)!,
- UseShellExecute = false
- };
-
- // ReXGlue aplica a configuração por esta ordem:
- // argumentos CLI -> ficheiro TOML -> variáveis de ambiente.
- // Portanto, usar REX_* aqui garante que as escolhas do launcher
- // têm prioridade sobre qualquer configuração guardada no jogo.
-
- startInfo.Environment["REX_GAME_DATA_ROOT"] = gameRoot;
- startInfo.Environment["REX_VIDEO_MODE_WIDTH"] = width.ToString();
- startInfo.Environment["REX_VIDEO_MODE_HEIGHT"] = height.ToString();
- // The display size does not change the Xbox 360 render targets.
- int internalResolutionScale = Math.Max(1, internalResolutionBox.SelectedIndex + 1);
-
-startInfo.Environment["REX_DRAW_RESOLUTION_SCALE_X"] =
- internalResolutionScale.ToString();
-
-startInfo.Environment["REX_DRAW_RESOLUTION_SCALE_Y"] =
- internalResolutionScale.ToString();
- startInfo.Environment["REX_WINDOW_WIDTH"] = width.ToString();
- startInfo.Environment["REX_WINDOW_HEIGHT"] = height.ToString();
+ vrrBox.Checked = true;
+ msaaBox.Checked = true;
+ }
+
+ private void DetectGpus()
+ {
+ gpuBox.Items.Clear();
+ gpuAdapterIndices.Clear();
+ gpuBox.Items.Add("Automatic");
+ gpuAdapterIndices.Add(-1);
+
+ try
+ {
+ foreach (var gpu in DxgiAdapters.Enumerate())
+ {
+ gpuBox.Items.Add(
+ $"Adapter {gpu.Index}: {gpu.Name}"
+ );
+ gpuAdapterIndices.Add(checked((int)gpu.Index));
+ }
+ }
+ catch
+ {
+ // Automatic selection remains available when DXGI enumeration fails.
+ }
+
+ gpuBox.Items.Add("WARP (Software)");
+ gpuAdapterIndices.Add(-2);
+ gpuBox.SelectedIndex = 0;
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
+ private struct DEVMODE
+ {
+ private const int CCHDEVICENAME = 32;
+ private const int CCHFORMNAME = 32;
+
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHDEVICENAME)]
+ public string dmDeviceName;
+
+ public short dmSpecVersion;
+ public short dmDriverVersion;
+ public short dmSize;
+ public short dmDriverExtra;
+ public int dmFields;
+
+ public int dmPositionX;
+ public int dmPositionY;
+ public int dmDisplayOrientation;
+ public int dmDisplayFixedOutput;
+
+ public short dmColor;
+ public short dmDuplex;
+ public short dmYResolution;
+ public short dmTTOption;
+ public short dmCollate;
+
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHFORMNAME)]
+ public string dmFormName;
+
+ public short dmLogPixels;
+ public int dmBitsPerPel;
+ public int dmPelsWidth;
+ public int dmPelsHeight;
+ public int dmDisplayFlags;
+ public int dmDisplayFrequency;
+
+ public int dmICMMethod;
+ public int dmICMIntent;
+ public int dmMediaType;
+ public int dmDitherType;
+ public int dmReserved1;
+ public int dmReserved2;
+ public int dmPanningWidth;
+ public int dmPanningHeight;
+ }
+
+ [DllImport("user32.dll", CharSet = CharSet.Ansi)]
+ private static extern bool EnumDisplaySettings(
+ string deviceName,
+ int modeNum,
+ ref DEVMODE devMode
+ );
+
+ private const int ENUM_CURRENT_SETTINGS = -1;
+
+ private void DetectDisplayModes()
+ {
+ string? oldResolution = resolutionBox.SelectedItem?.ToString();
+ string? oldRefresh = refreshBox.SelectedItem?.ToString();
+
+ resolutionBox.Items.Clear();
+ refreshBox.Items.Clear();
+
+ var resolutions = new HashSet<string>();
+ var refreshRates = new SortedSet<int>();
+
+ Screen screen =
+ monitorBox.SelectedIndex >= 0 &&
+ monitorBox.SelectedIndex < Screen.AllScreens.Length
+ ? Screen.AllScreens[monitorBox.SelectedIndex]
+ : Screen.PrimaryScreen!;
+
+ int modeNum = 0;
+
+ while (true)
+ {
+ DEVMODE mode = CreateDevMode();
+
+ if (!EnumDisplaySettings(
+ screen.DeviceName,
+ modeNum,
+ ref mode))
+ {
+ break;
+ }
+
+ if (mode.dmPelsWidth >= 1280 &&
+ mode.dmPelsHeight >= 720 &&
+ mode.dmBitsPerPel >= 32)
+ {
+ resolutions.Add(
+ $"{mode.dmPelsWidth}x{mode.dmPelsHeight}"
+ );
+
+ if (mode.dmDisplayFrequency > 20 &&
+ mode.dmDisplayFrequency < 1000)
+ {
+ refreshRates.Add(mode.dmDisplayFrequency);
+ }
+ }
+
+ modeNum++;
+ }
+
+ // Always expose common output resolutions up to 4K,
+ // even when the current monitor does not advertise them.
+ resolutions.Add("1280x720");
+ resolutions.Add("1920x1080");
+ resolutions.Add("2560x1440");
+ resolutions.Add("3200x1800");
+ resolutions.Add("3840x2160");
+
+ foreach (string resolution in resolutions
+ .OrderBy(x =>
+ {
+ var p = x.Split('x');
+ return int.Parse(p[0]) * int.Parse(p[1]);
+ }))
+ {
+ resolutionBox.Items.Add(resolution);
+ }
+
+ foreach (int hz in refreshRates)
+ {
+ refreshBox.Items.Add(hz.ToString());
+ }
+
+ if (resolutionBox.Items.Count == 0)
+ {
+ resolutionBox.Items.AddRange(new object[]
+ {
+ "1280x720",
+ "1600x900",
+ "1920x1080",
+ "2560x1440",
+ "3200x1800",
+ "3840x2160"
+ });
+ }
+
+ if (refreshBox.Items.Count == 0)
+ {
+ refreshBox.Items.AddRange(new object[]
+ {
+ "30", "50", "60", "75", "100",
+ "120", "144", "165", "180", "200", "240"
+ });
+ }
+
+ if (!string.IsNullOrWhiteSpace(oldResolution) &&
+ resolutionBox.Items.Contains(oldResolution))
+ {
+ resolutionBox.SelectedItem = oldResolution;
+ }
+ else
+ {
+ string currentResolution =
+ $"{screen.Bounds.Width}x{screen.Bounds.Height}";
+
+ if (resolutionBox.Items.Contains(currentResolution))
+ resolutionBox.SelectedItem = currentResolution;
+ else if (resolutionBox.Items.Count > 0)
+ resolutionBox.SelectedIndex = resolutionBox.Items.Count - 1;
+ }
+
+ if (!string.IsNullOrWhiteSpace(oldRefresh) &&
+ refreshBox.Items.Contains(oldRefresh))
+ {
+ refreshBox.SelectedItem = oldRefresh;
+ }
+ else
+ {
+ DEVMODE currentMode = CreateDevMode();
+
+ if (EnumDisplaySettings(
+ screen.DeviceName,
+ ENUM_CURRENT_SETTINGS,
+ ref currentMode))
+ {
+ string currentHz =
+ currentMode.dmDisplayFrequency.ToString();
+
+ if (refreshBox.Items.Contains(currentHz))
+ refreshBox.SelectedItem = currentHz;
+ }
+
+ if (refreshBox.SelectedIndex < 0 &&
+ refreshBox.Items.Count > 0)
+ {
+ refreshBox.SelectedIndex = 0;
+ }
+ }
+ }
+
+ private void UpdateRefreshRates()
+ {
+ if (monitorBox.SelectedIndex < 0 || resolutionBox.SelectedIndex < 0) return;
+ string previous = refreshBox.Text;
+ Screen screen = Screen.AllScreens[monitorBox.SelectedIndex];
+ DEVMODE desktop = CreateDevMode();
+ if (!EnumDisplaySettings(screen.DeviceName, ENUM_CURRENT_SETTINGS, ref desktop)) return;
+ string[] size = resolutionBox.Text.Split('x');
+ if (size.Length != 2 || !int.TryParse(size[0], out int width) ||
+ !int.TryParse(size[1], out int height)) return;
+ if (displayModeBox.SelectedIndex != 0) {
+ width = desktop.dmPelsWidth;
+ height = desktop.dmPelsHeight;
+ }
+ var rates = new SortedSet<int>();
+ for (int i = 0; ; i++) {
+ DEVMODE mode = CreateDevMode();
+ if (!EnumDisplaySettings(screen.DeviceName, i, ref mode)) break;
+ if (mode.dmPelsWidth == width && mode.dmPelsHeight == height &&
+ mode.dmBitsPerPel >= 32 && mode.dmDisplayFrequency > 20)
+ rates.Add(mode.dmDisplayFrequency);
+ }
+ refreshBox.Items.Clear();
+ foreach (int rate in rates) refreshBox.Items.Add(rate.ToString());
+ if (refreshBox.Items.Contains(previous)) refreshBox.SelectedItem = previous;
+ else if (refreshBox.Items.Contains(desktop.dmDisplayFrequency.ToString()))
+ refreshBox.SelectedItem = desktop.dmDisplayFrequency.ToString();
+ else if (refreshBox.Items.Count > 0) refreshBox.SelectedIndex = 0;
+ }
+
+ private static DEVMODE CreateDevMode()
+ {
+ return new DEVMODE
+ {
+ dmDeviceName = new string('\0', 32),
+ dmFormName = new string('\0', 32),
+ dmSize = (short)Marshal.SizeOf<DEVMODE>()
+ };
+ }
+
+ private void UpdateGraphicsApiState()
+ {
+ bool isD3D12 = graphicsApiBox.SelectedIndex != 1;
+
+ // GPU adapter selection is currently specific to the D3D12 backend.
+ // Vulkan uses automatic device selection (REX_VULKAN_DEVICE=-1).
+ gpuBox.Enabled = isD3D12;
+ vrrBox.Enabled = isD3D12 && !vsyncBox.Checked;
+ vrrBox.Text = "VRR / Tearing (D3D12)";
+ readbackMemexportFastBox.Enabled = readbackMemexportBox.Checked;
+
+ if (!isD3D12)
+ {
+ gpuBox.BackColor = Color.FromArgb(34, 38, 43);
+ }
+ else
+ {
+ gpuBox.BackColor = Color.FromArgb(24, 28, 32);
+ }
+ }
+ private void UpdateSummary()
+ {
+ string gpu;
+
+ if (graphicsApiBox.SelectedIndex == 1)
+ {
+ gpu = "Automatic GPU (Vulkan)";
+ }
+ else
+ {
+ gpu = gpuBox.SelectedItem?.ToString() ?? "Automatic GPU";
+
+ if (gpu.StartsWith("Adapter ", StringComparison.Ordinal))
+ {
+ int colon = gpu.IndexOf(':');
+ if (colon >= 0 && colon + 1 < gpu.Length)
+ gpu = gpu[(colon + 1)..].Trim();
+ }
+ }
+
+ string resolution = resolutionBox.SelectedItem?.ToString() ?? "Resolution";
+ string hz = refreshBox.SelectedItem?.ToString() ?? "--";
+
+ hardwareLabel.Text =
+ $"{gpu} • {resolution} • {hz} Hz";
+ }
+
+ private void UpdateStatus(string text, bool ok)
+ {
+ statusLabel.Text = text;
+ statusLabel.ForeColor = ok ? TextSecondary : Color.FromArgb(255, 120, 120);
+ }
+
+ private async void LaunchGame()
+ {
+ if (gameRunning) {
+ ShowError("FIFA Street is already running.");
+ return;
+ }
+ try
+ {
+ string exe = exePathBox.Text.Trim();
+ string gameRoot = gamePathBox.Text.Trim();
+
+ if (!File.Exists(exe))
+ {
+ ShowError("fifastreet.exe was not found.");
+ return;
+ }
+
+ if (!Directory.Exists(gameRoot))
+ {
+ ShowError("The game data folder does not exist.");
+ return;
+ }
+
+ if (!File.Exists(Path.Combine(gameRoot, "default.xex")))
+ {
+ MessageBox.Show(
+ "The selected folder does not contain default.xex.",
+ "Invalid folder",
+ MessageBoxButtons.OK,
+ MessageBoxIcon.Warning
+ );
+ return;
+ }
+
+ // Select the validated ReXGlue graphics backend.
+ string graphicsApi = graphicsApiBox.SelectedIndex == 1
+ ? "Vulkan"
+ : "D3D12";
+
+ string backendDirectory = Path.Combine(
+ Path.GetDirectoryName(exe)!,
+ "Backends",
+ graphicsApi);
+
+ string backendRuntime = Path.Combine(
+ backendDirectory,
+ "rexruntime.dll");
+
+ string backendGpu = Path.Combine(
+ backendDirectory,
+ "rexgpu-xenos.dll");
+
+ if (!File.Exists(backendRuntime) || !File.Exists(backendGpu))
+ {
+ MessageBox.Show(
+ $"The {graphicsApi} graphics backend is missing.\n\n" +
+ $"Expected files in:\n{backendDirectory}",
+ "FIFA Street Launcher",
+ MessageBoxButtons.OK,
+ MessageBoxIcon.Error);
+ return;
+ }
+
+ string executableDirectory = Path.GetDirectoryName(exe)!;
+
+ File.Copy(
+ backendRuntime,
+ Path.Combine(executableDirectory, "rexruntime.dll"),
+ true);
+
+ File.Copy(
+ backendGpu,
+ Path.Combine(executableDirectory, "rexgpu-xenos.dll"),
+ true);
+
+ if (string.IsNullOrWhiteSpace(resolutionBox.Text) ||
+ !resolutionBox.Text.Contains('x'))
+ {
+ ShowError("Select a valid resolution.");
+ return;
+ }
+
+ var resolution = resolutionBox.Text.Split('x');
+ int width = int.Parse(resolution[0]);
+ int height = int.Parse(resolution[1]);
+ string refresh = refreshBox.Text;
+
+ bool fullscreen =
+ displayModeBox.SelectedItem?.ToString() == "Fullscreen";
+
+ int monitor = Math.Max(0, monitorBox.SelectedIndex);
+
+ int adapter = gpuBox.SelectedIndex >= 0
+ ? gpuAdapterIndices[gpuBox.SelectedIndex] : -1;
+
+ string postEffect = postEffectBox.SelectedIndex switch
+ {
+ 1 => "fxaa",
+ 2 => "fxaa_extreme",
+ _ => "none"
+ };
+
+
+ string logsDir = Path.Combine(
+ Path.GetDirectoryName(exe)!,
+ "Logs"
+ );
+
+ Directory.CreateDirectory(logsDir);
+
+ string logFile =
+ Path.Combine(logsDir, "fifastreet.log");
+
+ var startInfo = new ProcessStartInfo
+ {
+ FileName = exe,
+ WorkingDirectory = Path.GetDirectoryName(exe)!,
+ UseShellExecute = false
+ };
+
+ // ReXGlue aplica a configuração por esta ordem:
+ // argumentos CLI -> ficheiro TOML -> variáveis de ambiente.
+ // Portanto, usar REX_* aqui garante que as escolhas do launcher
+ // têm prioridade sobre qualquer configuração guardada no jogo.
+
+ startInfo.Environment["REX_GAME_DATA_ROOT"] = gameRoot;
+ startInfo.Environment["REX_VIDEO_MODE_WIDTH"] = width.ToString();
+ startInfo.Environment["REX_VIDEO_MODE_HEIGHT"] = height.ToString();
+ // The display size does not change the Xbox 360 render targets.
+ int internalResolutionScale = Math.Max(1, internalResolutionBox.SelectedIndex + 1);
+
+startInfo.Environment["REX_DRAW_RESOLUTION_SCALE_X"] =
+ internalResolutionScale.ToString();
+
+startInfo.Environment["REX_DRAW_RESOLUTION_SCALE_Y"] =
+ internalResolutionScale.ToString();
+ startInfo.Environment["REX_WINDOW_WIDTH"] = width.ToString();
+ startInfo.Environment["REX_WINDOW_HEIGHT"] = height.ToString();
+ // Apply the selected rate to both the monitor and Xbox video timing.
startInfo.Environment["REX_VIDEO_MODE_REFRESH_RATE"] = refresh;
- startInfo.Environment["REX_FULLSCREEN"] =
- fullscreen ? "true" : "false";
- startInfo.Environment["REX_MONITOR"] = monitor.ToString();
- startInfo.Environment["REX_VSYNC"] =
- vsyncBox.Checked ? "true" : "false";
- startInfo.Environment["REX_NATIVE_2X_MSAA"] =
- msaaBox.Checked ? "true" : "false";
- startInfo.Environment["REX_SWAP_POST_EFFECT"] = postEffect;
-
- if (graphicsApi == "D3D12")
- {
- // Validated D3D12 configuration.
- startInfo.Environment["REX_D3D12_ALLOW_VARIABLE_REFRESH_RATE_AND_TEARING"] =
- vrrBox.Checked ? "true" : "false";
- startInfo.Environment["REX_D3D12_ADAPTER"] = adapter.ToString();
-
- // Do not force ROV/RTV. The validated D3D12 build uses
- // ReXGlue's automatic render target path selection.
- startInfo.Environment["REX_RENDER_TARGET_PATH_D3D12"] = "";
- }
- else
- {
- // Validated Vulkan configuration.
- // Vulkan device stays automatic; DXGI adapter indices are
- // not interchangeable with Vulkan device indices.
- startInfo.Environment["REX_VULKAN_DEVICE"] = "-1";
- startInfo.Environment["REX_RENDER_TARGET_PATH_VULKAN"] = "fbo";
- }
-
- // Compatibilidade / coerência GPU.
- startInfo.Environment["REX_READBACK_RESOLVE"] = "full";
- startInfo.Environment["REX_READBACK_MEMEXPORT"] =
- readbackMemexportBox.Checked ? "true" : "false";
- startInfo.Environment["REX_READBACK_MEMEXPORT_FAST"] =
- readbackMemexportFastBox.Checked ? "true" : "false";
- startInfo.Environment["REX_CLEAR_MEMORY_PAGE_STATE"] =
- clearMemoryPageStateBox.Checked ? "true" : "false";
- startInfo.Environment["REX_OCCLUSION_QUERY_ENABLE"] =
- occlusionQueryBox.Checked ? "true" : "false";
- startInfo.Environment["REX_ASYNC_SHADER_COMPILATION"] =
- asyncShadersBox.Checked ? "true" : "false";
-
- startInfo.Environment["REX_LOG_VERBOSE"] = "false";
- startInfo.Environment["REX_LOG_LEVEL"] = "info";
- startInfo.Environment["REX_LOG_FRAME_STATS"] = "true";
- startInfo.Environment["REX_BIND_DEBUG_OVERLAY"] = "Home";
- startInfo.Environment["REX_LOG_FILE"] = logFile;
-
- // Mantemos game_data_root também como argumento porque esta
- // aplicação já confirmou que o aceita diretamente.
- startInfo.ArgumentList.Add($"--game_data_root={gameRoot}");
-
- SaveSettings();
-
- string launcherDebug = Path.Combine(
- logsDir,
- "launcher_settings.txt"
- );
-
- File.WriteAllText(
- launcherDebug,
- $"Resolution={width}x{height}{Environment.NewLine}" +
- $"InternalResolution={1280 * internalResolutionScale}x{720 * internalResolutionScale} ({internalResolutionScale}x){Environment.NewLine}" +
- $"RefreshRate={refresh}{Environment.NewLine}" +
- $"Fullscreen={fullscreen}{Environment.NewLine}" +
- $"Monitor={monitor}{Environment.NewLine}" +
- $"VSync={vsyncBox.Checked}{Environment.NewLine}" +
- $"VRR={vrrBox.Checked}{Environment.NewLine}" +
- $"MSAA={msaaBox.Checked}{Environment.NewLine}" +
- $"PostEffect={postEffect}{Environment.NewLine}" +
- $"Adapter={adapter}{Environment.NewLine}" +
- $"ReadbackResolve=full (fixed){Environment.NewLine}" +
- $"ReadbackMemexport={readbackMemexportBox.Checked}{Environment.NewLine}" +
- $"ReadbackMemexportFast={readbackMemexportFastBox.Checked}{Environment.NewLine}" +
- $"ClearMemoryPageState={clearMemoryPageStateBox.Checked}{Environment.NewLine}" +
- $"OcclusionQueries={occlusionQueryBox.Checked}{Environment.NewLine}" +
- $"AsyncShaders={asyncShadersBox.Checked}{Environment.NewLine}"
- );
-
- UpdateStatus("Starting FIFA Street...", true);
-
- var process = Process.Start(startInfo);
-
- UpdateStatus(
- process != null
- ? $"Running • PID {process.Id}"
- : "Could not start the game",
- process != null
- );
- }
- catch (Exception ex)
- {
- UpdateStatus("Launch failed", false);
-
- MessageBox.Show(
- ex.Message,
- "Error starting FIFA Street",
- MessageBoxButtons.OK,
- MessageBoxIcon.Error
- );
- }
- }
-
- private void ShowError(string message)
- {
- UpdateStatus("Check your settings", false);
-
- MessageBox.Show(
- message,
- "FIFA Street Launcher",
- MessageBoxButtons.OK,
- MessageBoxIcon.Error
- );
- }
-
- private void BrowseExe()
- {
- using var dialog = new OpenFileDialog
- {
- Filter = "FIFA Street executable|fifastreet.exe|Executables|*.exe"
- };
-
- if (dialog.ShowDialog() == DialogResult.OK)
- exePathBox.Text = dialog.FileName;
- }
-
- private void BrowseGame()
- {
- using var dialog = new FolderBrowserDialog
- {
- Description = "Select the folder containing default.xex"
- };
-
- if (dialog.ShowDialog() == DialogResult.OK)
- gamePathBox.Text = dialog.SelectedPath;
- }
-
- private void OpenLogs()
- {
- string exe = exePathBox.Text.Trim();
-
- if (!File.Exists(exe))
- return;
-
- string logs = Path.Combine(
- Path.GetDirectoryName(exe)!,
- "Logs"
- );
-
- Directory.CreateDirectory(logs);
-
- Process.Start(new ProcessStartInfo
- {
- FileName = "explorer.exe",
- Arguments = $"\"{logs}\"",
- UseShellExecute = true
- });
- }
-
- private void OpenGameFolder()
- {
- string exe = exePathBox.Text.Trim();
-
- if (!File.Exists(exe))
- return;
-
- Process.Start(new ProcessStartInfo
- {
- FileName = "explorer.exe",
- Arguments = $"\"{Path.GetDirectoryName(exe)}\"",
- UseShellExecute = true
- });
- }
-
+ ApplyGameLanguage(startInfo);
+ // Disable the guest pacing limit together with display VSync.
+ startInfo.Environment["REX_GUEST_VBLANK_UNLOCKED"] =
+ vsyncBox.Checked ? "false" : "true";
+ startInfo.Environment["REX_FULLSCREEN"] =
+ fullscreen ? "true" : "false";
+ startInfo.Environment["REX_MONITOR"] = (monitor + 1).ToString();
+ startInfo.Environment["REX_LAUNCHER_MONITOR_DEVICE"] = Screen.AllScreens[monitor].DeviceName;
+ startInfo.Environment["REX_VSYNC"] =
+ vsyncBox.Checked ? "true" : "false";
+ startInfo.Environment["REX_NATIVE_2X_MSAA"] =
+ msaaBox.Checked ? "true" : "false";
+ startInfo.Environment["REX_SWAP_POST_EFFECT"] = postEffect;
+
+ if (graphicsApi == "D3D12")
+ {
+ // Validated D3D12 configuration.
+ startInfo.Environment["REX_D3D12_ALLOW_VARIABLE_REFRESH_RATE_AND_TEARING"] =
+ !vsyncBox.Checked && vrrBox.Checked ? "true" : "false";
+ startInfo.Environment["REX_D3D12_ADAPTER"] = adapter.ToString();
+
+ // Do not force ROV/RTV. The validated D3D12 build uses
+ // ReXGlue's automatic render target path selection.
+ startInfo.Environment["REX_RENDER_TARGET_PATH_D3D12"] = "";
+ }
+ else
+ {
+ // Validated Vulkan configuration.
+ // Vulkan device stays automatic; DXGI adapter indices are
+ // not interchangeable with Vulkan device indices.
+ startInfo.Environment["REX_VULKAN_DEVICE"] = "-1";
+ startInfo.Environment["REX_RENDER_TARGET_PATH_VULKAN"] = "fbo";
+ // Override legacy TOML values: checked means FIFO, unchecked
+ // requests immediate presentation without display synchronization.
+ startInfo.Environment["REX_VULKAN_ALLOW_PRESENT_MODE_IMMEDIATE"] =
+ vsyncBox.Checked ? "false" : "true";
+ startInfo.Environment["REX_VULKAN_ALLOW_PRESENT_MODE_MAILBOX"] = "false";
+ startInfo.Environment["REX_VULKAN_ALLOW_PRESENT_MODE_FIFO_RELAXED"] =
+ vsyncBox.Checked ? "false" : "true";
+ }
+
+ // Compatibilidade / coerência GPU.
+ startInfo.Environment["REX_READBACK_RESOLVE"] = "full";
+ // Keep synchronous Full Readback; reduce scheduler round trips for
+ // short GPU work without reading before its fence is signalled.
+ startInfo.Environment["REX_D3D12_READBACK_SHORT_WAIT"] = "true";
+ startInfo.Environment["REX_D3D12_READBACK_SPIN_US"] = "500";
+ startInfo.Environment["REX_VULKAN_READBACK_SHORT_WAIT"] = "true";
+ startInfo.Environment["REX_VULKAN_READBACK_SPIN_US"] = "500";
+ startInfo.Environment["REX_READBACK_MEMEXPORT"] =
+ readbackMemexportBox.Checked ? "true" : "false";
+ startInfo.Environment[graphicsApi == "Vulkan"
+ ? "REX_VULKAN_READBACK_MEMEXPORT" : "REX_D3D12_READBACK_MEMEXPORT"] =
+ readbackMemexportBox.Checked ? "true" : "false";
+ startInfo.Environment["REX_READBACK_MEMEXPORT_FAST"] =
+ readbackMemexportBox.Checked && readbackMemexportFastBox.Checked ? "true" : "false";
+ startInfo.Environment["REX_CLEAR_MEMORY_PAGE_STATE"] =
+ clearMemoryPageStateBox.Checked ? "true" : "false";
+ startInfo.Environment["REX_OCCLUSION_QUERY_ENABLE"] =
+ occlusionQueryBox.Checked ? "true" : "false";
+ startInfo.Environment["REX_ASYNC_SHADER_COMPILATION"] =
+ asyncShadersBox.Checked ? "true" : "false";
+
+ startInfo.Environment["REX_LOG_VERBOSE"] = "false";
+ startInfo.Environment["REX_LOG_LEVEL"] = "info";
+ startInfo.Environment["REX_LOG_FRAME_STATS"] = "true";
+ startInfo.Environment["REX_BIND_DEBUG_OVERLAY"] = "Home";
+ startInfo.Environment["REX_LOG_FILE"] = logFile;
+
+ // Mantemos game_data_root também como argumento porque esta
+ // aplicação já confirmou que o aceita diretamente.
+ startInfo.ArgumentList.Add($"--game_data_root={gameRoot}");
+
+ SaveSettings();
+
+ string launcherDebug = Path.Combine(
+ logsDir,
+ "launcher_settings.txt"
+ );
+
+ File.WriteAllText(
+ launcherDebug,
+ $"Resolution={width}x{height}{Environment.NewLine}" +
+ $"InternalResolution={1280 * internalResolutionScale}x{720 * internalResolutionScale} ({internalResolutionScale}x){Environment.NewLine}" +
+ $"MonitorRefreshRate={refresh}{Environment.NewLine}" +
+ $"GuestRefreshRate={refresh}{Environment.NewLine}" +
+ $"GuestVblankUnlocked={!vsyncBox.Checked}{Environment.NewLine}" +
+ $"GraphicsApi={graphicsApi}{Environment.NewLine}" +
+ $"Fullscreen={fullscreen}{Environment.NewLine}" +
+ $"Monitor={monitor}{Environment.NewLine}" +
+ $"VSync={vsyncBox.Checked}{Environment.NewLine}" +
+ $"VRRRequested={vrrBox.Checked}; VRREffective={graphicsApi == "D3D12" && !vsyncBox.Checked && vrrBox.Checked}{Environment.NewLine}" +
+ $"MSAA={msaaBox.Checked}{Environment.NewLine}" +
+ $"PostEffect={postEffect}{Environment.NewLine}" +
+ $"Adapter={adapter}{Environment.NewLine}" +
+ $"ReadbackResolve=full (fixed){Environment.NewLine}" +
+ $"ReadbackMemexport={readbackMemexportBox.Checked}{Environment.NewLine}" +
+ $"ReadbackMemexportFast={readbackMemexportBox.Checked && readbackMemexportFastBox.Checked}{Environment.NewLine}" +
+ $"ClearMemoryPageState={clearMemoryPageStateBox.Checked}{Environment.NewLine}" +
+ $"OcclusionQueries={occlusionQueryBox.Checked}{Environment.NewLine}" +
+ $"AsyncShaders={asyncShadersBox.Checked}{Environment.NewLine}"
+ );
+
+ UpdateStatus("Starting FIFA Street...", true);
+
+ ApplyMonitorRefresh(monitor, refresh, fullscreen ? width : 0, fullscreen ? height : 0);
+ using var process = Process.Start(startInfo);
+ gameRunning = process != null;
+
+ UpdateStatus(
+ process != null
+ ? $"Running • PID {process.Id}"
+ : "Could not start the game",
+ process != null
+ );
+ if (process != null) {
+ await process.WaitForExitAsync();
+ UpdateStatus("Ready to play", true);
+ }
+ }
+ catch (Exception ex)
+ {
+ UpdateStatus("Launch failed", false);
+
+ MessageBox.Show(
+ ex.Message,
+ "Error starting FIFA Street",
+ MessageBoxButtons.OK,
+ MessageBoxIcon.Error
+ );
+ }
+ finally {
+ RestoreMonitorRefresh();
+ gameRunning = false;
+ if (closeAfterGame) Close();
+ }
+ }
+
+ protected override void OnFormClosing(FormClosingEventArgs e)
+ {
+ if (gameRunning && e.CloseReason == CloseReason.UserClosing) {
+ // Keep the launcher alive to restore the display after the game exits.
+ closeAfterGame = true;
+ e.Cancel = true;
+ Hide();
+ }
+ base.OnFormClosing(e);
+ }
+
+ [DllImport("user32.dll", CharSet = CharSet.Ansi)]
+ private static extern int ChangeDisplaySettingsEx(
+ string deviceName, ref DEVMODE mode, IntPtr window, uint flags, IntPtr parameter);
+
+ private void ApplyMonitorRefresh(int monitor, string refresh, int width, int height)
+ {
+ const uint CDS_TEST = 2, CDS_FULLSCREEN = 4;
+ const int DM_DISPLAYFREQUENCY = 0x00400000;
+ if (monitor < 0 || monitor >= Screen.AllScreens.Length ||
+ !int.TryParse(refresh, out int hz) || hz <= 1) {
+ throw new InvalidOperationException("Select a valid monitor and refresh rate.");
+ }
+ string device = Screen.AllScreens[monitor].DeviceName;
+ DEVMODE original = CreateDevMode();
+ if (!EnumDisplaySettings(device, ENUM_CURRENT_SETTINGS, ref original)) {
+ throw new InvalidOperationException("Could not read the monitor's current display mode.");
+ }
+ bool changeResolution = width > 0 && height > 0;
+ if (original.dmDisplayFrequency == hz &&
+ (!changeResolution || (original.dmPelsWidth == width && original.dmPelsHeight == height))) return;
+ DEVMODE requested = original;
+ requested.dmDisplayFrequency = hz;
+ requested.dmFields = DM_DISPLAYFREQUENCY;
+ if (changeResolution) {
+ requested.dmPelsWidth = width;
+ requested.dmPelsHeight = height;
+ requested.dmFields |= 0x00080000 | 0x00100000; // DM_PELSWIDTH | DM_PELSHEIGHT
+ }
+ int result = ChangeDisplaySettingsEx(device, ref requested, IntPtr.Zero, CDS_TEST, IntPtr.Zero);
+ if (result != 0) {
+ throw new InvalidOperationException(
+ $"The selected resolution and {hz} Hz are not available on this monitor (Windows code {result}).");
+ }
+ result = ChangeDisplaySettingsEx(device, ref requested, IntPtr.Zero, CDS_FULLSCREEN, IntPtr.Zero);
+ if (result != 0) {
+ throw new InvalidOperationException($"Windows could not apply {hz} Hz (code {result}).");
+ }
+ original.dmFields = requested.dmFields;
+ previousDisplayMode = original;
+ changedDisplay = device;
+ DEVMODE actual = CreateDevMode();
+ if (!EnumDisplaySettings(device, ENUM_CURRENT_SETTINGS, ref actual) ||
+ Math.Abs(actual.dmDisplayFrequency - hz) > 1 ||
+ (changeResolution && (actual.dmPelsWidth != width || actual.dmPelsHeight != height))) {
+ throw new InvalidOperationException("Windows did not apply the selected monitor refresh rate.");
+ }
+ }
+
+ private void RestoreMonitorRefresh()
+ {
+ if (changedDisplay == null) return;
+ string device = changedDisplay;
+ changedDisplay = null;
+ int result = ChangeDisplaySettingsEx(device, ref previousDisplayMode, IntPtr.Zero, 0, IntPtr.Zero);
+ if (result != 0) {
+ ShowError($"Could not restore the monitor refresh rate (Windows code {result}). Check Windows display settings.");
+ }
+ }
+
+ private void ShowError(string message)
+ {
+ UpdateStatus("Check your settings", false);
+
+ MessageBox.Show(
+ message,
+ "FIFA Street Launcher",
+ MessageBoxButtons.OK,
+ MessageBoxIcon.Error
+ );
+ }
+
+ private void BrowseExe()
+ {
+ using var dialog = new OpenFileDialog
+ {
+ Filter = "FIFA Street executable|fifastreet.exe|Executables|*.exe"
+ };
+
+ if (dialog.ShowDialog() == DialogResult.OK)
+ exePathBox.Text = dialog.FileName;
+ }
+
+ private void BrowseGame()
+ {
+ using var dialog = new FolderBrowserDialog
+ {
+ Description = "Select the folder containing default.xex"
+ };
+
+ if (dialog.ShowDialog() == DialogResult.OK)
+ gamePathBox.Text = dialog.SelectedPath;
+ }
+
+ private void OpenLogs()
+ {
+ string exe = exePathBox.Text.Trim();
+
+ if (!File.Exists(exe)) {
+ ShowError("Select an existing game executable first.");
+ return;
+ }
+
+ string logs = Path.Combine(
+ Path.GetDirectoryName(exe)!,
+ "Logs"
+ );
+
+ Directory.CreateDirectory(logs);
+
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = "explorer.exe",
+ Arguments = $"\"{logs}\"",
+ UseShellExecute = true
+ });
+ }
+
+ private void OpenGameFolder()
+ {
+ string exe = exePathBox.Text.Trim();
+
+ if (!File.Exists(exe)) {
+ ShowError("Select an existing game executable first.");
+ return;
+ }
+
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = "explorer.exe",
+ Arguments = $"\"{Path.GetDirectoryName(exe)}\"",
+ UseShellExecute = true
+ });
+ }
+
private void SaveSettings()
- {
- try
- {
- var settings = new LauncherSettings
- {
- ExePath = exePathBox.Text,
- GamePath = gamePathBox.Text,
- Resolution = resolutionBox.Text,
- RefreshRate = refreshBox.Text,
- Fullscreen = displayModeBox.SelectedIndex == 0,
- Monitor = monitorBox.SelectedIndex,
+ {
+ try
+ {
+ var settings = new LauncherSettings
+ {
+ ExePath = exePathBox.Text,
+ GamePath = gamePathBox.Text,
+ Resolution = resolutionBox.Text,
+ RefreshRate = refreshBox.Text,
+ Fullscreen = displayModeBox.SelectedIndex == 0,
+ Monitor = monitorBox.SelectedIndex,
GraphicsApi = graphicsApiBox.SelectedIndex,
- Gpu = gpuBox.SelectedIndex,
- GpuUsesDxgi = true,
- PostEffect = postEffectBox.SelectedIndex,
- InternalResolutionScale = internalResolutionBox.SelectedIndex,
- ReadbackMemexport = readbackMemexportBox.Checked,
- ReadbackMemexportFast = readbackMemexportFastBox.Checked,
- ClearMemoryPageState = clearMemoryPageStateBox.Checked,
- OcclusionQueries = occlusionQueryBox.Checked,
- AsyncShaders = asyncShadersBox.Checked,
- VSync = vsyncBox.Checked,
- VRR = vrrBox.Checked,
- MSAA = msaaBox.Checked
- };
-
- string json = JsonSerializer.Serialize(
- settings,
- new JsonSerializerOptions
- {
- WriteIndented = true
- }
- );
-
- File.WriteAllText(SettingsPath, json);
- }
- catch
- {
- }
- }
-
- private void LoadSettings()
- {
- try
- {
- if (!File.Exists(SettingsPath))
- return;
-
- var settings =
- JsonSerializer.Deserialize<LauncherSettings>(
- File.ReadAllText(SettingsPath)
- );
-
+ GameLanguage = GameLanguageIds[Math.Max(0, gameLanguageBox.SelectedIndex)],
+ Gpu = gpuBox.SelectedIndex,
+ GpuUsesDxgi = true,
+ PostEffect = postEffectBox.SelectedIndex,
+ InternalResolutionScale = internalResolutionBox.SelectedIndex,
+ ReadbackMemexport = readbackMemexportBox.Checked,
+ ReadbackMemexportFast = readbackMemexportFastBox.Checked,
+ ClearMemoryPageState = clearMemoryPageStateBox.Checked,
+ OcclusionQueries = occlusionQueryBox.Checked,
+ AsyncShaders = asyncShadersBox.Checked,
+ VSync = vsyncBox.Checked,
+ VRR = vrrBox.Checked,
+ MSAA = msaaBox.Checked
+ };
+
+ string json = JsonSerializer.Serialize(
+ settings,
+ new JsonSerializerOptions
+ {
+ WriteIndented = true
+ }
+ );
+
+ File.WriteAllText(SettingsPath, json);
+ }
+ catch (Exception ex)
+ {
+ throw new IOException("Could not save launcher settings: " + ex.Message, ex);
+ }
+ }
+
+ private void LoadSettings()
+ {
+ try
+ {
+ if (!File.Exists(SettingsPath))
+ return;
+
+ var settings =
+ JsonSerializer.Deserialize<LauncherSettings>(
+ File.ReadAllText(SettingsPath)
+ );
+
if (settings == null)
return;
-
- exePathBox.Text = settings.ExePath ?? exePathBox.Text;
- const string oldDefaultExe = @"C:\Users\Samuel M\Desktop\FIFASTREET - 2012\Jogo\FifaStreetRex\out\build\win-amd64-debug\fifastreet.exe";
- string releaseExe = oldDefaultExe.Replace("win-amd64-debug", "win-amd64-release");
- if (string.Equals(exePathBox.Text, oldDefaultExe, StringComparison.OrdinalIgnoreCase)
- && File.Exists(releaseExe))
- exePathBox.Text = releaseExe;
- gamePathBox.Text = settings.GamePath ?? gamePathBox.Text;
-
- displayModeBox.SelectedIndex =
- settings.Fullscreen ? 0 : 1;
-
- if (settings.Monitor >= 0 &&
- settings.Monitor < monitorBox.Items.Count)
- {
- monitorBox.SelectedIndex = settings.Monitor;
- }
-
- DetectDisplayModes();
-
- SelectItem(resolutionBox, settings.Resolution);
- SelectItem(refreshBox, settings.RefreshRate);
-
- if (settings.GraphicsApi >= 0 &&
- settings.GraphicsApi < graphicsApiBox.Items.Count)
- {
- graphicsApiBox.SelectedIndex = settings.GraphicsApi;
- }
-
- if (settings.GpuUsesDxgi && settings.Gpu >= 0 &&
- settings.Gpu < gpuBox.Items.Count)
- {
- gpuBox.SelectedIndex = settings.Gpu;
- }
-
- if (settings.PostEffect >= 0 &&
- settings.PostEffect < postEffectBox.Items.Count)
- {
- postEffectBox.SelectedIndex = settings.PostEffect;
- }
-if (settings.InternalResolutionScale >= 0 &&
- settings.InternalResolutionScale < internalResolutionBox.Items.Count)
-{
- internalResolutionBox.SelectedIndex = settings.InternalResolutionScale;
-}
-
- readbackMemexportBox.Checked = settings.ReadbackMemexport;
- readbackMemexportFastBox.Checked = settings.ReadbackMemexportFast;
- clearMemoryPageStateBox.Checked = settings.ClearMemoryPageState;
- occlusionQueryBox.Checked = settings.OcclusionQueries;
- asyncShadersBox.Checked = settings.AsyncShaders;
-
- vsyncBox.Checked = settings.VSync;
- vrrBox.Checked = settings.VRR;
- msaaBox.Checked = settings.MSAA;
- }
- catch
- {
- }
- }
-
+ int languageIndex = Array.IndexOf(GameLanguageIds, settings.GameLanguage);
+ gameLanguageBox.SelectedIndex = Math.Max(0, languageIndex);
+
+ exePathBox.Text = settings.ExePath ?? exePathBox.Text;
+ const string oldDefaultExe = @"C:\Users\Samuel M\Desktop\FIFASTREET - 2012\Jogo\FifaStreetRex\out\build\win-amd64-debug\fifastreet.exe";
+ string releaseExe = oldDefaultExe.Replace("win-amd64-debug", "win-amd64-release");
+ if (string.Equals(exePathBox.Text, oldDefaultExe, StringComparison.OrdinalIgnoreCase)
+ && File.Exists(releaseExe))
+ exePathBox.Text = releaseExe;
+ gamePathBox.Text = settings.GamePath ?? gamePathBox.Text;
+
+ displayModeBox.SelectedIndex =
+ settings.Fullscreen ? 0 : 1;
+
+ if (settings.Monitor >= 0 &&
+ settings.Monitor < monitorBox.Items.Count)
+ {
+ monitorBox.SelectedIndex = settings.Monitor;
+ }
+
+ DetectDisplayModes();
+
+ SelectItem(resolutionBox, settings.Resolution);
+ SelectItem(refreshBox, settings.RefreshRate);
+
+ if (settings.GraphicsApi >= 0 &&
+ settings.GraphicsApi < graphicsApiBox.Items.Count)
+ {
+ graphicsApiBox.SelectedIndex = settings.GraphicsApi;
+ }
+
+ if (settings.GpuUsesDxgi && settings.Gpu >= 0 &&
+ settings.Gpu < gpuBox.Items.Count)
+ {
+ gpuBox.SelectedIndex = settings.Gpu;
+ }
+
+ if (settings.PostEffect >= 0 &&
+ settings.PostEffect < postEffectBox.Items.Count)
+ {
+ postEffectBox.SelectedIndex = settings.PostEffect;
+ }
+if (settings.InternalResolutionScale >= 0 &&
+ settings.InternalResolutionScale < internalResolutionBox.Items.Count)
+{
+ internalResolutionBox.SelectedIndex = settings.InternalResolutionScale;
+}
+
+ readbackMemexportBox.Checked = settings.ReadbackMemexport;
+ readbackMemexportFastBox.Checked = settings.ReadbackMemexportFast;
+ clearMemoryPageStateBox.Checked = settings.ClearMemoryPageState;
+ occlusionQueryBox.Checked = settings.OcclusionQueries;
+ asyncShadersBox.Checked = settings.AsyncShaders;
+
+ vsyncBox.Checked = settings.VSync;
+ vrrBox.Checked = settings.VRR;
+ msaaBox.Checked = settings.MSAA;
+ }
+ catch
+ {
+ }
+ }
+
private static void SelectItem(ComboBox box, string? value)
- {
- if (string.IsNullOrWhiteSpace(value))
- return;
-
- int index = box.Items.IndexOf(value);
-
- if (index >= 0)
- box.SelectedIndex = index;
+ {
+ if (string.IsNullOrWhiteSpace(value))
+ return;
+
+ int index = box.Items.IndexOf(value);
+
+ if (index >= 0)
+ box.SelectedIndex = index;
}
- private sealed class MessiPicture : PictureBox
+ private void ApplyGameLanguage(ProcessStartInfo startInfo)
{
- private const float CropX = 100f / 1280f;
- private const float CropY = 225f / 1819f;
- private const float CropWidth = 640f / 1280f;
-
- protected override void OnPaint(PaintEventArgs e)
- {
- if (Image == null || ClientSize.Width <= 0 || ClientSize.Height <= 0)
- return;
-
- e.Graphics.Clear(Color.FromArgb(10, 12, 16));
- e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
- e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
-
- float sourceX = Image.Width * CropX;
- float sourceY = Image.Height * CropY;
- float sourceWidth = Image.Width * CropWidth;
-
- // Preserve the same horizontal framing. Expanding the launcher
- // reveals more of the source image vertically without stretching.
- float scale = ClientSize.Width / sourceWidth;
- float sourceHeight = ClientSize.Height / scale;
- float availableHeight = Image.Height - sourceY;
- sourceHeight = Math.Min(sourceHeight, availableHeight);
-
- var sourceRect = new RectangleF(sourceX, sourceY, sourceWidth, sourceHeight);
- float destinationHeight = sourceHeight * scale;
- var destinationRect = new RectangleF(0, 0, ClientSize.Width, destinationHeight);
-
- e.Graphics.DrawImage(Image, destinationRect, sourceRect, GraphicsUnit.Pixel);
- }
+ int index = Math.Max(0, gameLanguageBox.SelectedIndex);
+ startInfo.Environment["REX_USER_LANGUAGE"] = GameLanguageIds[index].ToString(System.Globalization.CultureInfo.InvariantCulture);
}
-}
-
-public class LauncherSettings
-{
- public string? ExePath { get; set; }
- public string? GamePath { get; set; }
- public string? Resolution { get; set; }
- public string? RefreshRate { get; set; }
- public bool Fullscreen { get; set; } = true;
- public int Monitor { get; set; }
+
+ private sealed class MessiPicture : PictureBox
+ {
+ private const float CropX = 100f / 1280f;
+ private const float CropY = 225f / 1819f;
+ private const float CropWidth = 640f / 1280f;
+
+ protected override void OnPaint(PaintEventArgs e)
+ {
+ if (Image == null || ClientSize.Width <= 0 || ClientSize.Height <= 0)
+ return;
+
+ e.Graphics.Clear(Color.FromArgb(10, 12, 16));
+ e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
+ e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
+
+ float sourceX = Image.Width * CropX;
+ float sourceY = Image.Height * CropY;
+ float sourceWidth = Image.Width * CropWidth;
+
+ // Preserve the same horizontal framing. Expanding the launcher
+ // reveals more of the source image vertically without stretching.
+ float scale = ClientSize.Width / sourceWidth;
+ float sourceHeight = ClientSize.Height / scale;
+ float availableHeight = Image.Height - sourceY;
+ sourceHeight = Math.Min(sourceHeight, availableHeight);
+
+ var sourceRect = new RectangleF(sourceX, sourceY, sourceWidth, sourceHeight);
+ float destinationHeight = sourceHeight * scale;
+ var destinationRect = new RectangleF(0, 0, ClientSize.Width, destinationHeight);
+
+ e.Graphics.DrawImage(Image, destinationRect, sourceRect, GraphicsUnit.Pixel);
+ }
+ }
+}
+
+public class LauncherSettings
+{
+ public string? ExePath { get; set; }
+ public string? GamePath { get; set; }
+ public string? Resolution { get; set; }
+ public string? RefreshRate { get; set; }
+ public bool Fullscreen { get; set; } = true;
+ public int Monitor { get; set; }
public int GraphicsApi { get; set; } = 0;
- public int Gpu { get; set; }
- public bool GpuUsesDxgi { get; set; }
- public int PostEffect { get; set; }
- public int InternalResolutionScale { get; set; } = 0;
- public bool ReadbackMemexport { get; set; } = true;
- public bool ReadbackMemexportFast { get; set; } = true;
- public bool ClearMemoryPageState { get; set; } = false;
- public bool OcclusionQueries { get; set; } = true;
- public bool AsyncShaders { get; set; } = true;
- public bool VSync { get; set; } = true;
- public bool VRR { get; set; } = false;
- public bool MSAA { get; set; } = false;
-}
-
-public class RoundedPanel : Panel
-{
- public Color FillColor { get; set; } = Color.FromArgb(18, 22, 28);
- public Color BorderColor { get; set; } = Color.FromArgb(48, 57, 68);
- public int Radius { get; set; } = 16;
-
- public RoundedPanel()
- {
- DoubleBuffered = true;
- BackColor = Color.Transparent;
- }
-
- protected override void OnPaint(PaintEventArgs e)
- {
- base.OnPaint(e);
-
- e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
-
- Rectangle rect = ClientRectangle;
- rect.Width -= 1;
- rect.Height -= 1;
-
- using var path = CreateRoundedRectangle(rect, Radius);
- using var fill = new SolidBrush(FillColor);
- using var border = new Pen(BorderColor, 1F);
-
- e.Graphics.FillPath(fill, path);
- e.Graphics.DrawPath(border, path);
- }
-
- protected override void OnResize(EventArgs eventargs)
- {
- base.OnResize(eventargs);
- Invalidate();
- }
-
- private static GraphicsPath CreateRoundedRectangle(Rectangle rect, int radius)
- {
- int diameter = radius * 2;
-
- var path = new GraphicsPath();
-
- if (diameter <= 0)
- {
- path.AddRectangle(rect);
- return path;
- }
-
- var arc = new Rectangle(rect.Location, new Size(diameter, diameter));
-
- path.AddArc(arc, 180, 90);
-
- arc.X = rect.Right - diameter;
- path.AddArc(arc, 270, 90);
-
- arc.Y = rect.Bottom - diameter;
- path.AddArc(arc, 0, 90);
-
- arc.X = rect.Left;
- path.AddArc(arc, 90, 90);
-
- path.CloseFigure();
-
- return path;
- }
-}
-
-public class ModernButton : Button
-{
- public Color FillColor { get; set; } = Color.FromArgb(24, 29, 36);
- public Color HoverColor { get; set; } = Color.FromArgb(34, 41, 50);
- public Color BorderColor { get; set; } = Color.FromArgb(48, 57, 68);
- public int Radius { get; set; } = 10;
-
- private bool hovered;
-
- public ModernButton()
- {
- FlatStyle = FlatStyle.Flat;
- FlatAppearance.BorderSize = 0;
- Cursor = Cursors.Hand;
- UseVisualStyleBackColor = false;
- DoubleBuffered = true;
- BackColor = Color.Transparent;
-
- MouseEnter += (_, _) =>
- {
- hovered = true;
- Invalidate();
- };
-
- MouseLeave += (_, _) =>
- {
- hovered = false;
- Invalidate();
- };
- }
-
- protected override void OnPaint(PaintEventArgs pevent)
- {
- pevent.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
-
- Rectangle rect = ClientRectangle;
- rect.Width -= 1;
- rect.Height -= 1;
-
- using var path = CreateRoundedRectangle(rect, Radius);
- using var fill = new SolidBrush(hovered ? HoverColor : FillColor);
- using var border = new Pen(BorderColor, 1F);
-
- pevent.Graphics.FillPath(fill, path);
- pevent.Graphics.DrawPath(border, path);
-
- TextRenderer.DrawText(
- pevent.Graphics,
- Text,
- Font,
- ClientRectangle,
- ForeColor,
- TextFormatFlags.HorizontalCenter |
- TextFormatFlags.VerticalCenter |
- TextFormatFlags.EndEllipsis
- );
- }
-
- private static GraphicsPath CreateRoundedRectangle(Rectangle rect, int radius)
- {
- int diameter = radius * 2;
-
- var path = new GraphicsPath();
-
- if (diameter <= 0)
- {
- path.AddRectangle(rect);
- return path;
- }
-
- var arc = new Rectangle(rect.Location, new Size(diameter, diameter));
-
- path.AddArc(arc, 180, 90);
-
- arc.X = rect.Right - diameter;
- path.AddArc(arc, 270, 90);
-
- arc.Y = rect.Bottom - diameter;
- path.AddArc(arc, 0, 90);
-
- arc.X = rect.Left;
- path.AddArc(arc, 90, 90);
-
- path.CloseFigure();
-
- return path;
- }
-}
+ public int GameLanguage { get; set; } = 1;
+ public int Gpu { get; set; }
+ public bool GpuUsesDxgi { get; set; }
+ public int PostEffect { get; set; }
+ public int InternalResolutionScale { get; set; } = 0;
+ public bool ReadbackMemexport { get; set; } = true;
+ public bool ReadbackMemexportFast { get; set; } = true;
+ public bool ClearMemoryPageState { get; set; } = false;
+ public bool OcclusionQueries { get; set; } = true;
+ public bool AsyncShaders { get; set; } = true;
+ public bool VSync { get; set; } = true;
+ public bool VRR { get; set; } = false;
+ public bool MSAA { get; set; } = false;
+}
+
+public class RoundedPanel : Panel
+{
+ public Color FillColor { get; set; } = Color.FromArgb(18, 22, 28);
+ public Color BorderColor { get; set; } = Color.FromArgb(48, 57, 68);
+ public int Radius { get; set; } = 16;
+
+ public RoundedPanel()
+ {
+ DoubleBuffered = true;
+ BackColor = Color.Transparent;
+ }
+
+ protected override void OnPaint(PaintEventArgs e)
+ {
+ base.OnPaint(e);
+
+ e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
+
+ Rectangle rect = ClientRectangle;
+ rect.Width -= 1;
+ rect.Height -= 1;
+
+ using var path = CreateRoundedRectangle(rect, Radius);
+ using var fill = new SolidBrush(FillColor);
+ using var border = new Pen(BorderColor, 1F);
+
+ e.Graphics.FillPath(fill, path);
+ e.Graphics.DrawPath(border, path);
+ }
+
+ protected override void OnResize(EventArgs eventargs)
+ {
+ base.OnResize(eventargs);
+ Invalidate();
+ }
+
+ private static GraphicsPath CreateRoundedRectangle(Rectangle rect, int radius)
+ {
+ int diameter = radius * 2;
+
+ var path = new GraphicsPath();
+
+ if (diameter <= 0)
+ {
+ path.AddRectangle(rect);
+ return path;
+ }
+
+ var arc = new Rectangle(rect.Location, new Size(diameter, diameter));
+
+ path.AddArc(arc, 180, 90);
+
+ arc.X = rect.Right - diameter;
+ path.AddArc(arc, 270, 90);
+
+ arc.Y = rect.Bottom - diameter;
+ path.AddArc(arc, 0, 90);
+
+ arc.X = rect.Left;
+ path.AddArc(arc, 90, 90);
+
+ path.CloseFigure();
+
+ return path;
+ }
+}
+
+public class ModernButton : Button
+{
+ public Color FillColor { get; set; } = Color.FromArgb(24, 29, 36);
+ public Color HoverColor { get; set; } = Color.FromArgb(34, 41, 50);
+ public Color BorderColor { get; set; } = Color.FromArgb(48, 57, 68);
+ public int Radius { get; set; } = 10;
+
+ private bool hovered;
+
+ public ModernButton()
+ {
+ FlatStyle = FlatStyle.Flat;
+ FlatAppearance.BorderSize = 0;
+ Cursor = Cursors.Hand;
+ UseVisualStyleBackColor = false;
+ DoubleBuffered = true;
+ BackColor = Color.Transparent;
+
+ MouseEnter += (_, _) =>
+ {
+ hovered = true;
+ Invalidate();
+ };
+
+ MouseLeave += (_, _) =>
+ {
+ hovered = false;
+ Invalidate();
+ };
+ }
+
+ protected override void OnPaint(PaintEventArgs pevent)
+ {
+ pevent.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
+
+ Rectangle rect = ClientRectangle;
+ rect.Width -= 1;
+ rect.Height -= 1;
+
+ using var path = CreateRoundedRectangle(rect, Radius);
+ using var fill = new SolidBrush(hovered ? HoverColor : FillColor);
+ using var border = new Pen(BorderColor, 1F);
+
+ pevent.Graphics.FillPath(fill, path);
+ pevent.Graphics.DrawPath(border, path);
+
+ TextRenderer.DrawText(
+ pevent.Graphics,
+ Text,
+ Font,
+ ClientRectangle,
+ ForeColor,
+ TextFormatFlags.HorizontalCenter |
+ TextFormatFlags.VerticalCenter |
+ TextFormatFlags.EndEllipsis
+ );
+ }
+
+ private static GraphicsPath CreateRoundedRectangle(Rectangle rect, int radius)
+ {
+ int diameter = radius * 2;
+
+ var path = new GraphicsPath();
+
+ if (diameter <= 0)
+ {
+ path.AddRectangle(rect);
+ return path;
+ }
+
+ var arc = new Rectangle(rect.Location, new Size(diameter, diameter));
+
+ path.AddArc(arc, 180, 90);
+
+ arc.X = rect.Right - diameter;
+ path.AddArc(arc, 270, 90);
+
+ arc.Y = rect.Bottom - diameter;
+ path.AddArc(arc, 0, 90);
+
+ arc.X = rect.Left;
+ path.AddArc(arc, 90, 90);
+
+ path.CloseFigure();
+
+ return path;
+ }
+}
diff --git a/README.md b/README.md
index dc3d77d..ee26158 100644
--- a/README.md
+++ b/README.md
@@ -1,117 +1,129 @@
-<div align="center">
-
-<img src="docs/images/project-icon.png" alt="FIFA Street" width="64">
-
-# FIFA Street Recompiled
-
-**My experimental Windows PC port of FIFA Street (2012), built with ReXGlue.**
-
-### PORTED BY: SAMUELITODAVILA
-
-[Downloads](https://gitlab.com/samuelitodavila-group/fifa-street-pc/-/releases) · [Report a bug](https://gitlab.com/samuelitodavila-group/fifa-street-pc/-/issues) · [Build from source](docs/BUILDING.md)
-
-<img src="docs/images/start-screen.png" alt="FIFA Street running on PC" width="1000">
-
-</div>
-
+<div align="center">
+
+<img src="docs/images/project-icon.png" alt="FIFA Street" width="64">
+
+# FIFA Street Recompiled
+
+**My experimental Windows PC port of FIFA Street (2012), built with ReXGlue.**
+
+### PORTED BY: SAMUELITODAVILA
+
+[Downloads](https://gitlab.com/samuelitodavila-group/fifa-street-pc/-/releases) · [Report a bug](https://gitlab.com/samuelitodavila-group/fifa-street-pc/-/issues) · [Build from source](docs/BUILDING.md)
+
+<img src="docs/images/start-screen.png" alt="FIFA Street running on PC" width="1000">
+
+</div>
+
## About
-I'm bringing FIFA Street (2012) to Windows PC using ReXGlue. The project includes a graphical installer and a dedicated launcher with Direct3D 12 and Vulkan support, display settings, independent internal-resolution scaling and compatibility controls.
+## v0.4.0 Experimental
+
+The v0.4.0 installer includes precompiled game binaries for faster installation, updates that preserve saves and preferences, and English, Spanish, French, German and Italian selection in the launcher. See [the changelog](CHANGELOG.md) and [credits](CREDITS.md).
-The installer uses your own Xbox 360 ISO to extract the game files, apply my menu credits and compile the game locally. I don't include an ISO, original game data or generated game binaries in this repository or installer.
+**Latest download:** [FifaStreetSetup.exe — v0.4.0 Experimental](https://gitlab.com/samuelitodavila-group/fifa-street-pc/-/releases/v0.4.0-experimental/downloads/installers/FifaStreetSetup.exe) · [SHA-256](https://gitlab.com/samuelitodavila-group/fifa-street-pc/-/releases/v0.4.0-experimental/downloads/installers/FifaStreetSetup.exe.sha256) · [Third-party notices](https://gitlab.com/samuelitodavila-group/fifa-street-pc/-/releases/v0.4.0-experimental/downloads/notices/Third-party-notices-v0.4.0.zip)
-## Download and install
+For a new installation, provide your own ISO. To update, select your existing installation folder containing `Game` and `GameData`; no ISO extraction is needed. Only builds matching the three verified original module hashes are accepted. A shared title ID or a PAL/NTSC label alone does not establish compatibility.
+The instructions and download links below describe the earlier v0.3.0 source installer. Unlike v0.3.0, v0.4.0 contains generated game binaries. Their redistribution rights have not been established by the project's MIT licence; no legal clearance is claimed.
+
+I'm bringing FIFA Street (2012) to Windows PC using ReXGlue. The project includes a graphical installer and a dedicated launcher with Direct3D 12 and Vulkan support, display settings, independent internal-resolution scaling and compatibility controls.
+
+The v0.3.0 source installer uses your own Xbox 360 ISO to extract the game files, apply my menu credits and compile the game locally. The v0.4.0 installer instead includes generated game binaries and extracts data from your ISO. Original ISOs and extracted game data are not included. Generated binaries are release assets, not source repository files.
+
+## Download and install
+
The latest experimental release is available from the [release page](https://gitlab.com/samuelitodavila-group/fifa-street-pc/-/releases).
**Current download:** [FifaStreetSetup.exe — v0.3.0 Experimental](https://gitlab.com/samuelitodavila-group/fifa-street-pc/-/releases/v0.3.0-experimental/downloads/installers/FifaStreetSetup.exe) · [SHA-256](https://gitlab.com/samuelitodavila-group/fifa-street-pc/-/releases/v0.3.0-experimental/downloads/installers/FifaStreetSetup.exe.sha256) · [Third-party notices](https://gitlab.com/samuelitodavila-group/fifa-street-pc/-/releases/v0.3.0-experimental/downloads/notices/Third-party-notices-v0.3.0.zip)
The migrated installer is the unchanged, previously tested local v0.3.0 release. Older release pages preserve their source tags; installers for v0.1.0 and v0.2.0 have not been positively recovered. The GitLab validation job checks source syntax; a complete Windows rebuild is a separate manual job.
-
-**You'll need:** Windows x64, your own Xbox 360 FIFA Street ISO, a compatible Direct3D 12 or Vulkan GPU and at least 12 GB free on the destination drive, plus extra space for temporary and build files.
-
-1. Run **FifaStreetSetup.exe**.
-2. Select your ISO and a new or empty installation folder.
-3. Click **INSTALL FIFA STREET** and wait for extraction and local compilation.
-4. Once complete, click **OPEN LAUNCHER**, choose your settings and press **PLAY**.
-
-The installer includes its .NET runtime, SDK and compiler tools. Installation time varies by system.
-
-## Graphics backends
-
-v0.3.0 Experimental packages two validated ReXGlue graphics backends:
-
-- **Direct3D 12** — default backend, with GPU-adapter selection in the launcher.
-- **Vulkan** — uses automatic Vulkan device selection.
-
-The launcher switches the validated `rexruntime.dll` and `rexgpu-xenos.dll` pair automatically when the graphics API is changed.
-
-Full resolve readback is fixed to the validated configuration for both backends.
-
-## Resolution controls
-
-Output resolution and internal rendering resolution are configured independently.
-
-**Output Resolution** controls the video/window output. Common modes exposed by the launcher include:
-
-- 1280x720
-- 1920x1080
-- 2560x1440
-- 3200x1800
-- 3840x2160
-
-**Internal Resolution** controls the integer render scale relative to FIFA Street's 1280x720 base:
-
-- 1x — 1280x720
-- 2x — 2560x1440
-- 3x — 3840x2160
-- 4x — 5120x2880
-
-Higher settings are exposed for testing and do not imply a performance guarantee. Output resolution does not automatically change the internal rendering scale.
-
-## World Tour fix
-
-The current build recompiles the additional **FootballCompEngzf** competition-engine module used by World Tour. This fixes the crash/return-to-menu previously encountered during Bronze/Silver/Gold World Tour progression.
-
-The installer now builds the main executable plus:
-
-- `fifastreet_fifadllzf_xex.dll`
-- `fifastreet_FootballCompEngzf_xex.dll`
-
-A clean end-to-end installation from an original Xbox 360 ISO has been completed successfully with the current multi-backend pipeline. Direct3D 12, Vulkan, Practice and World Tour were tested successfully from that installation.
-
-## Screenshots and gameplay
-
-<img src="docs/images/installer.png" alt="My FIFA Street installer" width="900">
-
-<img src="docs/images/launcher.png" alt="My FIFA Street PC launcher" width="1000">
-
-### Gameplay video
-
-I've recorded gameplay from my PC build.
-
-<a href="https://gitlab.com/samuelitodavila-group/fifa-street-pc/-/releases/v0.1.0-experimental/downloads/gameplay/unknown_2026.10.01-16.18_1.mp4">
- <img src="docs/images/gameplay.png" alt="Download my FIFA Street PC gameplay video" width="1000">
-</a>
-
-## Current status
-
-The v0.3.0 installer pipeline has been validated from ISO extraction through credit patching, local recompilation, multi-backend packaging and first launch.
-
-A clean installation was tested with both Direct3D 12 and Vulkan. 2560x1440 output with 2x internal rendering was specifically exercised during backend validation. World Tour was also retested successfully on the final clean multi-backend installation.
-
-This remains an experimental port. Performance depends on hardware, drivers, output resolution and internal scale. 3x/4x internal rendering and 4K output should not be interpreted as guaranteed 60 FPS modes.
-
-See [known issues and validation](docs/STATUS.md) for the current validation scope.
-
-If you encounter a problem, [open an issue](https://gitlab.com/samuelitodavila-group/fifa-street-pc/-/issues) with your hardware, Windows and driver versions, selected graphics API/settings and relevant logs. Please don't upload ISOs or game files.
-
-## Credits and licence
-
+
+**You'll need:** Windows x64, your own Xbox 360 FIFA Street ISO, a compatible Direct3D 12 or Vulkan GPU and at least 12 GB free on the destination drive, plus extra space for temporary and build files.
+
+1. Run **FifaStreetSetup.exe**.
+2. Select your ISO and a new or empty installation folder.
+3. Click **INSTALL FIFA STREET** and wait for extraction and local compilation.
+4. Once complete, click **OPEN LAUNCHER**, choose your settings and press **PLAY**.
+
+The installer includes its .NET runtime, SDK and compiler tools. Installation time varies by system.
+
+## Graphics backends
+
+v0.3.0 Experimental packages two validated ReXGlue graphics backends:
+
+- **Direct3D 12** — default backend, with GPU-adapter selection in the launcher.
+- **Vulkan** — uses automatic Vulkan device selection.
+
+The launcher switches the validated `rexruntime.dll` and `rexgpu-xenos.dll` pair automatically when the graphics API is changed.
+
+Full resolve readback is fixed to the validated configuration for both backends.
+
+## Resolution controls
+
+Output resolution and internal rendering resolution are configured independently.
+
+**Output Resolution** controls the video/window output. Common modes exposed by the launcher include:
+
+- 1280x720
+- 1920x1080
+- 2560x1440
+- 3200x1800
+- 3840x2160
+
+**Internal Resolution** controls the integer render scale relative to FIFA Street's 1280x720 base:
+
+- 1x — 1280x720
+- 2x — 2560x1440
+- 3x — 3840x2160
+- 4x — 5120x2880
+
+Higher settings are exposed for testing and do not imply a performance guarantee. Output resolution does not automatically change the internal rendering scale.
+
+## World Tour fix
+
+The current build recompiles the additional **FootballCompEngzf** competition-engine module used by World Tour. This fixes the crash/return-to-menu previously encountered during Bronze/Silver/Gold World Tour progression.
+
+The installer now builds the main executable plus:
+
+- `fifastreet_fifadllzf_xex.dll`
+- `fifastreet_FootballCompEngzf_xex.dll`
+
+A clean end-to-end installation from an original Xbox 360 ISO has been completed successfully with the current multi-backend pipeline. Direct3D 12, Vulkan, Practice and World Tour were tested successfully from that installation.
+
+## Screenshots and gameplay
+
+<img src="docs/images/installer.png" alt="My FIFA Street installer" width="900">
+
+<img src="docs/images/launcher.png" alt="My FIFA Street PC launcher" width="1000">
+
+### Gameplay video
+
+I've recorded gameplay from my PC build.
+
+<a href="https://gitlab.com/samuelitodavila-group/fifa-street-pc/-/releases/v0.1.0-experimental/downloads/gameplay/unknown_2026.10.01-16.18_1.mp4">
+ <img src="docs/images/gameplay.png" alt="Download my FIFA Street PC gameplay video" width="1000">
+</a>
+
+## Current status
+
+The v0.3.0 installer pipeline has been validated from ISO extraction through credit patching, local recompilation, multi-backend packaging and first launch.
+
+A clean installation was tested with both Direct3D 12 and Vulkan. 2560x1440 output with 2x internal rendering was specifically exercised during backend validation. World Tour was also retested successfully on the final clean multi-backend installation.
+
+This remains an experimental port. Performance depends on hardware, drivers, output resolution and internal scale. 3x/4x internal rendering and 4K output should not be interpreted as guaranteed 60 FPS modes.
+
+See [known issues and validation](docs/STATUS.md) for the current validation scope.
+
+If you encounter a problem, [open an issue](https://gitlab.com/samuelitodavila-group/fifa-street-pc/-/issues) with your hardware, Windows and driver versions, selected graphics API/settings and relevant logs. Please don't upload ISOs or game files.
+
+## Credits and licence
+
I developed this project with assistance from **ChatGPT and OpenAI Codex**, and directed and tested the work myself.
-Thanks to [ReXGlue](https://github.com/rexglue/rexglue-sdk), [Xenia](https://github.com/xenia-project/xenia), [extract-xiso](https://github.com/XboxDev/extract-xiso), LLVM, CMake, Ninja, .NET and MonoGame. See the [third-party notices](licenses/README.md).
-
-My original installer, launcher and scripts use the [MIT License](LICENSE). Third-party components keep their own licences. FIFA Street, its game content, artwork and trademarks belong to their respective owners.
-
-This is my unofficial community project, with no affiliation to EA, Microsoft or Xbox.
+Thanks to **Emran_Ahm3d** for investigating and suggesting the Windows patch line-ending fix, module-registration path handling, flexible game-data paths, the FootballCompEng function-boundary override and resource-compiler compatibility. These contributions informed the integrated fixes and were reviewed and tested locally. His proposed general boundary scanner has not been integrated.
+
+Thanks to [ReXGlue](https://github.com/rexglue/rexglue-sdk), [Xenia](https://github.com/xenia-project/xenia), [extract-xiso](https://github.com/XboxDev/extract-xiso), LLVM, CMake, Ninja, .NET and MonoGame. See the [third-party notices](licenses/README.md).
+
+My original installer, launcher and scripts use the [MIT License](LICENSE). Third-party components keep their own licences. FIFA Street, its game content, artwork and trademarks belong to their respective owners.
+
+This is my unofficial community project, with no affiliation to EA, Microsoft or Xbox.
diff --git a/ci/build-inputs.json b/ci/build-inputs.json
new file mode 100644
index 0000000..a2c1b73
--- /dev/null
+++ b/ci/build-inputs.json
@@ -0,0 +1,4 @@
+{
+ "version": "v0.4.0-candidate",
+ "sha256": "660a3d807f7bbff394aa7e6f740d45064924523af09c719c5c37aa9b14d9b67d"
+}
diff --git a/ci/build-installer.ps1 b/ci/build-installer.ps1
index aceed21..bc2cace 100644
--- a/ci/build-installer.ps1
+++ b/ci/build-installer.ps1
@@ -1,41 +1,46 @@
-$ErrorActionPreference = 'Stop'
-$PSNativeCommandUseErrorActionPreference = $true
-$inputs = Join-Path $PWD '.ci-inputs'
-New-Item -ItemType Directory -Force -Path $inputs | Out-Null
-$archive = Join-Path $inputs 'inputs.zip'
-$url = "$env:CI_API_V4_URL/projects/$env:CI_PROJECT_ID/packages/generic/validated-build-inputs/v0.3.0/inputs.zip"
-Invoke-WebRequest -Uri $url -Headers @{ 'JOB-TOKEN' = $env:CI_JOB_TOKEN } -OutFile $archive
-$expected = 'f754c863c879008d3e31b8cb83b3f4070ec65455ea8a718b2625b2f195507b83'
-if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash.ToLower() -ne $expected) { throw 'Validated build input checksum mismatch.' }
-Expand-Archive -LiteralPath $archive -DestinationPath $inputs
-# Restore the unchanged public SDK and toolchain; no game code or data is included.
-New-Item -ItemType Directory -Force -Path ReXGlue/out/install, ReXGlue/out/win-amd64, ReXGlue/include, ReXGlue/thirdparty, Installer/tools | Out-Null
-Copy-Item -LiteralPath (Join-Path $inputs 'sdk') -Destination ReXGlue/out/install/win-amd64 -Recurse
-Copy-Item -Path (Join-Path $inputs 'sdk/bin/*') -Destination ReXGlue/out/win-amd64
-Copy-Item -Path (Join-Path $inputs 'sdk/lib/*.lib') -Destination ReXGlue/out/win-amd64
-Copy-Item -LiteralPath (Join-Path $inputs 'sdk/include/rex') -Destination ReXGlue/include -Recurse
-Copy-Item -LiteralPath (Join-Path $inputs 'licenses/ReXGlue.txt') -Destination ReXGlue/LICENSE
-Copy-Item -Path (Join-Path $inputs 'licenses/ReXGlue-thirdparty/*') -Destination ReXGlue/thirdparty -Recurse
-Copy-Item -LiteralPath (Join-Path $inputs 'tools/extract-xiso.exe') -Destination Installer/tools/extract-xiso.exe
-foreach ($backend in @('D3D12', 'Vulkan')) {
- $directory = Join-Path $PWD "ReXGlue/out/win-amd64-$($backend.ToLower())/Release"
- New-Item -ItemType Directory -Force -Path $directory | Out-Null
- Copy-Item -Path (Join-Path $inputs "sdk/backends/$backend/*") -Destination $directory
-}
-foreach ($name in @('rexruntime.lib', 'rexgpu-xenos.lib')) {
- Copy-Item -LiteralPath (Join-Path $inputs "sdk/lib/$name") -Destination ReXGlue/out/win-amd64-vulkan/Release
-}
-$compiler = Join-Path $inputs 'compiler'
-New-Item -ItemType Directory -Force -Path (Join-Path $compiler 'doc/cmake') | Out-Null
-Copy-Item -LiteralPath (Join-Path $inputs 'licenses/CMake.rst') -Destination (Join-Path $compiler 'doc/cmake/LICENSE.rst')
-$env:PATH = "$(Join-Path $compiler 'bin');$env:PATH"
-New-Item -ItemType Directory -Force -Path dist | Out-Null
-./Installer/BuildSetup.ps1 -Output "$PWD/dist/FifaStreet-Setup.exe" -LLVMRoot $compiler -CMakeRoot $compiler -NinjaPath (Join-Path $compiler 'bin/ninja.exe') -ClangResourceVersion '23'
-if (-not (Test-Path -LiteralPath 'dist/FifaStreet-Setup.exe')) { throw 'Installer was not created.' }
-Get-FileHash -LiteralPath 'dist/FifaStreet-Setup.exe' -Algorithm SHA256 |
- ForEach-Object { "$($_.Hash.ToLower()) FifaStreet-Setup.exe" } |
- Set-Content -Encoding ascii 'dist/FifaStreet-Setup.exe.sha256'
-$packageUrl = "$env:CI_API_V4_URL/projects/$env:CI_PROJECT_ID/packages/generic/installer-builds/$env:CI_COMMIT_SHA"
-foreach ($file in @('FifaStreet-Setup.exe', 'FifaStreet-Setup.exe.sha256')) {
- Invoke-RestMethod -Method Put -Uri "$packageUrl/$file" -Headers @{ 'JOB-TOKEN' = $env:CI_JOB_TOKEN } -InFile (Join-Path $PWD "dist/$file") -ContentType 'application/octet-stream' | Out-Null
-}
+$ErrorActionPreference = 'Stop'
+$PSNativeCommandUseErrorActionPreference = $true
+$inputs = Join-Path $PWD '.ci-inputs'
+New-Item -ItemType Directory -Force -Path $inputs | Out-Null
+$archive = Join-Path $inputs 'inputs.zip'
+$inputManifest = Get-Content -LiteralPath (Join-Path $PSScriptRoot 'build-inputs.json') -Raw | ConvertFrom-Json
+. (Join-Path $PSScriptRoot '../Installer/BuildIntegrity.ps1')
+if ($inputManifest.version -notmatch '^v[0-9A-Za-z.-]+$' -or $inputManifest.sha256 -notmatch '^[a-fA-F0-9]{64}$') { throw 'Invalid build input integrity manifest.' }
+$inputManifest = Get-Content -LiteralPath (Join-Path $PSScriptRoot 'build-inputs.json') -Raw | ConvertFrom-Json
+. (Join-Path $PSScriptRoot '../Installer/BuildIntegrity.ps1')
+if ($inputManifest.version -notmatch '^v[0-9A-Za-z.-]+$' -or $inputManifest.sha256 -notmatch '^[a-fA-F0-9]{64}$') { throw 'Invalid build input integrity manifest.' }
+$url = "$env:CI_API_V4_URL/projects/$env:CI_PROJECT_ID/packages/generic/validated-build-inputs/$($inputManifest.version)/inputs.zip"
+Invoke-WebRequest -Uri $url -Headers @{ 'JOB-TOKEN' = $env:CI_JOB_TOKEN } -OutFile $archive
+if ((Get-InputSha256 $archive) -ne $inputManifest.sha256) { throw 'Validated build input checksum mismatch.' }
+Expand-Archive -LiteralPath $archive -DestinationPath $inputs
+# Restore the unchanged public SDK and toolchain; no game code or data is included.
+New-Item -ItemType Directory -Force -Path ReXGlue/out/install, ReXGlue/out/win-amd64, ReXGlue/include, ReXGlue/thirdparty, Installer/tools | Out-Null
+Copy-Item -LiteralPath (Join-Path $inputs 'sdk') -Destination ReXGlue/out/install/win-amd64 -Recurse
+Copy-Item -Path (Join-Path $inputs 'sdk/bin/*') -Destination ReXGlue/out/win-amd64
+Copy-Item -Path (Join-Path $inputs 'sdk/lib/*.lib') -Destination ReXGlue/out/win-amd64
+Copy-Item -LiteralPath (Join-Path $inputs 'sdk/include/rex') -Destination ReXGlue/include -Recurse
+Copy-Item -LiteralPath (Join-Path $inputs 'licenses/ReXGlue.txt') -Destination ReXGlue/LICENSE
+Copy-Item -Path (Join-Path $inputs 'licenses/ReXGlue-thirdparty/*') -Destination ReXGlue/thirdparty -Recurse
+Copy-Item -LiteralPath (Join-Path $inputs 'tools/extract-xiso.exe') -Destination Installer/tools/extract-xiso.exe
+foreach ($backend in @('D3D12', 'Vulkan')) {
+ $backendManifest = Get-Content Installer/backend-manifest.json -Raw | ConvertFrom-Json
+ $directory = Join-Path $PWD ("ReXGlue/" + $backendManifest.backends.$backend.source)
+ New-Item -ItemType Directory -Force -Path $directory | Out-Null
+ Copy-Item -Path (Join-Path $inputs "sdk/backends/$backend/*") -Destination $directory
+}
+foreach ($name in @('rexruntime.lib', 'rexgpu-xenos.lib')) {
+ Copy-Item -LiteralPath (Join-Path $inputs "sdk/lib/$name") -Destination ReXGlue/out/win-amd64-vulkan/Release
+}
+$compiler = Join-Path $inputs 'compiler'
+New-Item -ItemType Directory -Force -Path (Join-Path $compiler 'doc/cmake') | Out-Null
+Copy-Item -LiteralPath (Join-Path $inputs 'licenses/CMake.rst') -Destination (Join-Path $compiler 'doc/cmake/LICENSE.rst')
+$env:PATH = "$(Join-Path $compiler 'bin');$env:PATH"
+New-Item -ItemType Directory -Force -Path dist | Out-Null
+./Installer/BuildSetup.ps1 -Output "$PWD/dist/FifaStreet-Setup.exe" -LLVMRoot $compiler -CMakeRoot $compiler -NinjaPath (Join-Path $compiler 'bin/ninja.exe') -ClangResourceVersion '23'
+if (-not (Test-Path -LiteralPath 'dist/FifaStreet-Setup.exe')) { throw 'Installer was not created.' }
+"$(Get-InputSha256 'dist/FifaStreet-Setup.exe') FifaStreet-Setup.exe" |
+ Set-Content -Encoding ascii 'dist/FifaStreet-Setup.exe.sha256'
+$packageUrl = "$env:CI_API_V4_URL/projects/$env:CI_PROJECT_ID/packages/generic/installer-builds/$env:CI_COMMIT_SHA"
+foreach ($file in @('FifaStreet-Setup.exe', 'FifaStreet-Setup.exe.sha256')) {
+ Invoke-RestMethod -Method Put -Uri "$packageUrl/$file" -Headers @{ 'JOB-TOKEN' = $env:CI_JOB_TOKEN } -InFile (Join-Path $PWD "dist/$file") -ContentType 'application/octet-stream' | Out-Null
+}
diff --git a/patches/rexglue-local-changes.patch b/patches/rexglue-local-changes.patch
index 55a89da..556f07a 100644
--- a/patches/rexglue-local-changes.patch
+++ b/patches/rexglue-local-changes.patch
@@ -51,7 +51,7 @@ index da8e432..0499356 100644
uint32_t primary_buffer_ptr_ = 0;
uint32_t primary_buffer_size_ = 0;
diff --git a/include/rex/graphics/d3d12/command_processor.h b/include/rex/graphics/d3d12/command_processor.h
-index 96d362b..29f4d8a 100644
+index 96d362b..4f48975 100644
--- a/include/rex/graphics/d3d12/command_processor.h
+++ b/include/rex/graphics/d3d12/command_processor.h
@@ -310,7 +310,7 @@ class D3D12CommandProcessor : public CommandProcessor {
@@ -82,6 +82,19 @@ index 96d362b..29f4d8a 100644
uint32_t current_index = 0;
uint64_t last_used_frame = 0;
};
+@@ -615,6 +616,12 @@ class D3D12CommandProcessor : public CommandProcessor {
+ Microsoft::WRL::ComPtr<ID3D12PipelineState> resolve_downscale_pipeline_;
+ Microsoft::WRL::ComPtr<ID3D12Resource> resolve_downscale_buffer_;
+ uint32_t resolve_downscale_buffer_size_ = 0;
++ // Diagnostic timestamps are sampled only with full synchronous readback.
++ Microsoft::WRL::ComPtr<ID3D12QueryHeap> resolve_timing_query_heap_;
++ Microsoft::WRL::ComPtr<ID3D12Resource> resolve_timing_readback_;
++ uint64_t resolve_timing_frequency_ = 0;
++ uint64_t resolve_timing_sample_counter_ = 0;
++ uint64_t resolve_timing_submission_ = 0;
+
+ // PWL gamma ramp can result in values with more precision than 10bpc. Though
+ // those sub-10bpc bits don't have any noticeable visual effect, so normally
diff --git a/include/rex/graphics/d3d12/texture_cache.h b/include/rex/graphics/d3d12/texture_cache.h
index 4d845c7..6986efc 100644
--- a/include/rex/graphics/d3d12/texture_cache.h
@@ -134,7 +147,7 @@ index 3b0fd61..be2c144 100644
enum class DepthStencilMode : uint32_t {
kNoModifiers,
diff --git a/include/rex/graphics/vulkan/command_processor.h b/include/rex/graphics/vulkan/command_processor.h
-index 696ff48..acbba70 100644
+index 696ff48..a2bdd15 100644
--- a/include/rex/graphics/vulkan/command_processor.h
+++ b/include/rex/graphics/vulkan/command_processor.h
@@ -149,6 +149,7 @@ class VulkanCommandProcessor : public CommandProcessor {
@@ -160,6 +173,26 @@ index 696ff48..acbba70 100644
struct SparseBufferBind {
VkBuffer buffer;
+@@ -406,7 +414,7 @@ class VulkanCommandProcessor : public CommandProcessor {
+ // Rechecks submission number and reclaims per-submission resources. Pass 0 as
+ // the submission to await to simply check status, or pass
+ // GetCurrentSubmission() to wait for all queue operations to be completed.
+- void CheckSubmissionFenceAndDeviceLoss(uint64_t await_submission);
++ void CheckSubmissionFenceAndDeviceLoss(uint64_t await_submission, const char* reason = "other");
+ // If is_guest_command is true, a new full frame - with full cleanup of
+ // resources and, if needed, starting capturing - is opened if pending (as
+ // opposed to simply resuming after mid-frame synchronization). Returns
+@@ -416,8 +424,8 @@ class VulkanCommandProcessor : public CommandProcessor {
+ // clearing and stopping capturing. Returns whether the submission was done
+ // successfully, if it has failed, leaves it open.
+ bool EndSubmission(bool is_swap);
+- bool AwaitAllQueueOperationsCompletion() {
+- CheckSubmissionFenceAndDeviceLoss(GetCurrentSubmission());
++ bool AwaitAllQueueOperationsCompletion(const char* reason = "other") {
++ CheckSubmissionFenceAndDeviceLoss(GetCurrentSubmission(), reason);
+ return !submission_open_ && submissions_in_flight_fences_.empty();
+ }
+ // Keep primary-buffer-end submit behavior aligned with D3D12: only submit
diff --git a/include/rex/input/input_system.h b/include/rex/input/input_system.h
index 1cb3faa..5529d0c 100644
--- a/include/rex/input/input_system.h
@@ -194,6 +227,20 @@ index b3947e0..21202c7 100644
kCount // sentinel -- must be last
};
+diff --git a/include/rex/stream.h b/include/rex/stream.h
+index 07eb5ea..ae8d43e 100644
+--- a/include/rex/stream.h
++++ b/include/rex/stream.h
+@@ -42,7 +42,8 @@ class BitStream {
+ // Note: num_bits MUST be in the range 0-57 (inclusive)
+ uint64_t Peek(size_t num_bits);
+ uint64_t Read(size_t num_bits);
+- bool Write(uint64_t val, size_t num_bits); // TODO(DrChat): Not tested!
++ // Returns false without modifying the stream if the write is out of bounds.
++ bool Write(uint64_t val, size_t num_bits);
+
+ size_t Copy(uint8_t* dest_buffer, size_t num_bits);
+
diff --git a/include/rex/ui/overlay/debug_overlay.h b/include/rex/ui/overlay/debug_overlay.h
index e15e410..fa838ff 100644
--- a/include/rex/ui/overlay/debug_overlay.h
@@ -212,8 +259,38 @@ index e15e410..fa838ff 100644
};
} // namespace rex::ui
+diff --git a/include/rex/ui/presenter.h b/include/rex/ui/presenter.h
+index afb4a30..1cfc84f 100644
+--- a/include/rex/ui/presenter.h
++++ b/include/rex/ui/presenter.h
+@@ -374,6 +374,9 @@ class Presenter {
+ // Requests (re)painting with the UI if there's UI to draw.
+ void RequestUIPaintFromUIThread();
+
++ // Called by the guest vblank worker; false keeps the timer fallback.
++ bool WaitForMonitorVBlank(double refresh_rate_hz);
++
+ protected:
+ enum class PaintResult {
+ kPresented,
+@@ -398,6 +401,7 @@ class Presenter {
+ static constexpr uint32_t kGuestOutputMailboxSize = 3;
+
+ struct GuestOutputProperties {
++ uint64_t frame_sequence = 0;
+ // At least any value being 0 here means the guest output is disabled for
+ // this frame.
+ uint32_t frontbuffer_width;
+@@ -976,6 +980,7 @@ class Presenter {
+ // Accessible only by refreshing, whether the last refresh contained an image
+ // rather than being blank.
+ bool guest_output_active_last_refresh_ = false;
++ uint64_t guest_output_frame_sequence_ = 0;
+
+ // Ordered by the Z order, and then by the time of addition.
+ // Note: All the iteration logic involving this Z ordering must be the same as
diff --git a/include/rex/ui/vulkan/functions/device_1_0.inc b/include/rex/ui/vulkan/functions/device_1_0.inc
-index aa55a4a..460ba63 100644
+index aa55a4a..ee502f0 100644
--- a/include/rex/ui/vulkan/functions/device_1_0.inc
+++ b/include/rex/ui/vulkan/functions/device_1_0.inc
@@ -25,6 +25,7 @@ XE_UI_VULKAN_FUNCTION(vkCmdEndQuery)
@@ -232,57 +309,67 @@ index aa55a4a..460ba63 100644
XE_UI_VULKAN_FUNCTION(vkGetImageMemoryRequirements)
XE_UI_VULKAN_FUNCTION(vkInvalidateMappedMemoryRanges)
XE_UI_VULKAN_FUNCTION(vkMapMemory)
-diff --git a/resources/templates/codegen/_indirect_call.inja b/resources/templates/codegen/_indirect_call.inja
-index d4b1830..127e573 100644
---- a/resources/templates/codegen/_indirect_call.inja
-+++ b/resources/templates/codegen/_indirect_call.inja
-@@ -1,12 +1,7 @@
- //=============================================================================
- // Indirect Call Dispatch
--//
--// REX_LOOKUP_FUNC indexes into the per-module dispatch table at
--// IMAGE_BASE + IMAGE_SIZE. REX_CALL_INDIRECT_FUNC bounds-checks the target
--// against the caller's [REX_CODE_BASE, REX_CODE_BASE + REX_CODE_SIZE +
--// REX_THUNK_RESERVE_SIZE) range; out-of-bounds targets and in-bounds
--// unregistered slots fall back to rex::runtime::ResolveIndirectFunction,
--// which queries the global FunctionDispatcher across every loaded module.
-+// Resolve through the runtime: function tables are independent of XEX images.
-+// The dispatcher handles calls across all loaded modules.
- //=============================================================================
+@@ -79,6 +81,7 @@ XE_UI_VULKAN_FUNCTION(vkResetDescriptorPool)
+ XE_UI_VULKAN_FUNCTION(vkResetFences)
+ XE_UI_VULKAN_FUNCTION(vkQueueBindSparse)
+ XE_UI_VULKAN_FUNCTION(vkQueueSubmit)
++XE_UI_VULKAN_FUNCTION(vkQueueWaitIdle)
+ XE_UI_VULKAN_FUNCTION(vkUnmapMemory)
+ XE_UI_VULKAN_FUNCTION(vkUpdateDescriptorSets)
+ XE_UI_VULKAN_FUNCTION(vkWaitForFences)
+diff --git a/include/rex/ui/vulkan/presenter.h b/include/rex/ui/vulkan/presenter.h
+index 56ee43b..4991869 100644
+--- a/include/rex/ui/vulkan/presenter.h
++++ b/include/rex/ui/vulkan/presenter.h
+@@ -281,7 +281,7 @@ class VulkanPresenter final : public Presenter {
+ ~Submission();
+
+ VkSemaphore acquire_semaphore() const { return acquire_semaphore_; }
+- VkSemaphore present_semaphore() const { return present_semaphore_; }
++ VkFence acquire_fence() const { return acquire_fence_; }
+ VkCommandPool draw_command_pool() const { return draw_command_pool_; }
+ VkCommandBuffer draw_command_buffer() const { return draw_command_buffer_; }
+
+@@ -292,7 +292,7 @@ class VulkanPresenter final : public Presenter {
+
+ const VulkanDevice* vulkan_device_;
+ VkSemaphore acquire_semaphore_ = VK_NULL_HANDLE;
+- VkSemaphore present_semaphore_ = VK_NULL_HANDLE;
++ VkFence acquire_fence_ = VK_NULL_HANDLE;
+ VkCommandPool draw_command_pool_ = VK_NULL_HANDLE;
+ VkCommandBuffer draw_command_buffer_ = VK_NULL_HANDLE;
+ };
+@@ -415,6 +415,8 @@ class VulkanPresenter final : public Presenter {
+ VkExtent2D swapchain_extent = {};
+ bool swapchain_is_fifo = false;
+ std::vector<VkImage> swapchain_images;
++ // Present waits are retired by reacquiring their image, not by a draw fence.
++ std::vector<VkSemaphore> swapchain_present_semaphores;
+ std::vector<SwapchainFramebuffer> swapchain_framebuffers;
+ };
- #ifdef REXGLUE_ENABLE_PROFILING
-@@ -17,22 +12,14 @@
- #endif
+diff --git a/include/rex/ui/vulkan/submission_tracker.h b/include/rex/ui/vulkan/submission_tracker.h
+index 505b599..3eda4cb 100644
+--- a/include/rex/ui/vulkan/submission_tracker.h
++++ b/include/rex/ui/vulkan/submission_tracker.h
+@@ -17,6 +17,7 @@
- #define REX_LOOKUP_FUNC(x, y) \
-- (*(PPCFunc**)(x + REX_IMAGE_BASE + REX_IMAGE_SIZE + (u64(u32(y) - REX_CODE_BASE) * 2)))
-+ rex::runtime::ResolveIndirectFunction(static_cast<uint32_t>(y))
-
--#define REX_CALL_INDIRECT_FUNC(x) \
-- do { \
-- REX_PROFILE_INDIRECT_DISPATCH(); \
-- uint32_t rex_indirect_target_ = (uint32_t)(x); \
-- PPCFunc* rex_indirect_func_; \
-- if ((uint32_t)(rex_indirect_target_ - REX_CODE_BASE) < \
-- REX_CODE_SIZE + REX_THUNK_RESERVE_SIZE) [[likely]] { \
-- rex_indirect_func_ = REX_LOOKUP_FUNC(base, rex_indirect_target_); \
-- } else { \
-- rex_indirect_func_ = nullptr; \
-- } \
-- if (!rex_indirect_func_) [[unlikely]] { \
-- ctx.last_indirect_target = rex_indirect_target_; \
-- rex_indirect_func_ = rex::runtime::ResolveIndirectFunction(rex_indirect_target_); \
-- } \
-- rex_indirect_func_(ctx, base); \
-+#define REX_CALL_INDIRECT_FUNC(x) \
-+ do { \
-+ REX_PROFILE_INDIRECT_DISPATCH(); \
-+ uint32_t rex_indirect_target_ = static_cast<uint32_t>(x); \
-+ ctx.last_indirect_target = rex_indirect_target_; \
-+ PPCFunc* rex_indirect_func_ = \
-+ REX_LOOKUP_FUNC(base, rex_indirect_target_); \
-+ rex_indirect_func_(ctx, base); \
- } while (0)
+ #include <rex/assert.h>
+ #include <rex/ui/vulkan/device.h>
++#include <rex/ui/vulkan/fence_wait_timing.h>
+
+ namespace rex {
+ namespace ui {
+@@ -104,7 +105,8 @@ class VulkanSubmissionTracker {
+ // guarantees as needed (when downloading, as opposed to just destroying).
+ // If false is returned, it's also not guaranteed that GetCompletedSubmission
+ // will return a value >= submission_index.
+- bool AwaitSubmissionCompletion(uint64_t submission_index);
++ bool AwaitSubmissionCompletion(uint64_t submission_index,
++ FenceWaitTiming::Reason reason = FenceWaitTiming::Reason::Other);
+ bool AwaitAllSubmissionsCompletion() {
+ return AwaitSubmissionCompletion(submission_current_ - 1);
+ }
diff --git a/src/codegen/builders/context.cpp b/src/codegen/builders/context.cpp
index f78e0d8..1d303db 100644
--- a/src/codegen/builders/context.cpp
@@ -726,6 +813,221 @@ index 1c73548..2d7d406 100644
graph.addUnresolvedJumpToFunction(funcAddr, branch.site, branch.target, branch.isCall,
branch.isConditional);
}
+diff --git a/src/core/bit_stream.cpp b/src/core/bit_stream.cpp
+index 9329c6d..7c718a2 100644
+--- a/src/core/bit_stream.cpp
++++ b/src/core/bit_stream.cpp
+@@ -39,12 +39,20 @@ uint64_t BitStream::Peek(size_t num_bits) {
+ assert_false(num_bits > 57);
+ assert_false(offset_bits_ + num_bits > size_bits_);
+
++ if (!num_bits || num_bits > 57 || offset_bits_ > size_bits_ ||
++ num_bits > size_bits_ - offset_bits_) {
++ return 0;
++ }
++
+ size_t offset_bytes = offset_bits_ >> 3;
+ size_t rel_offset_bits = offset_bits_ - (offset_bytes << 3);
+
+ // offset -->
+ // ..[junk]..| target bits |....[junk].............
+- uint64_t bits = *(uint64_t*)(buffer_ + offset_bytes);
++ const size_t available_bits = size_bits_ - (offset_bytes << 3);
++ const size_t available_bytes = available_bits / 8 + (available_bits % 8 != 0);
++ uint64_t bits = 0;
++ std::memcpy(&bits, buffer_ + offset_bytes, std::min(sizeof(bits), available_bytes));
+
+ // We need the data in little endian.
+ // TODO: Have a flag specifying endianness of data?
+@@ -68,82 +76,60 @@ uint64_t BitStream::Read(size_t num_bits) {
+ return val;
+ }
+
+-// TODO: This is totally not tested!
+ bool BitStream::Write(uint64_t val, size_t num_bits) {
+- assert_false(num_bits > 57);
+- assert_false(offset_bits_ + num_bits >= size_bits_);
+-
+- size_t offset_bytes = offset_bits_ >> 3;
+- size_t rel_offset_bits = offset_bits_ - (offset_bytes << 3);
+-
+- // Construct a mask
+- uint64_t mask = (1ULL << num_bits) - 1;
+- mask <<= 64 - (rel_offset_bits + num_bits);
+- mask = ~mask;
+-
+- // Shift the value left into position.
+- val <<= 64 - (rel_offset_bits + num_bits);
+-
+- // offset ----->
+- // ....[junk]...| target bits w/ junk |....[junk]......
+- uint64_t bits = *(uint64_t*)(buffer_ + offset_bytes);
+-
+- // AND with mask
+- // ....[junk]...| target bits (0) |........[junk]......
+- bits &= mask;
+-
+- // OR with val
+- // ....[junk]...| target bits (val) |......[junk]......
+- bits |= val;
+-
+- // Store into the bitstream.
+- *(uint64_t*)(buffer_ + offset_bytes) = bits;
+-
+- // Advance the bitstream forward.
+- Advance(num_bits);
+-
++ if (num_bits > 57 || offset_bits_ > size_bits_ ||
++ num_bits > size_bits_ - offset_bits_) {
++ return false;
++ }
++ // Write only the affected bytes, in the same MSB-first order as Read.
++ size_t remaining = num_bits;
++ while (remaining) {
++ const size_t bit_in_byte = offset_bits_ & 7;
++ const size_t count = std::min(remaining, 8 - bit_in_byte);
++ const size_t shift = 8 - bit_in_byte - count;
++ const uint8_t mask = uint8_t(((1u << count) - 1) << shift);
++ const uint8_t value = uint8_t((val >> (remaining - count)) << shift);
++ auto& byte = buffer_[offset_bits_ >> 3];
++ byte = uint8_t((byte & ~mask) | (value & mask));
++ offset_bits_ += count;
++ remaining -= count;
++ }
+ return true;
+ }
+
+ size_t BitStream::Copy(uint8_t* dest_buffer, size_t num_bits) {
+- size_t offset_bytes = offset_bits_ >> 3;
+- size_t rel_offset_bits = offset_bits_ - (offset_bytes << 3);
++ const size_t rel_offset_bits = offset_bits_ & 7;
++ if (!num_bits || offset_bits_ > size_bits_ ||
++ num_bits > size_bits_ - offset_bits_) {
++ return rel_offset_bits;
++ }
+ size_t bits_left = num_bits;
+ size_t out_offset_bytes = 0;
+
+- // First: Copy the first few bits up to a byte boundary.
++ // Preserve the source bit alignment in the first destination byte.
+ if (rel_offset_bits) {
+- uint64_t bits = Peek(8 - rel_offset_bits);
+- uint8_t clear_mask = ~((uint8_t(1) << rel_offset_bits) - 1);
+- dest_buffer[out_offset_bytes] &= clear_mask;
+- dest_buffer[out_offset_bytes] |= (uint8_t)bits;
+-
+- bits_left -= 8 - rel_offset_bits;
+- Advance(8 - rel_offset_bits);
+- out_offset_bytes++;
++ const size_t count = std::min(bits_left, 8 - rel_offset_bits);
++ const size_t shift = 8 - rel_offset_bits - count;
++ const uint8_t mask = uint8_t(((1u << count) - 1) << shift);
++ auto& byte = dest_buffer[out_offset_bytes++];
++ byte = uint8_t((byte & ~mask) | (uint8_t(Peek(count) << shift) & mask));
++ Advance(count);
++ bits_left -= count;
+ }
+-
+- // Second: Use memcpy for the bytes left.
+ if (bits_left >= 8) {
+- std::memcpy(dest_buffer + out_offset_bytes, buffer_ + offset_bytes + out_offset_bytes,
+- bits_left / 8);
+- out_offset_bytes += (bits_left / 8);
+- Advance((bits_left / 8) * 8);
+- bits_left -= (bits_left / 8) * 8;
++ const size_t bytes = bits_left / 8;
++ std::memcpy(dest_buffer + out_offset_bytes, buffer_ + (offset_bits_ >> 3), bytes);
++ out_offset_bytes += bytes;
++ Advance(bytes * 8);
++ bits_left %= 8;
+ }
+-
+- // Third: Copy the last few bits.
+ if (bits_left) {
+- uint64_t bits = Peek(bits_left);
+- bits <<= 8 - bits_left;
+-
+- uint8_t clear_mask = ((uint8_t(1) << bits_left) - 1);
+- dest_buffer[out_offset_bytes] &= clear_mask;
+- dest_buffer[out_offset_bytes] |= (uint8_t)bits;
++ const size_t shift = 8 - bits_left;
++ const uint8_t mask = uint8_t(((1u << bits_left) - 1) << shift);
++ auto& byte = dest_buffer[out_offset_bytes];
++ byte = uint8_t((byte & ~mask) | (uint8_t(Peek(bits_left) << shift) & mask));
+ Advance(bits_left);
+ }
+-
+- // Return the bit offset to the copied bits.
+ return rel_offset_bits;
+ }
+
+diff --git a/src/core/byte_stream.cpp b/src/core/byte_stream.cpp
+index 3dd190e..b45ba3e 100644
+--- a/src/core/byte_stream.cpp
++++ b/src/core/byte_stream.cpp
+@@ -11,6 +11,7 @@
+
+ #include <cstring>
+ #include <span>
++#include <stdexcept>
+
+ #include <rex/assert.h>
+ #include <rex/stream.h>
+@@ -23,19 +24,29 @@ ByteStream::ByteStream(uint8_t* data, size_t data_length, size_t offset)
+ ByteStream::~ByteStream() = default;
+
+ void ByteStream::Advance(size_t num_bytes) {
+- assert_true(offset_ + num_bytes <= data_length_);
++ if (offset_ > data_length_ || num_bytes > data_length_ - offset_) {
++ throw std::out_of_range("ByteStream advance exceeds buffer");
++ }
+ offset_ += num_bytes;
+ }
+
+ void ByteStream::Read(std::span<uint8_t> buf) {
+- assert_true(offset_ + buf.size() <= data_length_);
+- std::memcpy(buf.data(), data_ + offset_, buf.size());
++ if (offset_ > data_length_ || buf.size() > data_length_ - offset_) {
++ throw std::out_of_range("ByteStream read exceeds buffer");
++ }
++ if (!buf.empty()) {
++ std::memcpy(buf.data(), data_ + offset_, buf.size());
++ }
+ Advance(buf.size());
+ }
+
+ void ByteStream::Write(std::span<const uint8_t> buf) {
+- assert_true(offset_ + buf.size() <= data_length_);
+- std::memcpy(data_ + offset_, buf.data(), buf.size());
++ if (offset_ > data_length_ || buf.size() > data_length_ - offset_) {
++ throw std::out_of_range("ByteStream write exceeds buffer");
++ }
++ if (!buf.empty()) {
++ std::memcpy(data_ + offset_, buf.data(), buf.size());
++ }
+ Advance(buf.size());
+ }
+
+@@ -43,6 +54,9 @@ template <>
+ std::string ByteStream::Read() {
+ std::string str;
+ uint32_t len = Read<uint32_t>();
++ if (offset_ > data_length_ || len > data_length_ - offset_) {
++ throw std::out_of_range("ByteStream string exceeds buffer");
++ }
+ str.resize(len);
+ Read(std::span<uint8_t>(reinterpret_cast<uint8_t*>(str.data()), len));
+ return str;
+@@ -52,6 +66,9 @@ template <>
+ std::u16string ByteStream::Read() {
+ std::u16string str;
+ size_t len = Read<uint32_t>();
++ if (offset_ > data_length_ || len > (data_length_ - offset_) / sizeof(char16_t)) {
++ throw std::out_of_range("ByteStream UTF-16 string exceeds buffer");
++ }
+ str.resize(len);
+ Read(std::span<uint8_t>(reinterpret_cast<uint8_t*>(str.data()), len * sizeof(char16_t)));
+ return str;
diff --git a/src/core/perf/counter.cpp b/src/core/perf/counter.cpp
index 536009e..97f15f4 100644
--- a/src/core/perf/counter.cpp
@@ -829,7 +1131,7 @@ index a744375..5d1954e 100644
// Xenia-specific VdSwap hook.
diff --git a/src/graphics/d3d12/command_processor.cpp b/src/graphics/d3d12/command_processor.cpp
-index 19874a5..692f28e 100644
+index 19874a5..054a8f3 100644
--- a/src/graphics/d3d12/command_processor.cpp
+++ b/src/graphics/d3d12/command_processor.cpp
@@ -10,6 +10,7 @@
@@ -840,7 +1142,7 @@ index 19874a5..692f28e 100644
#include <cstdarg>
#include <cstring>
#include <sstream>
-@@ -35,6 +36,15 @@
+@@ -35,6 +36,18 @@
REXCVAR_DEFINE_BOOL(d3d12_bindless, true, "GPU/D3D12", "Use bindless resources where available")
.lifecycle(rex::cvar::Lifecycle::kRequiresRestart);
@@ -850,13 +1152,28 @@ index 19874a5..692f28e 100644
+REXCVAR_DEFINE_BOOL(d3d12_readback_short_wait, false, "GPU/D3D12",
+ "Poll full resolve fences briefly before sleeping");
+
++REXCVAR_DEFINE_UINT32(d3d12_readback_spin_us, 200, "GPU/D3D12",
++ "Maximum CPU polling time before the blocking full-readback wait");
++
+REXCVAR_DEFINE_UINT32(d3d12_resolve_readback_max_bytes, 0, "GPU/D3D12",
+ "Experimental CPU resolve readback size ceiling; zero preserves full readback");
+
REXCVAR_DEFINE_BOOL(d3d12_readback_memexport, false, "GPU/D3D12",
"Read data written by memory export in shaders on the CPU")
.lifecycle(rex::cvar::Lifecycle::kHotReload);
-@@ -2784,6 +2794,11 @@ bool D3D12CommandProcessor::IssueDraw_MemexportReadbackFastPath(uint32_t total_s
+@@ -1672,6 +1685,11 @@ void D3D12CommandProcessor::ShutdownContext() {
+ scratch_buffer_size_ = 0;
+ resolve_downscale_buffer_size_ = 0;
+ resolve_downscale_buffer_.Reset();
++ resolve_timing_readback_.Reset();
++ resolve_timing_query_heap_.Reset();
++ resolve_timing_frequency_ = 0;
++ resolve_timing_sample_counter_ = 0;
++ resolve_timing_submission_ = 0;
+
+ for (const std::pair<uint64_t, ID3D12Resource*>& resource_for_deletion :
+ resources_for_deletion_) {
+@@ -2784,6 +2802,11 @@ bool D3D12CommandProcessor::IssueDraw_MemexportReadbackFastPath(uint32_t total_s
MakeMemexportReadbackKey(memexport_ranges_.front().base_address_dwords, total_size);
ReadbackBuffer& readback = memexport_readback_buffers_[readback_key];
readback.last_used_frame = frame_current_;
@@ -868,7 +1185,7 @@ index 19874a5..692f28e 100644
auto ensure_readback_slot = [&](uint32_t index, uint32_t size) -> bool {
if (readback.buffers[index] && readback.mapped_data[index] && size <= readback.sizes[index]) {
-@@ -2847,11 +2862,13 @@ bool D3D12CommandProcessor::IssueDraw_MemexportReadbackFastPath(uint32_t total_s
+@@ -2847,11 +2870,13 @@ bool D3D12CommandProcessor::IssueDraw_MemexportReadbackFastPath(uint32_t total_s
}
readback.submission_written[write_index] = submission_current_;
readback.written_size[write_index] = total_size;
@@ -882,7 +1199,7 @@ index 19874a5..692f28e 100644
readback.submission_written[read_index] &&
readback.submission_written[read_index] <= submission_completed_;
if (!previous_slot_ready) {
-@@ -2887,6 +2904,20 @@ bool D3D12CommandProcessor::IssueCopy() {
+@@ -2887,6 +2912,54 @@ bool D3D12CommandProcessor::IssueCopy() {
}
bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
@@ -895,15 +1212,49 @@ index 19874a5..692f28e 100644
+ ResolveClock::time_point interval_start = ResolveClock::now();
+ uint64_t calls = 0, bytes = 0;
+ double total_ms = 0, wait_ms = 0, worst_ms = 0;
++ uint64_t gpu_samples = 0;
++ double gpu_resolve_ms = 0, gpu_downscale_ms = 0, gpu_copy_ms = 0;
++ uint64_t gpu_pre_resolve_samples = 0;
++ double gpu_pre_resolve_ms = 0;
+ std::unordered_map<uint64_t, Range> ranges;
+ };
+ static thread_local ResolveTiming timing;
+ const bool measure = REXCVAR_GET(log_resolve_timing);
+ const auto started = measure ? ResolveClock::now() : ResolveClock::time_point{};
++ bool gpu_sample = measure &&
++ GetReadbackResolveMode(REXCVAR_GET(d3d12_readback_resolve)) == ReadbackResolveMode::kFull &&
++ (++resolve_timing_sample_counter_ % 64 == 0);
++ if (gpu_sample && !resolve_timing_query_heap_) {
++ const auto& provider = GetD3D12Provider();
++ ID3D12Device* device = provider.GetDevice();
++ D3D12_QUERY_HEAP_DESC heap_desc = {};
++ heap_desc.Type = D3D12_QUERY_HEAP_TYPE_TIMESTAMP;
++ heap_desc.Count = 5;
++ D3D12_RESOURCE_DESC buffer_desc;
++ ui::d3d12::util::FillBufferResourceDesc(buffer_desc, sizeof(uint64_t) * 5,
++ D3D12_RESOURCE_FLAG_NONE);
++ if (FAILED(provider.GetDirectQueue()->GetTimestampFrequency(&resolve_timing_frequency_)) ||
++ !resolve_timing_frequency_ ||
++ FAILED(device->CreateQueryHeap(&heap_desc, IID_PPV_ARGS(&resolve_timing_query_heap_))) ||
++ FAILED(device->CreateCommittedResource(&ui::d3d12::util::kHeapPropertiesReadback,
++ provider.GetHeapFlagCreateNotZeroed(), &buffer_desc,
++ D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&resolve_timing_readback_)))) {
++ resolve_timing_query_heap_.Reset();
++ resolve_timing_readback_.Reset();
++ REXGPU_WARN("Resolve GPU timing resources unavailable; readback remains unchanged");
++ }
++ }
++ gpu_sample = gpu_sample && resolve_timing_query_heap_ && resolve_timing_readback_;
++ if (gpu_sample) {
++ deferred_command_list_.D3DEndQuery(resolve_timing_query_heap_.Get(),
++ D3D12_QUERY_TYPE_TIMESTAMP, 0);
++ }
++ const bool gpu_submission_sample = gpu_sample &&
++ resolve_timing_submission_ == submission_current_;
uint32_t written_address, written_length;
if (!render_target_cache_->Resolve(*memory_, *shared_memory_, *texture_cache_, written_address,
written_length)) {
-@@ -2897,6 +2928,14 @@ bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
+@@ -2897,14 +2970,34 @@ bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
return true;
}
@@ -918,7 +1269,12 @@ index 19874a5..692f28e 100644
if (!memory_->TranslatePhysical(written_address)) {
return true;
}
-@@ -2905,6 +2944,14 @@ bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
+
++ if (gpu_sample) {
++ deferred_command_list_.D3DEndQuery(resolve_timing_query_heap_.Get(),
++ D3D12_QUERY_TYPE_TIMESTAMP, 1);
++ }
+ bool is_scaled = texture_cache_->IsDrawResolutionScaled();
uint64_t resolve_key = MakeReadbackResolveKey(written_address, written_length);
ReadbackBuffer& rb = readback_buffers_[resolve_key];
rb.last_used_frame = frame_current_;
@@ -933,7 +1289,7 @@ index 19874a5..692f28e 100644
uint32_t write_index = rb.current_index;
uint32_t size = AlignReadbackBufferSize(written_length);
-@@ -2922,6 +2969,10 @@ bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
+@@ -2922,6 +3015,10 @@ bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
return true;
}
if (rb.buffers[write_index]) {
@@ -944,11 +1300,37 @@ index 19874a5..692f28e 100644
if (rb.mapped_data[write_index]) {
rb.buffers[write_index]->Unmap(0, nullptr);
rb.mapped_data[write_index] = nullptr;
-@@ -3069,14 +3120,24 @@ bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
+@@ -3055,6 +3152,10 @@ bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
+ PushTransitionBarrier(resolve_downscale_buffer_.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
+ D3D12_RESOURCE_STATE_COPY_SOURCE);
+ SubmitBarriers();
++ if (gpu_sample) {
++ deferred_command_list_.D3DEndQuery(resolve_timing_query_heap_.Get(),
++ D3D12_QUERY_TYPE_TIMESTAMP, 2);
++ }
+ deferred_command_list_.D3DCopyBufferRegion(rb.buffers[write_index], 0,
+ resolve_downscale_buffer_.Get(), 0, written_length);
+ PushTransitionBarrier(resolve_downscale_buffer_.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE,
+@@ -3065,20 +3166,62 @@ bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
+ shared_memory_->UseAsCopySource();
+ SubmitBarriers();
+ ID3D12Resource* shared_memory_buffer = shared_memory_->GetBuffer();
++ if (gpu_sample) {
++ deferred_command_list_.D3DEndQuery(resolve_timing_query_heap_.Get(),
++ D3D12_QUERY_TYPE_TIMESTAMP, 2);
++ }
+ deferred_command_list_.D3DCopyBufferRegion(rb.buffers[write_index], 0, shared_memory_buffer,
written_address, written_length);
}
- ReadbackResolveMode readback_mode = GetReadbackResolveMode(REXCVAR_GET(d3d12_readback_resolve));
++ if (gpu_sample) {
++ deferred_command_list_.D3DEndQuery(resolve_timing_query_heap_.Get(),
++ D3D12_QUERY_TYPE_TIMESTAMP, 3);
++ deferred_command_list_.D3DResolveQueryData(resolve_timing_query_heap_.Get(),
++ D3D12_QUERY_TYPE_TIMESTAMP, 0, gpu_submission_sample ? 5 : 4,
++ resolve_timing_readback_.Get(), 0);
++ }
+ rb.submission_written[write_index] = submission_current_;
+ rb.written_size[write_index] = written_length;
bool use_delayed_sync =
@@ -971,8 +1353,31 @@ index 19874a5..692f28e 100644
+ }
}
++ if (gpu_sample) {
++ // The existing full-readback wait also completes these timestamps.
++ void* mapping = nullptr;
++ D3D12_RANGE read_range = {0, sizeof(uint64_t) * (gpu_submission_sample ? 5 : 4)};
++ if (SUCCEEDED(resolve_timing_readback_->Map(0, &read_range, &mapping))) {
++ const auto* stamps = static_cast<const uint64_t*>(mapping);
++ if (stamps[0] <= stamps[1] && stamps[1] <= stamps[2] && stamps[2] <= stamps[3]) {
++ const double milliseconds_per_tick = 1000.0 / double(resolve_timing_frequency_);
++ timing.gpu_resolve_ms += double(stamps[1] - stamps[0]) * milliseconds_per_tick;
++ timing.gpu_downscale_ms += double(stamps[2] - stamps[1]) * milliseconds_per_tick;
++ timing.gpu_copy_ms += double(stamps[3] - stamps[2]) * milliseconds_per_tick;
++ ++timing.gpu_samples;
++ if (gpu_submission_sample && stamps[4] <= stamps[0]) {
++ timing.gpu_pre_resolve_ms += double(stamps[0] - stamps[4]) * milliseconds_per_tick;
++ ++timing.gpu_pre_resolve_samples;
++ }
++ }
++ D3D12_RANGE no_writes = {0, 0};
++ resolve_timing_readback_->Unmap(0, &no_writes);
++ }
++ }
bool is_cache_miss = false;
-@@ -3090,6 +3151,13 @@ bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
+ if (use_delayed_sync && (!rb.buffers[read_index] || written_length > rb.sizes[read_index] ||
+ !rb.mapped_data[read_index])) {
+@@ -3090,6 +3233,13 @@ bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
}
bool should_copy = (readback_mode == ReadbackResolveMode::kSome) ? is_cache_miss : true;
@@ -986,7 +1391,7 @@ index 19874a5..692f28e 100644
if (should_copy && rb.buffers[read_index] && written_length <= rb.sizes[read_index] &&
rb.mapped_data[read_index]) {
uint8_t* destination = memory_->TranslatePhysical(written_address);
-@@ -3099,10 +3167,43 @@ bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
+@@ -3099,10 +3249,67 @@ bool D3D12CommandProcessor::IssueCopy_ReadbackResolvePath() {
}
rb.current_index = 1 - rb.current_index;
@@ -1009,6 +1414,19 @@ index 19874a5..692f28e 100644
+ "wait={:.2f}ms worst={:.2f}ms bytes={} mode={}",
+ timing.calls, interval_s, timing.total_ms, timing.wait_ms,
+ timing.worst_ms, timing.bytes, int(readback_mode));
++ if (timing.gpu_samples) {
++ REXGPU_INFO("Resolve GPU timing: samples={} resolve={:.4f}ms downscale={:.4f}ms "
++ "copy={:.4f}ms (sample means; includes stage barriers)",
++ timing.gpu_samples, timing.gpu_resolve_ms / timing.gpu_samples,
++ timing.gpu_downscale_ms / timing.gpu_samples,
++ timing.gpu_copy_ms / timing.gpu_samples);
++ }
++ if (timing.gpu_pre_resolve_samples) {
++ REXGPU_INFO("Resolve GPU preceding work: samples={} queued={:.4f}ms "
++ "(submission start to resolve; sample mean)",
++ timing.gpu_pre_resolve_samples,
++ timing.gpu_pre_resolve_ms / timing.gpu_pre_resolve_samples);
++ }
+ std::vector<std::pair<uint64_t, ResolveTiming::Range>> hottest(
+ timing.ranges.begin(), timing.ranges.end());
+ std::sort(hottest.begin(), hottest.end(), [](const auto& a, const auto& b) {
@@ -1028,27 +1446,94 @@ index 19874a5..692f28e 100644
-void D3D12CommandProcessor::CheckSubmissionFence(uint64_t await_submission) {
+void D3D12CommandProcessor::CheckSubmissionFence(uint64_t await_submission,
+ bool short_readback_wait) {
++ // Separate command recording/submission cost from GPU fence waiting.
++ // Timing is diagnostic only and never changes completion requirements.
++ using WaitClock = std::chrono::steady_clock;
++ const bool measure_readback = short_readback_wait && REXCVAR_GET(log_resolve_timing);
++ struct ReadbackWaitStats {
++ WaitClock::time_point interval_start = WaitClock::now();
++ uint64_t calls = 0, polled_complete = 0, slept = 0;
++ double submit_ms = 0, poll_ms = 0, sleep_ms = 0, cleanup_ms = 0;
++ };
++ static thread_local ReadbackWaitStats wait_stats;
++ const auto phase_started = measure_readback ? WaitClock::now() : WaitClock::time_point{};
if (await_submission >= submission_current_) {
if (submission_open_) {
EndSubmission(false);
-@@ -3133,6 +3234,16 @@ void D3D12CommandProcessor::CheckSubmissionFence(uint64_t await_submission) {
+@@ -3114,9 +3321,9 @@ void D3D12CommandProcessor::CheckSubmissionFence(uint64_t await_submission) {
+ if (queue_operations_done_since_submission_signal_) {
+ UINT64 fence_value = ++queue_operations_since_submission_fence_last_;
+ ID3D12CommandQueue* direct_queue = GetD3D12Provider().GetDirectQueue();
+- if (SUCCEEDED(direct_queue->Signal(queue_operations_since_submission_fence_, fence_value) &&
+- SUCCEEDED(queue_operations_since_submission_fence_->SetEventOnCompletion(
+- fence_value, fence_completion_event_)))) {
++ if (SUCCEEDED(direct_queue->Signal(queue_operations_since_submission_fence_, fence_value)) &&
++ SUCCEEDED(queue_operations_since_submission_fence_->SetEventOnCompletion(
++ fence_value, fence_completion_event_))) {
+ PROFILE_CMD_BUFFER_STALL();
+ WaitForSingleObject(fence_completion_event_, INFINITE);
+ queue_operations_done_since_submission_signal_ = false;
+@@ -3131,8 +3338,22 @@ void D3D12CommandProcessor::CheckSubmissionFence(uint64_t await_submission) {
+ await_submission = submission_current_ - 1;
+ }
++ const auto submit_finished = measure_readback ? WaitClock::now() : WaitClock::time_point{};
uint64_t submission_completed_before = submission_completed_;
submission_completed_ = submission_fence_->GetCompletedValue();
+ if (short_readback_wait && submission_completed_ < await_submission) {
+ // Full readback still requires this exact submission. Avoid a kernel sleep
+ // for very short GPU work, but bound CPU polling before the normal wait.
-+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::microseconds(200);
++ const auto deadline = std::chrono::steady_clock::now() + std::chrono::microseconds(
++ std::min(uint32_t(1000), REXCVAR_GET(d3d12_readback_spin_us)));
+ do {
+ YieldProcessor();
+ submission_completed_ = submission_fence_->GetCompletedValue();
+ } while (submission_completed_ < await_submission &&
+ std::chrono::steady_clock::now() < deadline);
+ }
++ const auto poll_finished = measure_readback ? WaitClock::now() : WaitClock::time_point{};
++ const bool needs_sleep = submission_completed_ < await_submission;
if (submission_completed_ < await_submission) {
if (SUCCEEDED(
submission_fence_->SetEventOnCompletion(await_submission, fence_completion_event_))) {
-@@ -4432,7 +4543,7 @@ bool D3D12CommandProcessor::UpdateBindings(const D3D12Shader* vertex_shader,
+@@ -3144,6 +3365,23 @@ void D3D12CommandProcessor::CheckSubmissionFence(uint64_t await_submission) {
+ if (submission_completed_ < await_submission) {
+ REXGPU_ERROR("Failed to await a submission completion Direct3D 12 fence");
+ }
++ const auto wait_finished = measure_readback ? WaitClock::now() : WaitClock::time_point{};
++ if (measure_readback) {
++ ++wait_stats.calls;
++ wait_stats.polled_complete += !needs_sleep;
++ wait_stats.slept += needs_sleep;
++ wait_stats.submit_ms += std::chrono::duration<double, std::milli>(submit_finished - phase_started).count();
++ wait_stats.poll_ms += std::chrono::duration<double, std::milli>(poll_finished - submit_finished).count();
++ wait_stats.sleep_ms += std::chrono::duration<double, std::milli>(wait_finished - poll_finished).count();
++ if (wait_finished - wait_stats.interval_start >= std::chrono::seconds(5)) {
++ REXGPU_INFO("D3D12ReadbackWait: calls={} no_sleep={} slept={} submit={:.3f}ms poll={:.3f}ms sleep={:.3f}ms budget_us={}",
++ wait_stats.calls, wait_stats.polled_complete, wait_stats.slept,
++ wait_stats.submit_ms, wait_stats.poll_ms, wait_stats.sleep_ms,
++ std::min(uint32_t(1000), REXCVAR_GET(d3d12_readback_spin_us)));
++ wait_stats = ReadbackWaitStats{};
++ }
++ }
++
+ if (submission_completed_ <= submission_completed_before) {
+ // Not updated - no need to reclaim or download things.
+ return;
+@@ -3302,6 +3540,12 @@ bool D3D12CommandProcessor::BeginSubmission(bool is_guest_command) {
+ // end of the submission (when async pipeline creation requests are
+ // fulfilled).
+ deferred_command_list_.Reset();
++ if (resolve_timing_query_heap_ && REXCVAR_GET(log_resolve_timing) &&
++ GetReadbackResolveMode(REXCVAR_GET(d3d12_readback_resolve)) == ReadbackResolveMode::kFull) {
++ deferred_command_list_.D3DEndQuery(resolve_timing_query_heap_.Get(),
++ D3D12_QUERY_TYPE_TIMESTAMP, 4);
++ resolve_timing_submission_ = submission_current_;
++ }
+
+ // Reset cached state of the command list.
+ ff_viewport_update_needed_ = true;
+@@ -4432,7 +4676,7 @@ bool D3D12CommandProcessor::UpdateBindings(const D3D12Shader* vertex_shader,
for (size_t i = 0; i < texture_count_pixel; ++i) {
const D3D12Shader::TextureBinding& texture = (*textures_pixel)[i];
descriptor_indices[texture.bindless_descriptor_index] =
@@ -1057,7 +1542,7 @@ index 19874a5..692f28e 100644
uint32_t(SystemBindlessView::kUnboundedSRVsStart);
}
current_texture_layout_uid_pixel_ = texture_layout_uid_pixel;
-@@ -4755,7 +4866,10 @@ void D3D12CommandProcessor::EvictOldReadbackBuffers(
+@@ -4755,7 +4999,10 @@ void D3D12CommandProcessor::EvictOldReadbackBuffers(
ReadbackBuffer& readback = it->second;
bool evict =
buffer_map.size() > kMaxReadbackBuffers || readback.last_used_frame < eviction_frame_floor;
@@ -1069,6 +1554,112 @@ index 19874a5..692f28e 100644
++it;
continue;
}
+diff --git a/src/graphics/d3d12/pipeline_cache.cpp b/src/graphics/d3d12/pipeline_cache.cpp
+index 8e6b854..ab5a70b 100644
+--- a/src/graphics/d3d12/pipeline_cache.cpp
++++ b/src/graphics/d3d12/pipeline_cache.cpp
+@@ -11,6 +11,8 @@
+
+ #include "thirdparty/dxbc/DXBCChecksum.h"
+
++#include <d3d11shader.h>
++
+ #include <algorithm>
+ #include <atomic>
+ #include <cinttypes>
+@@ -78,6 +80,8 @@ namespace shaders {
+ #include "../shaders/bytecode/d3d12_5_1/discrete_triangle_3cp_hs.h"
+ #include "../shaders/bytecode/d3d12_5_1/float24_round_ps.h"
+ #include "../shaders/bytecode/d3d12_5_1/float24_truncate_ps.h"
++#include "../shaders/bytecode/d3d12_5_1/float24_round_ps_position_only.h"
++#include "../shaders/bytecode/d3d12_5_1/float24_truncate_ps_position_only.h"
+ #include "../shaders/bytecode/d3d12_5_1/tessellation_adaptive_vs.h"
+ #include "../shaders/bytecode/d3d12_5_1/tessellation_indexed_vs.h"
+ } // namespace shaders
+@@ -2843,11 +2847,23 @@ ID3D12PipelineState* PipelineCache::CreateD3D12Pipeline(
+ (description.depth_func != xenos::CompareFunction::kAlways || description.depth_write) &&
+ description.depth_format == xenos::DepthRenderTargetFormat::kD24FS8) {
+ if (render_target_cache_.depth_float24_round()) {
+- state_desc.PS.pShaderBytecode = shaders::float24_round_ps;
+- state_desc.PS.BytecodeLength = sizeof(shaders::float24_round_ps);
++ if (!DxbcShaderTranslator::Modification(description.vertex_shader_modification)
++ .vertex.interpolator_mask) {
++ state_desc.PS.pShaderBytecode = shaders::float24_round_ps_position_only;
++ state_desc.PS.BytecodeLength = sizeof(shaders::float24_round_ps_position_only);
++ } else {
++ state_desc.PS.pShaderBytecode = shaders::float24_round_ps;
++ state_desc.PS.BytecodeLength = sizeof(shaders::float24_round_ps);
++ }
+ } else {
+- state_desc.PS.pShaderBytecode = shaders::float24_truncate_ps;
+- state_desc.PS.BytecodeLength = sizeof(shaders::float24_truncate_ps);
++ if (!DxbcShaderTranslator::Modification(description.vertex_shader_modification)
++ .vertex.interpolator_mask) {
++ state_desc.PS.pShaderBytecode = shaders::float24_truncate_ps_position_only;
++ state_desc.PS.BytecodeLength = sizeof(shaders::float24_truncate_ps_position_only);
++ } else {
++ state_desc.PS.pShaderBytecode = shaders::float24_truncate_ps;
++ state_desc.PS.BytecodeLength = sizeof(shaders::float24_truncate_ps);
++ }
+ }
+ }
+ }
+@@ -3028,8 +3044,53 @@ ID3D12PipelineState* PipelineCache::CreateD3D12Pipeline(
+
+ // Create the D3D12 pipeline state object.
+ ID3D12Device* device = command_processor_.GetD3D12Provider().GetDevice();
+- ID3D12PipelineState* state;
+- if (FAILED(device->CreateGraphicsPipelineState(&state_desc, IID_PPV_ARGS(&state)))) {
++ ID3D12PipelineState* state = nullptr;
++ const HRESULT create_result =
++ device->CreateGraphicsPipelineState(&state_desc, IID_PPV_ARGS(&state));
++ if (FAILED(create_result)) {
++ // Inspect linkage only after a failure, using the compiler already loaded
++ // by the provider. This avoids changing device or pipeline configuration.
++ using ReflectFn = HRESULT(WINAPI*)(LPCVOID, SIZE_T, REFIID, void**);
++ const HMODULE compiler_module = GetModuleHandleW(L"D3DCompiler_47.dll");
++ const auto reflect = compiler_module ? reinterpret_cast<ReflectFn>(
++ GetProcAddress(compiler_module, "D3DReflect")) : nullptr;
++ if (reflect) {
++ const auto log_signature = [&](const char* stage,
++ D3D12_SHADER_BYTECODE bytecode, bool output) {
++ if (!bytecode.BytecodeLength) return;
++ Microsoft::WRL::ComPtr<ID3D11ShaderReflection> reflection;
++ if (FAILED(reflect(bytecode.pShaderBytecode, bytecode.BytecodeLength,
++ IID_PPV_ARGS(&reflection)))) return;
++ D3D11_SHADER_DESC shader_desc{};
++ if (FAILED(reflection->GetDesc(&shader_desc))) return;
++ const UINT count = output ? shader_desc.OutputParameters : shader_desc.InputParameters;
++ for (UINT i = 0; i < std::min(count, UINT(64)); ++i) {
++ D3D11_SIGNATURE_PARAMETER_DESC parameter{};
++ const HRESULT result = output ? reflection->GetOutputParameterDesc(i, &parameter)
++ : reflection->GetInputParameterDesc(i, &parameter);
++ if (SUCCEEDED(result)) {
++ REXGPU_ERROR("D3D12 failed pipeline signature: stage={} semantic={}{} register={} mask={} used={} type={}",
++ stage, parameter.SemanticName, parameter.SemanticIndex, parameter.Register,
++ uint32_t(parameter.Mask), uint32_t(parameter.ReadWriteMask),
++ uint32_t(parameter.ComponentType));
++ }
++ }
++ };
++ log_signature("VS-output", state_desc.VS, true);
++ log_signature("GS-output", state_desc.GS, true);
++ log_signature("PS-input", state_desc.PS, false);
++ }
++ REXGPU_ERROR(
++ "D3D12 pipeline failure: HRESULT=0x{:08X} device_reason=0x{:08X} "
++ "samples={} native_2x={} rtv_count={} dsv_format={} depth={} stencil={} "
++ "cull_mode={} vs_bytes={} ps_bytes={} gs_bytes={}",
++ uint32_t(create_result), uint32_t(device->GetDeviceRemovedReason()),
++ state_desc.SampleDesc.Count, render_target_cache_.msaa_2x_supported(),
++ state_desc.NumRenderTargets, uint32_t(state_desc.DSVFormat),
++ bool(state_desc.DepthStencilState.DepthEnable),
++ bool(state_desc.DepthStencilState.StencilEnable), uint32_t(description.cull_mode),
++ state_desc.VS.BytecodeLength, state_desc.PS.BytecodeLength,
++ state_desc.GS.BytecodeLength);
+ if (runtime_description.pixel_shader != nullptr) {
+ REXGPU_ERROR("Failed to create graphics pipeline with VS {:016X}, PS {:016X}",
+ runtime_description.vertex_shader->shader().ucode_data_hash(),
diff --git a/src/graphics/d3d12/render_target_cache.cpp b/src/graphics/d3d12/render_target_cache.cpp
index dd321a5..544275c 100644
--- a/src/graphics/d3d12/render_target_cache.cpp
@@ -1085,7 +1676,7 @@ index dd321a5..544275c 100644
TryResolveCopyDirectly(resolve_info, copy_shader, draw_resolution_scaled);
if (direct_resolved) {
diff --git a/src/graphics/d3d12/texture_cache.cpp b/src/graphics/d3d12/texture_cache.cpp
-index 2be0e8e..8a832ec 100644
+index 2be0e8e..05b54f5 100644
--- a/src/graphics/d3d12/texture_cache.cpp
+++ b/src/graphics/d3d12/texture_cache.cpp
@@ -14,11 +14,15 @@
@@ -1279,7 +1870,38 @@ index 2be0e8e..8a832ec 100644
DeferredCommandList& command_list = command_processor_.GetDeferredCommandList();
ID3D12Device* device = command_processor_.GetD3D12Provider().GetDevice();
-@@ -1982,6 +2120,22 @@ ID3D12Resource* D3D12TextureCache::D3D12Texture::GetOrCreate3DAs2DResource(
+@@ -1634,14 +1772,14 @@ bool D3D12TextureCache::LoadTextureDataFromResidentMemoryImpl(Texture& texture,
+ host_x_blocks_per_thread *= block_width;
+ }
+ UINT64 copy_buffer_size = 0;
+- D3D12_PLACED_SUBRESOURCE_FOOTPRINT host_slice_layout_base;
+- UINT64 host_slice_size_base;
++ D3D12_PLACED_SUBRESOURCE_FOOTPRINT host_slice_layout_base{};
++ UINT64 host_slice_size_base = 0;
+ // Indexing is the same as for guest stored mips:
+ // 1...min(level_last, level_packed) if level_packed is not 0, or only 0 if
+ // level_packed == 0.
+ D3D12_PLACED_SUBRESOURCE_FOOTPRINT
+- host_slice_layouts_mips[xenos::kTextureMaxMips];
+- UINT64 host_slice_sizes_mips[xenos::kTextureMaxMips];
++ host_slice_layouts_mips[xenos::kTextureMaxMips]{};
++ UINT64 host_slice_sizes_mips[xenos::kTextureMaxMips]{};
+ // Using custom calculations instead of GetCopyableFootprints because
+ // shaders may unconditionally copy multiple blocks along X per thread for
+ // simplicity, to make sure all rows (also including the last one -
+@@ -1688,6 +1826,11 @@ bool D3D12TextureCache::LoadTextureDataFromResidentMemoryImpl(Texture& texture,
+ (is_base ? host_slice_size_base : host_slice_sizes_mips[level]) = level_host_slice_size;
+ copy_buffer_size += level_host_slice_size * array_size;
+ }
++ if (!copy_buffer_size || copy_buffer_size > UINT32_MAX) {
++ REXLOG_ERROR("Texture upload buffer size {} exceeds the supported range",
++ copy_buffer_size);
++ return false;
++ }
+ D3D12_RESOURCE_STATES copy_buffer_state = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
+ ID3D12Resource* copy_buffer =
+ command_processor_.RequestScratchGPUBuffer(uint32_t(copy_buffer_size), copy_buffer_state);
+@@ -1982,6 +2125,22 @@ ID3D12Resource* D3D12TextureCache::D3D12Texture::GetOrCreate3DAs2DResource(
auto& d3d12_cache = static_cast<D3D12TextureCache&>(texture_cache());
if (texture_3d_as_2d_) {
@@ -1302,7 +1924,7 @@ index 2be0e8e..8a832ec 100644
d3d12_cache.command_processor_.PushTransitionBarrier(
texture_3d_as_2d_->resource(), texture_3d_as_2d_->SetResourceState(end_state), end_state);
return texture_3d_as_2d_->resource();
-@@ -2051,6 +2205,18 @@ uint32_t D3D12TextureCache::FindOrCreateTextureDescriptor(D3D12Texture& texture,
+@@ -2051,6 +2210,18 @@ uint32_t D3D12TextureCache::FindOrCreateTextureDescriptor(D3D12Texture& texture,
PROFILE_TEXTURE_CACHE_MISS();
TextureKey texture_key = texture.key();
@@ -1322,10 +1944,26 @@ index 2be0e8e..8a832ec 100644
// Create a new bindless or cached descriptor if supported.
D3D12_SHADER_RESOURCE_VIEW_DESC desc = {};
diff --git a/src/graphics/graphics_system.cpp b/src/graphics/graphics_system.cpp
-index 8f2fcb0..926ca4e 100644
+index 8f2fcb0..d3cf8f3 100644
--- a/src/graphics/graphics_system.cpp
+++ b/src/graphics/graphics_system.cpp
-@@ -39,6 +39,9 @@ REXCVAR_DEFINE_BOOL(store_shaders, true, "GPU",
+@@ -1,3 +1,4 @@
++#include <rex/ui/presenter.h>
+ /**
+ ******************************************************************************
+ * Xenia : Xbox 360 Emulator Research Project *
+@@ -31,6 +32,10 @@
+ #include <rex/ui/window.h>
+ #include <rex/ui/windowed_app_context.h>
+
++#if REX_PLATFORM_WIN32
++#include "../core/platform_win.h"
++#endif
++
+ REXCVAR_DEFINE_STRING(swap_post_effect, "none", "GPU", "Swap post effect: none, fxaa, fxaa_extreme")
+ .allowed({"none", "fxaa", "fxaa_extreme"})
+ .lifecycle(rex::cvar::Lifecycle::kRequiresRestart);
+@@ -39,6 +44,9 @@ REXCVAR_DEFINE_BOOL(store_shaders, true, "GPU",
"Store shaders persistently and load them when loading games to avoid "
"runtime spikes and freezes when playing the game not for the first time.");
@@ -1335,8 +1973,54 @@ index 8f2fcb0..926ca4e 100644
namespace {
rex::graphics::CommandProcessor::SwapPostEffect ParseSwapPostEffect(
-@@ -161,7 +164,8 @@ X_STATUS GraphicsSystem::SetupGuestGpu(runtime::FunctionDispatcher* function_dis
+@@ -157,15 +165,75 @@ X_STATUS GraphicsSystem::SetupGuestGpu(runtime::FunctionDispatcher* function_dis
+ uint64_t vsync_interval_ticks =
+ std::max(uint64_t(1), uint64_t(double(guest_tick_frequency) / refresh_rate_hz));
+ uint64_t no_vsync_interval_ticks = std::max(uint64_t(1), guest_tick_frequency / 1000);
++#if REX_PLATFORM_WIN32
++ // Wait for the next guest deadline without changing the selected rate.
++ // Older Windows versions fall back to the existing polling sleep.
++ std::unique_ptr<void, decltype(&::CloseHandle)> precise_timer(
++ ::CreateWaitableTimerExW(nullptr, nullptr, 0x00000002,
++ TIMER_MODIFY_STATE | SYNCHRONIZE), &::CloseHandle);
++#endif
+ uint64_t last_frame_time = chrono::Clock::QueryGuestTickCount();
++ uint64_t monitor_report_time = last_frame_time;
++ uint64_t monitor_waits = 0;
++ uint64_t monitor_recovered_ticks = 0;
++ uint64_t monitor_max_elapsed_ticks = 0;
while (vsync_worker_running_) {
++ // Share the physical display clock only when the selected mode matches.
++ // Unlocked or time-scaled guests retain the existing timer behavior.
++ if (REXCVAR_GET(vsync) &&
++ chrono::Clock::guest_time_scalar() == 1.0 && presenter_ &&
++ presenter_->WaitForMonitorVBlank(refresh_rate_hz)) {
++ if (!vsync_worker_running_) break;
++ const uint64_t monitor_time = chrono::Clock::QueryGuestTickCount();
++ const uint64_t elapsed_ticks = monitor_time - last_frame_time;
++ // Native waits can span multiple refresh cycles when this worker
++ // is descheduled. Preserve elapsed guest vblanks just as the timer
++ // fallback does, instead of slowing the guest clock under load.
++ const uint64_t elapsed_vblanks = std::max(uint64_t(1),
++ (elapsed_ticks + vsync_interval_ticks / 2) / vsync_interval_ticks);
++ ++monitor_waits;
++ monitor_recovered_ticks += elapsed_vblanks - 1;
++ monitor_max_elapsed_ticks = std::max(monitor_max_elapsed_ticks, elapsed_ticks);
++ // Measure before dispatch: interrupt execution time belongs to the
++ // next interval and must not be discarded from elapsed time.
++ last_frame_time = monitor_time;
++ for (uint64_t i = 0; i < elapsed_vblanks && vsync_worker_running_; ++i) {
++ MarkVblank();
++ }
++ if (monitor_time - monitor_report_time >= guest_tick_frequency * 5) {
++ REXLOG_INFO("MonitorVblankTiming: waits={} recovered_ticks={} max_interval_ms={:.3f}",
++ monitor_waits, monitor_recovered_ticks,
++ double(monitor_max_elapsed_ticks) * 1000.0 / double(guest_tick_frequency));
++ monitor_report_time = monitor_time;
++ monitor_waits = monitor_recovered_ticks = monitor_max_elapsed_ticks = 0;
++ }
++ continue;
++ }
uint64_t current_time = chrono::Clock::QueryGuestTickCount();
uint64_t interval_ticks =
- REXCVAR_GET(vsync) ? vsync_interval_ticks : no_vsync_interval_ticks;
@@ -1345,6 +2029,46 @@ index 8f2fcb0..926ca4e 100644
while (current_time - last_frame_time >= interval_ticks) {
MarkVblank();
last_frame_time += interval_ticks;
+ }
++#if REX_PLATFORM_WIN32
++ if (precise_timer) {
++ current_time = chrono::Clock::QueryGuestTickCount();
++ const uint64_t elapsed_ticks = current_time - last_frame_time;
++ if (elapsed_ticks >= interval_ticks) continue;
++ const double scalar = std::max(0.001, chrono::Clock::guest_time_scalar());
++ const double remaining_seconds =
++ double(interval_ticks - elapsed_ticks) / double(guest_tick_frequency) / scalar;
++ LARGE_INTEGER due_time;
++ due_time.QuadPart = -std::max(int64_t(1), int64_t(
++ std::min(remaining_seconds, 0.020) * 10000000.0));
++ if (::SetWaitableTimer(precise_timer.get(), &due_time, 0, nullptr, nullptr, FALSE) &&
++ ::WaitForSingleObject(precise_timer.get(), 50) == WAIT_OBJECT_0) {
++ continue;
++ }
++ }
++#endif
+ rex::thread::Sleep(std::chrono::milliseconds(1));
+ }
+ return 0;
+@@ -180,8 +248,8 @@ X_STATUS GraphicsSystem::SetupGuestGpu(runtime::FunctionDispatcher* function_dis
+
+ void GraphicsSystem::Shutdown() {
+ if (command_processor_) {
++ // Keep the object alive while vblank may still increment its counter.
+ command_processor_->Shutdown();
+- command_processor_.reset();
+ }
+
+ if (vsync_worker_thread_) {
+@@ -190,6 +258,8 @@ void GraphicsSystem::Shutdown() {
+ vsync_worker_thread_.reset();
+ }
+
++ command_processor_.reset();
++
+ if (presenter_) {
+ if (app_context_) {
+ app_context_->CallInUIThreadSynchronous([this]() { presenter_.reset(); });
diff --git a/src/graphics/pipeline/shader/dxbc_translator_fetch.cpp b/src/graphics/pipeline/shader/dxbc_translator_fetch.cpp
index 31de175..267f7da 100644
--- a/src/graphics/pipeline/shader/dxbc_translator_fetch.cpp
@@ -1392,7 +2116,7 @@ index 3027dc8..54f77a9 100644
REXCVAR_DEFINE_BOOL(execute_unclipped_draw_vs_on_cpu_with_scissor, false, "GPU",
diff --git a/src/graphics/vulkan/command_processor.cpp b/src/graphics/vulkan/command_processor.cpp
-index 001f36b..e172691 100644
+index 001f36b..8f35864 100644
--- a/src/graphics/vulkan/command_processor.cpp
+++ b/src/graphics/vulkan/command_processor.cpp
@@ -11,6 +11,7 @@
@@ -1411,10 +2135,19 @@ index 001f36b..e172691 100644
#include <rex/math.h>
#include <rex/graphics/util/draw.h>
#include <rex/graphics/flags.h>
-@@ -47,6 +49,12 @@
+@@ -44,9 +46,21 @@
+ #include <rex/memory/utils.h>
+ #include <rex/ui/flags.h>
+ #include <rex/ui/vulkan/presenter.h>
++#include <rex/ui/vulkan/fence_wait_timing.h>
#include <rex/ui/vulkan/util.h>
// Legacy backend compatibility aliases for shared readback controls.
++REXCVAR_DEFINE_BOOL(vulkan_readback_short_wait, false, "GPU/Vulkan",
++ "Poll the final resolve fence briefly before the blocking wait");
++REXCVAR_DEFINE_UINT32(vulkan_readback_spin_us, 200, "GPU/Vulkan",
++ "Maximum CPU polling time before the blocking full-readback wait");
++
+REXCVAR_DEFINE_BOOL(vulkan_log_sync_timing, false, "GPU/Vulkan",
+ "Measure submission CPU time, fence waits and GPU execution without extra waits");
+
@@ -1424,7 +2157,7 @@ index 001f36b..e172691 100644
REXCVAR_DEFINE_BOOL(vulkan_readback_resolve, false, "GPU/Vulkan",
"Read render-to-texture results on the CPU")
.lifecycle(rex::cvar::Lifecycle::kHotReload);
-@@ -2059,10 +2067,16 @@ void VulkanCommandProcessor::ShutdownContext() {
+@@ -2059,10 +2073,16 @@ void VulkanCommandProcessor::ShutdownContext() {
deferred_command_buffer_.Reset();
for (const auto& command_buffer_pair : command_buffers_submitted_) {
@@ -1441,7 +2174,16 @@ index 001f36b..e172691 100644
dfn.vkDestroyCommandPool(device, command_buffer.pool, nullptr);
}
command_buffers_writable_.clear();
-@@ -4154,6 +4168,8 @@ bool VulkanCommandProcessor::IssueDraw(xenos::PrimitiveType prim_type, uint32_t
+@@ -3822,7 +3842,7 @@ bool VulkanCommandProcessor::IssueDraw(xenos::PrimitiveType prim_type, uint32_t
+ uint64_t sampler_overflow_await_submission =
+ texture_cache_->GetSubmissionToAwaitOnSamplerOverflow(samplers_overflowed_count);
+ assert_true(sampler_overflow_await_submission <= GetCurrentSubmission());
+- CheckSubmissionFenceAndDeviceLoss(sampler_overflow_await_submission);
++ CheckSubmissionFenceAndDeviceLoss(sampler_overflow_await_submission, "resource_reuse");
+ }
+
+ uint32_t normalized_color_mask =
+@@ -4154,6 +4174,8 @@ bool VulkanCommandProcessor::IssueDraw(xenos::PrimitiveType prim_type, uint32_t
0, 0, 0);
}
@@ -1450,7 +2192,25 @@ index 001f36b..e172691 100644
// Invalidate textures in memexported memory and watch for changes.
if (!memexport_ranges_.empty()) {
for (const draw_util::MemExportRange& memexport_range : memexport_ranges_) {
-@@ -4381,6 +4397,11 @@ bool VulkanCommandProcessor::IssueDraw_MemexportReadbackFastPath(uint32_t total_
+@@ -4222,7 +4244,7 @@ bool VulkanCommandProcessor::IssueDraw_MemexportReadbackFullPath(uint32_t total_
+ VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT,
+ VK_ACCESS_HOST_READ_BIT);
+
+- if (!AwaitAllQueueOperationsCompletion()) {
++ if (!AwaitAllQueueOperationsCompletion("memexport")) {
+ REXGPU_ERROR("Failed to await completion of Vulkan memexport readback");
+ dfn.vkDestroyBuffer(device, readback_buffer, nullptr);
+ dfn.vkFreeMemory(device, readback_memory, nullptr);
+@@ -4297,7 +4319,7 @@ bool VulkanCommandProcessor::IssueDraw_MemexportReadbackFastPath(uint32_t total_
+ }
+
+ if (readback.buffers[index] != VK_NULL_HANDLE || readback.memories[index] != VK_NULL_HANDLE) {
+- if (!AwaitAllQueueOperationsCompletion()) {
++ if (!AwaitAllQueueOperationsCompletion("resource_reuse")) {
+ dfn.vkUnmapMemory(device, new_memory);
+ dfn.vkDestroyBuffer(device, new_buffer, nullptr);
+ dfn.vkFreeMemory(device, new_memory, nullptr);
+@@ -4381,6 +4403,11 @@ bool VulkanCommandProcessor::IssueDraw_MemexportReadbackFastPath(uint32_t total_
return true;
}
@@ -1462,7 +2222,16 @@ index 001f36b..e172691 100644
bool VulkanCommandProcessor::IssueCopy() {
#if XE_GPU_FINE_GRAINED_DRAW_SCOPES
SCOPE_profile_cpu_f("gpu");
-@@ -4515,7 +4536,20 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
+@@ -4448,7 +4475,7 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
+ }
+
+ if (readback.buffers[index] != VK_NULL_HANDLE || readback.memories[index] != VK_NULL_HANDLE) {
+- if (!AwaitAllQueueOperationsCompletion()) {
++ if (!AwaitAllQueueOperationsCompletion("resource_reuse")) {
+ dfn.vkUnmapMemory(device, new_memory);
+ dfn.vkDestroyBuffer(device, new_buffer, nullptr);
+ dfn.vkFreeMemory(device, new_memory, nullptr);
+@@ -4515,7 +4542,20 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
}
VkBuffer scaled_resolve_buffer = texture_cache_->scaled_resolve_buffer();
@@ -1484,7 +2253,16 @@ index 001f36b..e172691 100644
return true;
}
-@@ -4561,8 +4595,8 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
+@@ -4533,7 +4573,7 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
+ }
+ if (resolve_downscale_buffer_ != VK_NULL_HANDLE ||
+ resolve_downscale_buffer_memory_ != VK_NULL_HANDLE) {
+- if (!AwaitAllQueueOperationsCompletion()) {
++ if (!AwaitAllQueueOperationsCompletion("resource_reuse")) {
+ dfn.vkDestroyBuffer(device, new_buffer, nullptr);
+ dfn.vkFreeMemory(device, new_memory, nullptr);
+ return true;
+@@ -4561,8 +4601,8 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
VkDescriptorBufferInfo buffer_infos[2] = {};
buffer_infos[0].buffer = scaled_resolve_buffer;
@@ -1495,7 +2273,7 @@ index 001f36b..e172691 100644
buffer_infos[1].buffer = resolve_downscale_buffer_;
buffer_infos[1].offset = 0;
buffer_infos[1].range = written_length;
-@@ -4601,7 +4635,7 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
+@@ -4601,7 +4641,7 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
constants.scale_y = texture_cache_->draw_resolution_scale_y();
constants.pixel_size_log2 = pixel_size_log2;
constants.tile_count = tile_count;
@@ -1504,7 +2282,7 @@ index 001f36b..e172691 100644
constants.half_pixel_offset = (REXCVAR_GET(readback_resolve_half_pixel_offset) &&
(constants.scale_x > 1 || constants.scale_y > 1))
? 1u
-@@ -4649,6 +4683,10 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
+@@ -4649,12 +4689,16 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT,
VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT);
@@ -1515,7 +2293,20 @@ index 001f36b..e172691 100644
bool use_delayed_sync =
readback_mode == ReadbackResolveMode::kFast || readback_mode == ReadbackResolveMode::kSome;
uint32_t read_index = write_index;
-@@ -4669,6 +4707,33 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
+ if (use_delayed_sync) {
+ read_index = 1 - write_index;
+- } else if (!AwaitAllQueueOperationsCompletion()) {
++ } else if (!AwaitAllQueueOperationsCompletion("resolve")) {
+ return true;
+ }
+
+@@ -4664,11 +4708,38 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
+ readback.mapped_data[read_index] == nullptr)) {
+ is_cache_miss = true;
+ read_index = write_index;
+- if (!AwaitAllQueueOperationsCompletion()) {
++ if (!AwaitAllQueueOperationsCompletion("resolve")) {
+ return true;
}
}
@@ -1549,7 +2340,7 @@ index 001f36b..e172691 100644
bool should_copy = (readback_mode == ReadbackResolveMode::kSome) ? is_cache_miss : true;
if (should_copy && readback.buffers[read_index] != VK_NULL_HANDLE &&
written_length <= readback.sizes[read_index] && readback.mapped_data[read_index] != nullptr) {
-@@ -4682,6 +4747,28 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
+@@ -4682,6 +4753,28 @@ bool VulkanCommandProcessor::IssueCopy_ReadbackResolvePath() {
uint8_t* destination = memory_->TranslatePhysical(written_address);
if (destination) {
std::memcpy(destination, readback.mapped_data[read_index], written_length);
@@ -1578,15 +2369,26 @@ index 001f36b..e172691 100644
}
}
-@@ -4944,6 +5031,7 @@ void VulkanCommandProcessor::WriteGuestOcclusionResult(uint32_t sample_count_add
+@@ -4886,7 +4979,7 @@ bool VulkanCommandProcessor::EndGuestOcclusionQuery(uint32_t sample_count_addres
+ if (!EndSubmission(false)) {
+ return false;
+ }
+- if (!AwaitAllQueueOperationsCompletion()) {
++ if (!AwaitAllQueueOperationsCompletion("occlusion")) {
+ return false;
+ }
+
+@@ -4943,7 +5036,8 @@ void VulkanCommandProcessor::WriteGuestOcclusionResult(uint32_t sample_count_add
+ sample_counts->StencilFail_B = 0;
}
- void VulkanCommandProcessor::CheckSubmissionFenceAndDeviceLoss(uint64_t await_submission) {
+-void VulkanCommandProcessor::CheckSubmissionFenceAndDeviceLoss(uint64_t await_submission) {
++void VulkanCommandProcessor::CheckSubmissionFenceAndDeviceLoss(uint64_t await_submission, const char* reason) {
+ const bool measure = REXCVAR_GET(vulkan_log_sync_timing);
// Only report once, no need to retry a wait that won't succeed anyway.
if (device_lost_) {
return;
-@@ -4951,7 +5039,12 @@ void VulkanCommandProcessor::CheckSubmissionFenceAndDeviceLoss(uint64_t await_su
+@@ -4951,7 +5045,12 @@ void VulkanCommandProcessor::CheckSubmissionFenceAndDeviceLoss(uint64_t await_su
if (await_submission >= GetCurrentSubmission()) {
if (submission_open_) {
@@ -1599,15 +2401,48 @@ index 001f36b..e172691 100644
}
// A submission won't be ended if it hasn't been started, or if ending
// has failed - clamp the index.
-@@ -4970,9 +5063,15 @@ void VulkanCommandProcessor::CheckSubmissionFenceAndDeviceLoss(uint64_t await_su
- // defined by vkQueueSubmit additionally include in the first
- // synchronization scope all commands that occur earlier in submission
- // order."
+@@ -4965,14 +5064,40 @@ void VulkanCommandProcessor::CheckSubmissionFenceAndDeviceLoss(uint64_t await_su
+ size_t fences_total = submissions_in_flight_fences_.size();
+ size_t fences_awaited = 0;
+ if (await_submission > submission_completed_) {
+- // Await in a blocking way if requested.
+- // TODO(Triang3l): Await only one fence. "Fence signal operations that are
+- // defined by vkQueueSubmit additionally include in the first
+- // synchronization scope all commands that occur earlier in submission
+- // order."
+- VkResult wait_result =
+- dfn.vkWaitForFences(device, uint32_t(await_submission - submission_completed_),
+- submissions_in_flight_fences_.data(), VK_TRUE, UINT64_MAX);
++ // Every tracked submission is sent to graphics_compute queue 0. The final
++ // submission fence includes preceding submissions on that same queue.
++ const size_t await_count = size_t(await_submission - submission_completed_);
++ assert_true(await_count <= fences_total);
++ const VkFence target_fence = submissions_in_flight_fences_[await_count - 1];
+ const auto wait_started = std::chrono::steady_clock::now();
+ PROFILE_CMD_BUFFER_STALL();
- VkResult wait_result =
- dfn.vkWaitForFences(device, uint32_t(await_submission - submission_completed_),
- submissions_in_flight_fences_.data(), VK_TRUE, UINT64_MAX);
++ VkResult wait_result;
++ {
++ using Timing = ui::vulkan::FenceWaitTiming;
++ Timing::Reason wait_reason = Timing::Reason::Other;
++ if (std::strcmp(reason, "resolve") == 0) wait_reason = Timing::Reason::Resolve;
++ else if (std::strcmp(reason, "resource_reuse") == 0) wait_reason = Timing::Reason::ResourceReuse;
++ else if (std::strcmp(reason, "memexport") == 0) wait_reason = Timing::Reason::Memexport;
++ else if (std::strcmp(reason, "frame_reuse") == 0) wait_reason = Timing::Reason::FrameReuse;
++ else if (std::strcmp(reason, "occlusion") == 0) wait_reason = Timing::Reason::Occlusion;
++ Timing timing("guest", this, wait_reason, await_submission - submission_completed_);
++ wait_result = dfn.vkGetFenceStatus(device, target_fence);
++ if (wait_result == VK_NOT_READY && wait_reason == Timing::Reason::Resolve &&
++ REXCVAR_GET(vulkan_readback_short_wait)) {
++ const auto deadline = std::chrono::steady_clock::now() +
++ std::chrono::microseconds(std::min(uint32_t(1000), REXCVAR_GET(vulkan_readback_spin_us)));
++ do {
++ wait_result = dfn.vkGetFenceStatus(device, target_fence);
++ } while (wait_result == VK_NOT_READY && std::chrono::steady_clock::now() < deadline);
++ }
++ if (wait_result == VK_NOT_READY) {
++ wait_result = dfn.vkWaitForFences(device, 1, &target_fence, VK_TRUE, UINT64_MAX);
++ }
++ }
+ if (measure) {
+ timing_wait_ms_ += std::chrono::duration<double, std::milli>(
+ std::chrono::steady_clock::now() - wait_started).count();
@@ -1615,7 +2450,7 @@ index 001f36b..e172691 100644
if (wait_result == VK_SUCCESS) {
fences_awaited += await_submission - submission_completed_;
} else {
-@@ -5032,11 +5131,35 @@ void VulkanCommandProcessor::CheckSubmissionFenceAndDeviceLoss(uint64_t await_su
+@@ -5032,11 +5157,35 @@ void VulkanCommandProcessor::CheckSubmissionFenceAndDeviceLoss(uint64_t await_su
if (command_buffer_pair.first > submission_completed_) {
break;
}
@@ -1651,7 +2486,16 @@ index 001f36b..e172691 100644
primitive_processor_->CompletedSubmissionUpdated();
-@@ -5284,6 +5407,9 @@ bool VulkanCommandProcessor::EndSubmission(bool is_swap) {
+@@ -5111,7 +5260,7 @@ bool VulkanCommandProcessor::BeginSubmission(bool is_guest_command) {
+ // is still available, and whether the await was successful.
+ uint64_t await_submission =
+ is_opening_frame ? closed_frame_submissions_[frame_current_ % kMaxFramesInFlight] : 0;
+- CheckSubmissionFenceAndDeviceLoss(await_submission);
++ CheckSubmissionFenceAndDeviceLoss(await_submission, "frame_reuse");
+ if (device_lost_ || submission_completed_ < await_submission) {
+ return false;
+ }
+@@ -5284,6 +5433,9 @@ bool VulkanCommandProcessor::EndSubmission(bool is_swap) {
if (dfn.vkAllocateCommandBuffers(device, &command_buffer_allocate_info,
&command_buffer.buffer) != VK_SUCCESS) {
REXGPU_ERROR("Failed to allocate a Vulkan command buffer");
@@ -1661,7 +2505,7 @@ index 001f36b..e172691 100644
dfn.vkDestroyCommandPool(device, command_buffer.pool, nullptr);
return false;
}
-@@ -5372,6 +5498,32 @@ bool VulkanCommandProcessor::EndSubmission(bool is_swap) {
+@@ -5372,6 +5524,32 @@ bool VulkanCommandProcessor::EndSubmission(bool is_swap) {
assert_false(command_buffers_writable_.empty());
CommandBuffer command_buffer = command_buffers_writable_.back();
@@ -1694,7 +2538,7 @@ index 001f36b..e172691 100644
if (dfn.vkResetCommandPool(device, command_buffer.pool, 0) != VK_SUCCESS) {
REXGPU_ERROR("Failed to reset a Vulkan command pool");
return false;
-@@ -5385,7 +5537,14 @@ bool VulkanCommandProcessor::EndSubmission(bool is_swap) {
+@@ -5385,7 +5563,14 @@ bool VulkanCommandProcessor::EndSubmission(bool is_swap) {
REXGPU_ERROR("Failed to begin a Vulkan command buffer");
return false;
}
@@ -1709,7 +2553,16 @@ index 001f36b..e172691 100644
if (dfn.vkEndCommandBuffer(command_buffer.buffer) != VK_SUCCESS) {
REXGPU_ERROR("Failed to end a Vulkan command buffer");
return false;
-@@ -5464,6 +5623,9 @@ bool VulkanCommandProcessor::EndSubmission(bool is_swap) {
+@@ -5452,7 +5637,7 @@ bool VulkanCommandProcessor::EndSubmission(bool is_swap) {
+ // Submission already closed now, so minus 1.
+ closed_frame_submissions_[(frame_current_++) % kMaxFramesInFlight] = GetCurrentSubmission() - 1;
+
+- if (cache_clear_requested_ && AwaitAllQueueOperationsCompletion()) {
++ if (cache_clear_requested_ && AwaitAllQueueOperationsCompletion("resource_reuse")) {
+ cache_clear_requested_ = false;
+
+ DestroyScratchBuffer();
+@@ -5464,6 +5649,9 @@ bool VulkanCommandProcessor::EndSubmission(bool is_swap) {
assert_true(command_buffers_submitted_.empty());
for (const CommandBuffer& command_buffer : command_buffers_writable_) {
@@ -1884,10 +2737,52 @@ index 813bb1c..39a6222 100644
return X_ERROR_DEVICE_NOT_CONNECTED;
}
diff --git a/src/kernel/xam/xam_info.cpp b/src/kernel/xam/xam_info.cpp
-index 1fda053..c5d6777 100644
+index 1fda053..fcdf567 100644
--- a/src/kernel/xam/xam_info.cpp
+++ b/src/kernel/xam/xam_info.cpp
-@@ -293,8 +293,13 @@ void XamLoaderTerminateTitle_entry() {
+@@ -16,6 +16,7 @@
+ #include <rex/types.h>
+ #include <rex/string.h>
+ #include <rex/system/kernel_state.h>
++#include <rex/system/flags.h>
+ #include <rex/system/user_module.h>
+ #include <rex/system/xenumerator.h>
+ #include <rex/system/xthread.h>
+@@ -183,19 +184,12 @@ u32 XGetGameRegion_entry() {
+ }
+
+ u32 XGetLanguage_entry() {
+- auto desired_language = XLanguage::kEnglish;
+-
+- // Switch the language based on game region.
+- // TODO(benvanik): pull from xex header.
+- uint32_t game_region = XEX_REGION_NTSCU;
+- if (game_region & XEX_REGION_NTSCU) {
+- desired_language = XLanguage::kEnglish;
+- } else if (game_region & XEX_REGION_NTSCJ) {
+- desired_language = XLanguage::kJapanese;
++ const uint32_t language = REXCVAR_GET(user_language);
++ if (language > static_cast<uint32_t>(XLanguage::kInvalid) &&
++ language < static_cast<uint32_t>(XLanguage::kMaxLanguages)) {
++ return language;
+ }
+- // Add more overrides?
+-
+- return uint32_t(desired_language);
++ return static_cast<uint32_t>(XLanguage::kEnglish);
+ }
+
+ u32 XamGetCurrentTitleId_entry() {
+@@ -268,7 +262,7 @@ void XamLoaderLaunchTitle_entry(mapped_string raw_name_ptr, u32 flags) {
+
+ // Translate the launch path to a full path.
+ if (raw_name_ptr) {
+- auto path = raw_name_ptr.value();
++ std::string path(raw_name_ptr.value());
+ if (path.empty()) {
+ loader_data.launch_path = "game:\\default.xex";
+ } else {
+@@ -293,8 +287,13 @@ void XamLoaderTerminateTitle_entry() {
REX_KERNEL_STATE()->TerminateTitle();
}
@@ -1965,7 +2860,7 @@ index dcd2001..97dd0ed 100644
result = X_STATUS_SUCCESS;
} else {
diff --git a/src/system/function_dispatcher.cpp b/src/system/function_dispatcher.cpp
-index bd43109..3e903e8 100644
+index bd43109..63d1faf 100644
--- a/src/system/function_dispatcher.cpp
+++ b/src/system/function_dispatcher.cpp
@@ -35,6 +35,18 @@ FunctionDispatcher* GetBoundFunctionDispatcher() {
@@ -1987,7 +2882,7 @@ index bd43109..3e903e8 100644
REX_FATAL("Call to invalid or unregistered function at guest address 0x{:08X}",
ctx.last_indirect_target);
}
-@@ -61,11 +73,26 @@ bool FunctionDispatcher::Execute(ThreadState* thread_state, uint32_t address) {
+@@ -61,29 +73,52 @@ bool FunctionDispatcher::Execute(ThreadState* thread_state, uint32_t address) {
SCOPE_profile_cpu_f("cpu");
PROFILE_FUNCTION_DISPATCHED();
@@ -2019,7 +2914,78 @@ index bd43109..3e903e8 100644
auto* ctx = thread_state->context();
auto* previous_thread_state = ThreadState::Get();
-@@ -179,8 +206,10 @@ uint64_t FunctionDispatcher::ExecuteInterrupt(ThreadState* thread_state, uint32_
+
++ struct DispatchRestoreGuard {
++ PPCContext* context;
++ ThreadState* previous_thread;
++ uint64_t stack_pointer;
++ uint64_t link_register;
++ ~DispatchRestoreGuard() {
++ context->lr = link_register;
++ context->r1.u64 = stack_pointer;
++ ThreadState::Bind(previous_thread);
++ }
++ } restore{ctx, previous_thread_state, ctx->r1.u64, ctx->lr};
++
+ // Rebind the active guest thread for cross-module callbacks.
+ ThreadState::Bind(thread_state);
+
+ // Pad out stack a bit, as some games seem to overwrite the caller by about 16 to 32b.
+ ctx->r1.u64 -= 64 + 112;
+
+- uint64_t previous_lr = ctx->lr;
+ ctx->lr = 0xBCBCBCBC;
+
+ fn(*ctx, memory_->virtual_membase());
+
+- ctx->lr = previous_lr;
+- ctx->r1.u64 += 64 + 112;
+- ThreadState::Bind(previous_thread_state);
+
+ return true;
+ }
+@@ -130,13 +165,16 @@ uint64_t FunctionDispatcher::Execute(ThreadState* thread_state, uint32_t address
+ uint64_t FunctionDispatcher::ExecuteTrap(ThreadState* thread_state, uint32_t address,
+ uint64_t args[], size_t arg_count) {
+ auto* ctx = thread_state->context();
+- PPCContext saved = *ctx;
+-
+- uint64_t result = Execute(thread_state, address, args, arg_count);
++ struct ContextRestoreGuard {
++ PPCContext* context;
++ PPCContext saved;
++ ~ContextRestoreGuard() {
++ *context = saved;
++ context->fpscr.restoreGuestBits(saved.fpscr.csr);
++ }
++ } restore{ctx, *ctx};
+
+- *ctx = saved;
+- ctx->fpscr.restoreGuestBits(saved.fpscr.csr);
+- return result;
++ return Execute(thread_state, address, args, arg_count);
+ }
+
+ uint64_t FunctionDispatcher::ExecuteInterrupt(ThreadState* thread_state, uint32_t address,
+@@ -166,49 +204,77 @@ uint64_t FunctionDispatcher::ExecuteInterrupt(ThreadState* thread_state, uint32_
+ auto pcr_address = memory_->TranslateVirtual(static_cast<uint32_t>(ctx->r13.u64));
+ uint32_t old_tls_ptr = memory::load_and_swap<uint32_t>(pcr_address);
+ memory::store_and_swap<uint32_t>(pcr_address, 0);
++ struct TlsRestoreGuard {
++ uint8_t* address;
++ uint32_t value;
++ ~TlsRestoreGuard() { memory::store_and_swap<uint32_t>(address, value); }
++ } tls_restore{pcr_address, old_tls_ptr};
+
+ if (!Execute(thread_state, address)) {
+ return 0xDEADBABE;
+ }
+
+- // Restore TLS ptr.
+- memory::store_and_swap<uint32_t>(pcr_address, old_tls_ptr);
+
+ return ctx->r3.u64;
+ }
// rexglue function table management
@@ -2032,7 +2998,18 @@ index bd43109..3e903e8 100644
bool is_entrypoint) {
std::lock_guard<std::recursive_mutex> lock(dispatch_mutex_);
-@@ -190,25 +219,39 @@ bool FunctionDispatcher::InitializeFunctionTable(uint32_t code_base, uint32_t co
++ const uint64_t image_end = uint64_t(image_base) + image_size;
++ const uint64_t code_end = uint64_t(code_base) + code_size + kThunkReserveSize;
++ if (!code_size || !image_size || (code_base & 3) || (code_size & 3) ||
++ image_end > UINT32_MAX || code_end > UINT32_MAX ||
++ (uint64_t(code_size) + kThunkReserveSize) * 2 > UINT32_MAX) {
++ REXLOG_ERROR("InitializeFunctionTable: invalid or overflowing module range");
++ return false;
++ }
++
+ if (is_entrypoint && entrypoint_code_base_ != 0) {
+ REXLOG_ERROR("InitializeFunctionTable: entrypoint already registered at {:08X}",
+ entrypoint_code_base_);
return false;
}
@@ -2084,7 +3061,7 @@ index bd43109..3e903e8 100644
REXLOG_ERROR("Failed to initialize guest memory function table");
return false;
}
-@@ -226,11 +269,13 @@ bool FunctionDispatcher::InitializeFunctionTable(uint32_t code_base, uint32_t co
+@@ -226,11 +292,13 @@ bool FunctionDispatcher::InitializeFunctionTable(uint32_t code_base, uint32_t co
entrypoint_code_base_ = code_base;
}
@@ -2101,11 +3078,23 @@ index bd43109..3e903e8 100644
FunctionDispatcher::ModuleTableInfo* FunctionDispatcher::FindModuleByAddress(
uint32_t guest_address) {
for (auto& mod : module_tables_) {
+@@ -253,6 +321,11 @@ bool FunctionDispatcher::SetFunction(uint32_t guest_address, ::PPCFunc* func) {
+ std::lock_guard<std::recursive_mutex> lock(dispatch_mutex_);
+ assert_true(!module_tables_.empty());
+
++ if (guest_address & 3) {
++ REXLOG_ERROR("SetFunction: unaligned guest address {:08X}", guest_address);
++ return false;
++ }
++
+ if (!FindModuleByAddress(guest_address)) {
+ REXLOG_ERROR("SetFunction: address {:08X} outside all registered module ranges", guest_address);
+ return false;
diff --git a/src/system/kernel_state.cpp b/src/system/kernel_state.cpp
-index 697399c..484fdfb 100644
+index 697399c..f609238 100644
--- a/src/system/kernel_state.cpp
+++ b/src/system/kernel_state.cpp
-@@ -914,11 +914,36 @@ void KernelState::RegisterRecompiledModule(const char* pe_name, const char* gues
+@@ -914,11 +914,44 @@ void KernelState::RegisterRecompiledModule(const char* pe_name, const char* gues
std::optional<KernelState::RecompiledModuleInfo> KernelState::FindRecompiledModule(
std::string_view guest_path) {
auto global_lock = global_critical_region_.Acquire();
@@ -2113,9 +3102,10 @@ index 697399c..484fdfb 100644
auto normalized = NormalizeGuestPath(guest_path);
+
+ // Primeiro tenta correspondência exata.
-+ for (const auto& info : recompiled_modules_) {
+ for (const auto& info : recompiled_modules_) {
+- if (info.guest_path == normalized)
+ if (info.guest_path == normalized) {
-+ return info;
+ return info;
+ }
+ }
+
@@ -2125,21 +3115,28 @@ index 697399c..484fdfb 100644
+ std::string filename =
+ pos == std::string::npos ? normalized_str : normalized_str.substr(pos + 1);
+
- for (const auto& info : recompiled_modules_) {
-- if (info.guest_path == normalized)
++ std::optional<RecompiledModuleInfo> filename_match;
++ for (const auto& info : recompiled_modules_) {
+ std::string info_path(info.guest_path);
+ size_t info_pos = info_path.find_last_of("\\/");
+ std::string info_filename =
+ info_pos == std::string::npos ? info_path : info_path.substr(info_pos + 1);
+
+ if (info_filename == filename) {
-+ REXSYS_INFO(
-+ "FindRecompiledModule: matched '{}' to '{}' by filename",
-+ normalized, info.guest_path);
- return info;
++ if (filename_match) {
++ REXSYS_ERROR("FindRecompiledModule: ambiguous filename '{}' for '{}'", filename, normalized);
++ return std::nullopt;
++ }
++ filename_match = info;
+ }
- }
++ }
+
++ if (filename_match) {
++ REXSYS_INFO("FindRecompiledModule: matched '{}' to '{}' by filename", normalized,
++ filename_match->guest_path);
++ return filename_match;
+ }
++ REXSYS_WARN("FindRecompiledModule: no registered recompiled module for '{}'", normalized);
return std::nullopt;
}
@@ -2262,6 +3259,33 @@ index 76cc877..121f321 100644
bool Memory::SetFunction(uint32_t guest_address, PPCFunc* host_function) {
uint32_t table_address = 0;
{
+diff --git a/src/ui/d3d12/d3d12_presenter.cpp b/src/ui/d3d12/d3d12_presenter.cpp
+index 306118e..2001e5c 100644
+--- a/src/ui/d3d12/d3d12_presenter.cpp
++++ b/src/ui/d3d12/d3d12_presenter.cpp
+@@ -478,7 +478,7 @@ D3D12Presenter::ConnectOrReconnectPaintingToSurfaceFromUIThread(Surface& new_sur
+ provider_.OffsetRTVDescriptor(rtv_heap_start, PaintContext::kRTVIndexSwapChainBuffer0 + i));
+ }
+
+- is_vsync_implicit_out = false;
++ is_vsync_implicit_out = REXCVAR_QUERY(bool, vsync);
+ return SurfacePaintConnectResult::kSuccess;
+ }
+
+@@ -1155,9 +1155,11 @@ Presenter::PaintResult D3D12Presenter::PaintAndPresentImpl(bool execute_ui_drawe
+ // fullscreen is ever used in, the allow tearing flag must not be passed in
+ // fullscreen, but DXGI fullscreen is largely unneeded with the flip
+ // presentation model used in Direct3D 12).
++ const bool presentation_vsync = REXCVAR_QUERY(bool, vsync);
+ HRESULT present_result = paint_context_.swap_chain->Present(
+- 0, DXGI_PRESENT_RESTART |
+- (paint_context_.swap_chain_allows_tearing ? DXGI_PRESENT_ALLOW_TEARING : 0));
++ presentation_vsync ? 1 : 0,
++ presentation_vsync ? 0 : (DXGI_PRESENT_RESTART |
++ (paint_context_.swap_chain_allows_tearing ? DXGI_PRESENT_ALLOW_TEARING : 0)));
+ // Even if presentation has failed, work might have been enqueued anyway
+ // internally before the failure according to Jesse Natalie from the DirectX
+ // Discord server.
diff --git a/src/ui/keybinds.cpp b/src/ui/keybinds.cpp
index 9822f3b..604936b 100644
--- a/src/ui/keybinds.cpp
@@ -2364,6 +3388,86 @@ index 43d6c06..b55b408 100644
}
} // namespace rex::ui
+diff --git a/src/ui/presenter.cpp b/src/ui/presenter.cpp
+index 7360ed9..d3db6a0 100644
+--- a/src/ui/presenter.cpp
++++ b/src/ui/presenter.cpp
+@@ -576,6 +576,8 @@ bool Presenter::RefreshGuestOutput(
+ guest_output_active_last_refresh_ = false;
+ }
+
++ writable_properties.frame_sequence = ++guest_output_frame_sequence_;
++
+ // Make the new image the next to present on the host (the "ready" one),
+ // replacing the one already specified as the next (dropping it instead of
+ // enqueueing the new image after it) to achieve the lowest latency (also,
+@@ -613,7 +615,9 @@ bool Presenter::RefreshGuestOutput(
+ guest_output_mailbox_writable_ = (3 - last_acquired - guest_output_mailbox_writable_) % 3;
+ }
+
+- // Trigger the presentation on the host.
++ // Trigger presentation after publishing the mailbox. Preserve the notification
++ // even when painting or reconfiguration currently owns the mode mutex, so a
++ // final guest frame cannot be left unpainted.
+ PaintResult paint_result = PaintResult::kNotPresented;
+ {
+ std::lock_guard<std::mutex> paint_mode_mutex_lock(paint_mode_mutex_);
+@@ -1605,6 +1609,33 @@ void Presenter::WaitForUITickFromUIThread() {
+ #endif // XE_PLATFORM
+ }
+
++bool Presenter::WaitForMonitorVBlank(double refresh_rate_hz) {
++#if REX_PLATFORM_WIN32
++ Microsoft::WRL::ComPtr<IDXGIOutput> output;
++ {
++ std::lock_guard<std::mutex> lock(dxgi_ui_tick_mutex_);
++ if (dxgi_ui_tick_thread_shutdown_) return false;
++ output = dxgi_ui_tick_output_;
++ }
++ if (!output) return false;
++ DXGI_OUTPUT_DESC description;
++ DEVMODEW mode = {};
++ mode.dmSize = sizeof(mode);
++ if (FAILED(output->GetDesc(&description)) || !description.AttachedToDesktop ||
++ !::EnumDisplaySettingsExW(description.DeviceName, ENUM_CURRENT_SETTINGS, &mode, 0) ||
++ double(mode.dmDisplayFrequency) < refresh_rate_hz - 1.0 ||
++ double(mode.dmDisplayFrequency) > refresh_rate_hz + 1.0) {
++ return false;
++ }
++ // Never hold the monitor mutex while the driver blocks.
++ if (FAILED(output->WaitForVBlank())) return false;
++ std::lock_guard<std::mutex> lock(dxgi_ui_tick_mutex_);
++ return !dxgi_ui_tick_thread_shutdown_ && output.Get() == dxgi_ui_tick_output_.Get();
++#else
++ return false;
++#endif
++}
++
+ void Presenter::ForceUIThreadPaintTick() {
+ #if REX_PLATFORM_WIN32
+ std::scoped_lock<std::mutex> dxgi_ui_tick_lock(dxgi_ui_tick_mutex_);
+@@ -1644,13 +1675,15 @@ void Presenter::DXGIUITickThread() {
+ // Wait for vertical blank, with the mutex unlocked (holding a new reference
+ // to the current output while it's happening) so subscribers can still do
+ // early-out checks.
+- bool wait_succeeded;
+- {
+- Microsoft::WRL::ComPtr<IDXGIOutput> dxgi_output = dxgi_ui_tick_output_;
+- dxgi_ui_tick_lock.unlock();
+- wait_succeeded = SUCCEEDED(dxgi_ui_tick_output_->WaitForVBlank());
+- }
++ Microsoft::WRL::ComPtr<IDXGIOutput> dxgi_output = dxgi_ui_tick_output_;
++ dxgi_ui_tick_lock.unlock();
++ bool wait_succeeded = SUCCEEDED(dxgi_output->WaitForVBlank());
+ dxgi_ui_tick_lock.lock();
++ // A monitor change may replace the output while its vblank wait is active.
++ // Do not apply the old output's result to the new output.
++ if (dxgi_output.Get() != dxgi_ui_tick_output_.Get()) {
++ continue;
++ }
+ if (wait_succeeded) {
+ ++dxgi_ui_tick_last_vblank_;
+ } else {
diff --git a/src/ui/rex_app.cpp b/src/ui/rex_app.cpp
index b94fe9e..b14890b 100644
--- a/src/ui/rex_app.cpp
@@ -2378,18 +3482,277 @@ index b94fe9e..b14890b 100644
debug_overlay_.reset();
} else {
diff --git a/src/ui/vulkan/vulkan_presenter.cpp b/src/ui/vulkan/vulkan_presenter.cpp
-index 23645ef..3cb302e 100644
+index 23645ef..d582c50 100644
--- a/src/ui/vulkan/vulkan_presenter.cpp
+++ b/src/ui/vulkan/vulkan_presenter.cpp
-@@ -1570,9 +1570,14 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
+@@ -11,6 +11,8 @@
+
+ #include <algorithm>
+ #include <atomic>
++#include <array>
++#include <chrono>
+ #include <cstddef>
+ #include <cstdint>
+ #include <cmath>
+@@ -58,10 +60,101 @@ REXCVAR_DEFINE_BOOL(vulkan_allow_present_mode_mailbox, true, "UI/Vulkan",
+ REXCVAR_DEFINE_BOOL(vulkan_allow_present_mode_fifo_relaxed, true, "UI/Vulkan",
+ "Allow FIFO relaxed present mode");
+
++REXCVAR_DEFINE_BOOL(vulkan_log_present_timing, false, "UI/Vulkan",
++ "Log aggregate CPU presentation timings every five seconds");
++
+ namespace rex {
+ namespace ui {
+ namespace vulkan {
+
++namespace {
++
++// Observe successfully queued host presents, not physical scanout timestamps.
++void LogPresentSequence(const void* presenter, uint64_t sequence) {
++ if (!REXCVAR_GET(vulkan_log_present_timing) || !sequence) return;
++ using Clock = std::chrono::steady_clock;
++ struct Stats {
++ const void* owner = nullptr;
++ Clock::time_point start = Clock::now(), last_new = {};
++ uint64_t last_sequence = 0, presents = 0, repeated = 0, skipped = 0;
++ std::vector<double> intervals;
++ };
++ static thread_local Stats stats;
++ if (stats.owner != presenter) { stats = Stats{}; stats.owner = presenter; }
++ const auto now = Clock::now();
++ ++stats.presents;
++ if (sequence == stats.last_sequence) {
++ ++stats.repeated;
++ } else {
++ if (stats.last_sequence) {
++ if (sequence > stats.last_sequence + 1) stats.skipped += sequence - stats.last_sequence - 1;
++ stats.intervals.push_back(std::chrono::duration<double, std::milli>(now - stats.last_new).count());
++ }
++ stats.last_sequence = sequence;
++ stats.last_new = now;
++ }
++ const double elapsed = std::chrono::duration<double>(now - stats.start).count();
++ if (elapsed < 5.0) return;
++ std::sort(stats.intervals.begin(), stats.intervals.end());
++ const size_t count = stats.intervals.size();
++ REXLOG_INFO("VulkanFrameCadence: seconds={:.3f} presents={} repeated={} skipped={} "
++ "new_frame_ms median={:.3f} p95={:.3f} max={:.3f}", elapsed, stats.presents,
++ stats.repeated, stats.skipped, count ? stats.intervals[count / 2] : 0.0,
++ count ? stats.intervals[(count - 1) * 95 / 100] : 0.0,
++ count ? stats.intervals.back() : 0.0);
++ stats.start = now;
++ stats.presents = stats.repeated = stats.skipped = 0;
++ stats.intervals.clear();
++}
++
++// CPU timings only: no GPU queries, waits, or presentation policy changes.
++struct PresentTiming {
++ using Clock = std::chrono::steady_clock;
++ bool enabled = REXCVAR_GET(vulkan_log_present_timing);
++ bool acquire_timeout = false;
++ Clock::time_point previous = enabled ? Clock::now() : Clock::time_point{};
++ std::array<double, 5> stages{};
++
++ void Mark(size_t stage) {
++ if (!enabled) return;
++ auto now = Clock::now();
++ stages[stage] = std::chrono::duration<double, std::milli>(now - previous).count();
++ previous = now;
++ }
++
++ ~PresentTiming() {
++ if (!enabled) return;
++ struct Stats {
++ Clock::time_point start = Clock::now();
++ uint64_t count = 0;
++ uint64_t timeouts = 0;
++ std::array<double, 5> sums{};
++ std::array<double, 5> maxima{};
++ };
++ static thread_local Stats stats;
++ ++stats.count;
++ stats.timeouts += acquire_timeout ? 1 : 0;
++ for (size_t i = 0; i < stages.size(); ++i) {
++ stats.sums[i] += stages[i];
++ stats.maxima[i] = std::max(stats.maxima[i], stages[i]);
++ }
++ if (Clock::now() - stats.start < std::chrono::seconds(5)) return;
++ REXLOG_INFO(
++ "VulkanPresentTiming: calls={} timeouts={} CPU ms avg/max "
++ "reuse={:.3f}/{:.3f} acquire={:.3f}/{:.3f} record={:.3f}/{:.3f} "
++ "submit={:.3f}/{:.3f} present={:.3f}/{:.3f}",
++ stats.count, stats.timeouts,
++ stats.sums[0] / stats.count, stats.maxima[0],
++ stats.sums[1] / stats.count, stats.maxima[1],
++ stats.sums[2] / stats.count, stats.maxima[2],
++ stats.sums[3] / stats.count, stats.maxima[3],
++ stats.sums[4] / stats.count, stats.maxima[4]);
++ stats = Stats{};
++ }
++};
++
++} // namespace
++
+ #if defined(REX_HAS_FIDELITYFX_RUNTIME) && REX_HAS_FIDELITYFX_RUNTIME
+ namespace {
+
+@@ -129,12 +222,12 @@ VulkanPresenter::PaintContext::Submission::~Submission() {
+ dfn.vkDestroyCommandPool(device, draw_command_pool_, nullptr);
+ }
+
+- if (present_semaphore_ != VK_NULL_HANDLE) {
+- dfn.vkDestroySemaphore(device, present_semaphore_, nullptr);
+- }
+ if (acquire_semaphore_ != VK_NULL_HANDLE) {
+ dfn.vkDestroySemaphore(device, acquire_semaphore_, nullptr);
+ }
++ if (acquire_fence_ != VK_NULL_HANDLE) {
++ dfn.vkDestroyFence(device, acquire_fence_, nullptr);
++ }
+ }
+
+ bool VulkanPresenter::PaintContext::Submission::Initialize() {
+@@ -152,11 +245,11 @@ bool VulkanPresenter::PaintContext::Submission::Initialize() {
+ "semaphore");
+ return false;
+ }
+- if (dfn.vkCreateSemaphore(device, &semaphore_create_info, nullptr, &present_semaphore_) !=
+- VK_SUCCESS) {
+- REXLOG_ERROR(
+- "VulkanPresenter: Failed to create a swapchain image presentation "
+- "semaphore");
++
++ VkFenceCreateInfo acquire_fence_info = {};
++ acquire_fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
++ if (dfn.vkCreateFence(device, &acquire_fence_info, nullptr, &acquire_fence_) != VK_SUCCESS) {
++ REXLOG_ERROR("VulkanPresenter: Failed to create an image acquisition fence");
+ return false;
+ }
+
+@@ -988,6 +1081,21 @@ VulkanPresenter::ConnectOrReconnectPaintingToSurfaceFromUIThread(Surface& new_su
+ return SurfacePaintConnectResult::kFailure;
+ }
+
++ // Buffer present semaphores by swapchain image. Waiting on a submission
++ // fence alone does not guarantee that its presentation wait has finished.
++ assert_true(paint_context_.swapchain_present_semaphores.empty());
++ paint_context_.swapchain_present_semaphores.resize(
++ paint_context_.swapchain_images.size(), VK_NULL_HANDLE);
++ VkSemaphoreCreateInfo present_semaphore_info = {};
++ present_semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
++ for (VkSemaphore& semaphore : paint_context_.swapchain_present_semaphores) {
++ if (dfn.vkCreateSemaphore(device, &present_semaphore_info, nullptr, &semaphore) != VK_SUCCESS) {
++ REXLOG_ERROR("VulkanPresenter: Failed to create a per-image presentation semaphore");
++ paint_context_.DestroySwapchainAndVulkanSurface();
++ return SurfacePaintConnectResult::kFailure;
++ }
++ }
++
+ // Create the image views and the framebuffers.
+ assert_true(paint_context_.swapchain_framebuffers.empty());
+ paint_context_.swapchain_framebuffers.reserve(paint_context_.swapchain_images.size());
+@@ -1061,7 +1169,7 @@ bool VulkanPresenter::RefreshGuestOutputImpl(
+ if (image_instance.image && (image_instance.image->extent().width != frontbuffer_width ||
+ image_instance.image->extent().height != frontbuffer_height)) {
+ guest_output_image_refresher_submission_tracker_.AwaitSubmissionCompletion(
+- image_instance.last_refresher_submission);
++ image_instance.last_refresher_submission, FenceWaitTiming::Reason::ResourceReuse);
+ image_instance.image.reset();
+ }
+ if (!image_instance.image) {
+@@ -1381,19 +1489,20 @@ VkSwapchainKHR VulkanPresenter::PaintContext::CreateSwapchainForVulkanSurface(
+ // interfering with GPU command processing, and also to allow tearing so
+ // variable refresh rate may be used where it's available.
+ // Note: If the priorities here are changes, update the cvar descriptions.
+- if (REXCVAR_GET(vulkan_allow_present_mode_immediate) &&
++ const bool presentation_vsync = REXCVAR_QUERY(bool, vsync);
++ if (!presentation_vsync && REXCVAR_GET(vulkan_allow_present_mode_immediate) &&
+ std::find(present_modes.cbegin(), present_modes.cend(), VK_PRESENT_MODE_IMMEDIATE_KHR) !=
+ present_modes.cend()) {
+ // Allowing tearing to reduce latency, and possibly variable refresh rate
+ // (though on Windows with borderless fullscreen, GDI copying is used
+ // instead of independent flip, so it's not supported there).
+ swapchain_create_info.presentMode = VK_PRESENT_MODE_IMMEDIATE_KHR;
+- } else if (REXCVAR_GET(vulkan_allow_present_mode_mailbox) &&
++ } else if (!presentation_vsync && REXCVAR_GET(vulkan_allow_present_mode_mailbox) &&
+ std::find(present_modes.cbegin(), present_modes.cend(), VK_PRESENT_MODE_MAILBOX_KHR) !=
+ present_modes.cend()) {
+ // Allowing dropping frames to reduce latency, but no tearing.
+ swapchain_create_info.presentMode = VK_PRESENT_MODE_MAILBOX_KHR;
+- } else if (REXCVAR_GET(vulkan_allow_present_mode_fifo_relaxed) &&
++ } else if (!presentation_vsync && REXCVAR_GET(vulkan_allow_present_mode_fifo_relaxed) &&
+ std::find(present_modes.cbegin(), present_modes.cend(),
+ VK_PRESENT_MODE_FIFO_RELAXED_KHR) != present_modes.cend()) {
+ // Limiting the frame rate, but lets too long frames cause tearing not to
+@@ -1428,6 +1537,13 @@ VkSwapchainKHR VulkanPresenter::PaintContext::CreateSwapchainForVulkanSurface(
+ VkSwapchainKHR VulkanPresenter::PaintContext::PrepareForSwapchainRetirement() {
+ if (swapchain != VK_NULL_HANDLE) {
+ submission_tracker.AwaitAllSubmissionsCompletion();
++ // Drain the present queue only when retiring the swapchain, never per frame.
++ // This is the conventional unextended Vulkan retirement path.
++ if (present_queue_family != UINT32_MAX) {
++ const VulkanDevice::Queue::Acquisition queue =
++ vulkan_device->AcquireQueue(present_queue_family, 0);
++ vulkan_device->functions().vkQueueWaitIdle(queue.queue());
++ }
+ }
+ const VulkanDevice::Functions& dfn = vulkan_device->functions();
+ const VkDevice device = vulkan_device->device();
+@@ -1436,6 +1552,12 @@ VkSwapchainKHR VulkanPresenter::PaintContext::PrepareForSwapchainRetirement() {
+ dfn.vkDestroyImageView(device, framebuffer.image_view, nullptr);
+ }
+ swapchain_framebuffers.clear();
++ for (VkSemaphore semaphore : swapchain_present_semaphores) {
++ if (semaphore != VK_NULL_HANDLE) {
++ dfn.vkDestroySemaphore(device, semaphore, nullptr);
++ }
++ }
++ swapchain_present_semaphores.clear();
+ swapchain_images.clear();
+ swapchain_extent.width = 0;
+ swapchain_extent.height = 0;
+@@ -1529,6 +1651,7 @@ bool VulkanPresenter::GuestOutputImage::Initialize() {
+ }
+
+ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_drawers) {
++ PresentTiming timing;
+ // Begin the submission in place of the one not currently potentially used on
+ // the GPU.
+ uint64_t current_paint_submission_index =
+@@ -1536,8 +1659,9 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
+ uint64_t paint_submission_count = uint64_t(paint_context_.submissions.size());
+ if (current_paint_submission_index >= paint_submission_count) {
+ paint_context_.submission_tracker.AwaitSubmissionCompletion(current_paint_submission_index -
+- paint_submission_count);
++ paint_submission_count, FenceWaitTiming::Reason::FrameReuse);
+ }
++ timing.Mark(0);
+ const PaintContext::Submission& paint_submission =
+ *paint_context_.submissions[current_paint_submission_index % paint_submission_count];
+
+@@ -1568,11 +1692,27 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
+ // safe to return early from this function in case of an error.
+
VkSemaphore acquire_semaphore = paint_submission.acquire_semaphore();
++ // In FIFO mode keep the monitor readiness wait on the presentation CPU
++ // thread, rather than enqueueing an unresolved wait on the guest GPU queue.
++ // The binary semaphore is still consumed by the draw submission as required.
++ const VkFence acquire_fence = paint_context_.swapchain_is_fifo
++ ? paint_submission.acquire_fence() : VK_NULL_HANDLE;
++ if (acquire_fence != VK_NULL_HANDLE &&
++ dfn.vkResetFences(device, 1, &acquire_fence) != VK_SUCCESS) {
++ return PaintResult::kGpuLostResponsible;
++ }
uint32_t swapchain_image_index;
VkResult acquire_result =
- dfn.vkAcquireNextImageKHR(device, paint_context_.swapchain, UINT64_MAX, acquire_semaphore,
+- VK_NULL_HANDLE, &swapchain_image_index);
+ // A minimized window may stop returning swapchain images. Keep the UI
+ // thread responsive so it can process restore and surface-change events.
+ dfn.vkAcquireNextImageKHR(device, paint_context_.swapchain, 50000000, acquire_semaphore,
- VK_NULL_HANDLE, &swapchain_image_index);
++ acquire_fence, &swapchain_image_index);
++ timing.Mark(1);
++ timing.acquire_timeout = acquire_result == VK_TIMEOUT || acquire_result == VK_NOT_READY;
switch (acquire_result) {
+ case VK_TIMEOUT:
+ case VK_NOT_READY:
@@ -2397,11 +3760,189 @@ index 23645ef..3cb302e 100644
case VK_SUCCESS:
case VK_SUBOPTIMAL_KHR:
break;
+@@ -1595,6 +1735,18 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
+ return PaintResult::kNotPresented;
+ }
+
++ if (acquire_fence != VK_NULL_HANDLE) {
++ FenceWaitTiming acquire_timing("presenter", this, FenceWaitTiming::Reason::AcquireImage);
++ const VkResult ready_result =
++ dfn.vkWaitForFences(device, 1, &acquire_fence, VK_TRUE, UINT64_MAX);
++ if (ready_result != VK_SUCCESS) {
++ REXLOG_ERROR("VulkanPresenter: Image acquisition readiness failed ({})",
++ int(ready_result));
++ return ready_result == VK_ERROR_DEVICE_LOST ? PaintResult::kGpuLostResponsible
++ : PaintResult::kNotPresentedConnectionOutdated;
++ }
++ }
++
+ // Non-zero extents needed for both the viewport (width must not be zero) and
+ // the guest output rectangle.
+ assert_not_zero(paint_context_.swapchain_extent.width);
+@@ -1688,7 +1840,7 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
+ // its descriptors.
+ paint_context_.submission_tracker.AwaitSubmissionCompletion(
+ paint_context_.guest_output_image_paint_refs[guest_output_image_paint_ref_new_index]
+- .first);
++ .first, FenceWaitTiming::Reason::OutputDescriptors);
+ }
+ guest_output_image_paint_ref_index = guest_output_image_paint_ref_new_index;
+ // The actual submission index will be set if the image is actually
+@@ -1736,7 +1888,8 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
+ // size is needed.
+ if (intermediate_image_ptr_ref) {
+ paint_context_.submission_tracker.AwaitSubmissionCompletion(
+- paint_context_.guest_output_intermediate_image_last_submission);
++ paint_context_.guest_output_intermediate_image_last_submission,
++ FenceWaitTiming::Reason::IntermediateImage);
+ intermediate_image_ptr_ref.reset();
+ util::DestroyAndNullHandle(dfn.vkDestroyFramebuffer, device,
+ paint_context_.guest_output_intermediate_framebuffers[i]);
+@@ -1829,7 +1982,8 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
+ swapchain_effect_pipeline.swapchain_format !=
+ paint_context_.swapchain_render_pass_format) {
+ paint_context_.submission_tracker.AwaitSubmissionCompletion(
+- paint_context_.guest_output_image_paint_last_submission);
++ paint_context_.guest_output_image_paint_last_submission,
++ FenceWaitTiming::Reason::PaintPipeline);
+ util::DestroyAndNullHandle(dfn.vkDestroyPipeline, device,
+ swapchain_effect_pipeline.swapchain_pipeline);
+ }
+@@ -1840,6 +1994,9 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
+ swapchain_effect, paint_context_.swapchain_render_pass);
+ if (swapchain_effect_pipeline.swapchain_pipeline == VK_NULL_HANDLE) {
+ guest_output_flow.effect_count = 0;
++ } else {
++ swapchain_effect_pipeline.swapchain_format =
++ paint_context_.swapchain_render_pass_format;
+ }
+ }
+ }
+@@ -2174,7 +2331,9 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
+ paint_context_.ui_setup_command_buffer_current_index = SIZE_MAX;
+ }
+ command_buffers[command_buffer_count++] = draw_command_buffer;
+- VkSemaphore present_semaphore = paint_submission.present_semaphore();
++ VkSemaphore present_semaphore =
++ paint_context_.swapchain_present_semaphores[swapchain_image_index];
++ timing.Mark(2);
+ VkSubmitInfo submit_info;
+ submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
+ submit_info.pNext = nullptr;
+@@ -2227,6 +2386,7 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
+ }
+ }
+
++ timing.Mark(3);
+ VkPresentInfoKHR present_info;
+ present_info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
+ present_info.pNext = nullptr;
+@@ -2242,6 +2402,10 @@ Presenter::PaintResult VulkanPresenter::PaintAndPresentImpl(bool execute_ui_draw
+ vulkan_device_->AcquireQueue(paint_context_.present_queue_family, 0);
+ present_result = dfn.vkQueuePresentKHR(queue_acquisition.queue(), &present_info);
+ }
++ timing.Mark(4);
++ if (present_result == VK_SUCCESS || present_result == VK_SUBOPTIMAL_KHR) {
++ LogPresentSequence(this, guest_output_properties.frame_sequence);
++ }
+ switch (present_result) {
+ case VK_SUCCESS:
+ return PaintResult::kPresented;
+diff --git a/src/ui/vulkan/vulkan_submission_tracker.cpp b/src/ui/vulkan/vulkan_submission_tracker.cpp
+index 07a07b2..610c9b0 100644
+--- a/src/ui/vulkan/vulkan_submission_tracker.cpp
++++ b/src/ui/vulkan/vulkan_submission_tracker.cpp
+@@ -10,11 +10,15 @@
+ */
+
+ #include <cstdint>
++#include <rex/ui/vulkan/fence_wait_timing.h>
+
+ #include <rex/assert.h>
+ #include <rex/ui/vulkan/submission_tracker.h>
+ #include <rex/ui/vulkan/util.h>
+
++REXCVAR_DEFINE_BOOL(vulkan_log_fence_waits, false, "UI/Vulkan",
++ "Log aggregate existing CPU fence waits without GPU queries");
++
+ namespace rex {
+ namespace ui {
+ namespace vulkan {
+@@ -88,7 +92,8 @@ uint64_t VulkanSubmissionTracker::UpdateAndGetCompletedSubmission() {
+ return submission_completed_on_gpu_;
+ }
+
+-bool VulkanSubmissionTracker::AwaitSubmissionCompletion(uint64_t submission_index) {
++bool VulkanSubmissionTracker::AwaitSubmissionCompletion(uint64_t submission_index,
++ FenceWaitTiming::Reason reason) {
+ // The tracker itself can't give a submission index for a submission that
+ // hasn't even started being recorded yet, the client has provided a
+ // completely invalid value or has done overly optimistic math if such an
+@@ -119,8 +124,12 @@ bool VulkanSubmissionTracker::AwaitSubmissionCompletion(uint64_t submission_inde
+ assert_true(pending_pair.first > submission_completed_on_gpu_);
+ if (pending_pair.first <= submission_index) {
+ // Wait if requested.
+- if (dfn.vkWaitForFences(device, 1, &pending_pair.second, VK_TRUE, UINT64_MAX) ==
+- VK_SUCCESS) {
++ VkResult wait_result;
++ {
++ FenceWaitTiming timing("presenter", this, reason);
++ wait_result = dfn.vkWaitForFences(device, 1, &pending_pair.second, VK_TRUE, UINT64_MAX);
++ }
++ if (wait_result == VK_SUCCESS) {
+ break;
+ }
+ }
diff --git a/src/ui/window_sdl.cpp b/src/ui/window_sdl.cpp
-index 2251429..feb2bea 100644
+index 2251429..29b1e8b 100644
--- a/src/ui/window_sdl.cpp
+++ b/src/ui/window_sdl.cpp
-@@ -484,11 +484,28 @@ void WindowSDL::HandleWindowEvent(SDL_Event& event) {
+@@ -40,6 +40,9 @@
+ #include <rex/ui/surface_gnulinux.h>
+ #endif
+
++REXCVAR_DEFINE_STRING(launcher_monitor_device, "", "UI/Window",
++ "Windows display device selected by the launcher");
++
+ namespace rex::ui {
+
+ namespace {
+@@ -170,6 +173,34 @@ bool WindowSDL::OpenImpl() {
+ }
+ }
+
++#if REX_PLATFORM_WIN32
++ // Windows and SDL enumeration orders need not match. Match the selected
++ // device's desktop position rather than interpreting a DXGI index as SDL.
++ const std::string selected_device = REXCVAR_GET(launcher_monitor_device);
++ if (!selected_device.empty()) {
++ DEVMODEA mode = {};
++ mode.dmSize = sizeof(mode);
++ if (::EnumDisplaySettingsA(selected_device.c_str(), ENUM_CURRENT_SETTINGS, &mode)) {
++ int count = 0;
++ SDL_DisplayID* displays = SDL_GetDisplays(&count);
++ if (displays) {
++ for (int i = 0; i < count; ++i) {
++ SDL_Rect bounds;
++ if (SDL_GetDisplayBounds(displays[i], &bounds) &&
++ bounds.x == mode.dmPosition.x && bounds.y == mode.dmPosition.y) {
++ SDL_SetWindowPosition(sdl_window_, SDL_WINDOWPOS_CENTERED_DISPLAY(displays[i]),
++ SDL_WINDOWPOS_CENTERED_DISPLAY(displays[i]));
++ break;
++ }
++ }
++ SDL_free(displays);
++ }
++ } else {
++ REXLOG_WARN("Could not locate launcher monitor {}", selected_device);
++ }
++ }
++#endif
++
+ if (IsFullscreen()) {
+ // Borderless desktop fullscreen (a NULL display mode is SDL3's default).
+ SDL_SetWindowFullscreen(sdl_window_, true);
+@@ -484,11 +515,28 @@ void WindowSDL::HandleWindowEvent(SDL_Event& event) {
OnPaint(true);
break;
case SDL_EVENT_WINDOW_MINIMIZED:
@@ -2431,3 +3972,443 @@ index 2251429..feb2bea 100644
case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
// SDL destroys nothing on its own; this is the veto point.
if (SendCloseRequestToListeners(destruction_receiver)) {
+diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt
+index 7bd264b..e5b229e 100644
+--- a/tests/unit/CMakeLists.txt
++++ b/tests/unit/CMakeLists.txt
+@@ -36,6 +36,7 @@ target_link_libraries(unit_tests PRIVATE
+ rexcodegen
+ rexruntime
+ Catch2::Catch2WithMain
++ xxHash::xxhash
+ )
+
+ # ReXApp is shipped as source for recomp projects, rather than compiled into
+diff --git a/tests/unit/codegen/output_stamp_test.cpp b/tests/unit/codegen/output_stamp_test.cpp
+index d97edb5..f030f58 100644
+--- a/tests/unit/codegen/output_stamp_test.cpp
++++ b/tests/unit/codegen/output_stamp_test.cpp
+@@ -224,6 +224,6 @@ TEST_CASE("Depfile escapes characters make treats as syntax", "[output_stamp]")
+ std::ifstream in(depfile, std::ios::binary);
+ std::string content((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
+
+- CHECK(content.find("has\ space.toml") != std::string::npos);
+- CHECK(content.find("hash\#.toml") != std::string::npos);
++ CHECK(content.find("has\\ space.toml") != std::string::npos);
++ CHECK(content.find("hash\\#.toml") != std::string::npos);
+ }
+diff --git a/tests/unit/core/stream_test.cpp b/tests/unit/core/stream_test.cpp
+index 9929507..d40aae3 100644
+--- a/tests/unit/core/stream_test.cpp
++++ b/tests/unit/core/stream_test.cpp
+@@ -1,3 +1,5 @@
++#include <stdexcept>
++#include <limits>
+ /**
+ * Unit tests for stream utilities (BitStream, ByteStream)
+ *
+@@ -288,13 +290,9 @@ TEST_CASE("BitStream Read crossing byte boundary", "[stream][bitstream]") {
+
+ // =============================================================================
+ // BitStream Write Tests
+-// NOTE: BitStream::Write is marked "TODO: This is totally not tested!" in source.
+-// It has a bug: doesn't byte-swap when storing, but Read expects big-endian.
+-// These tests are skipped until Write is fixed.
+ // =============================================================================
+
+-TEST_CASE("BitStream Write byte-aligned", "[stream][bitstream][!mayfail]") {
+- SKIP("BitStream::Write is broken - doesn't byte-swap on store");
++TEST_CASE("BitStream Write byte-aligned", "[stream][bitstream]") {
+
+ std::array<uint8_t, 16> buffer{};
+ BitStream stream(buffer.data(), buffer.size() * 8);
+@@ -306,8 +304,7 @@ TEST_CASE("BitStream Write byte-aligned", "[stream][bitstream][!mayfail]") {
+ CHECK(stream.Read(8) == 0xAB);
+ }
+
+-TEST_CASE("BitStream Write 16-bit value", "[stream][bitstream][!mayfail]") {
+- SKIP("BitStream::Write is broken - doesn't byte-swap on store");
++TEST_CASE("BitStream Write 16-bit value", "[stream][bitstream]") {
+
+ std::array<uint8_t, 16> buffer{};
+ BitStream stream(buffer.data(), buffer.size() * 8);
+@@ -318,8 +315,7 @@ TEST_CASE("BitStream Write 16-bit value", "[stream][bitstream][!mayfail]") {
+ CHECK(stream.Read(16) == 0x1234);
+ }
+
+-TEST_CASE("BitStream Write non-byte-aligned", "[stream][bitstream][!mayfail]") {
+- SKIP("BitStream::Write is broken - doesn't byte-swap on store");
++TEST_CASE("BitStream Write non-byte-aligned", "[stream][bitstream]") {
+
+ std::array<uint8_t, 16> buffer{};
+ BitStream stream(buffer.data(), buffer.size() * 8);
+@@ -332,8 +328,7 @@ TEST_CASE("BitStream Write non-byte-aligned", "[stream][bitstream][!mayfail]") {
+ CHECK(stream.Read(8) == 0xAB);
+ }
+
+-TEST_CASE("BitStream Write preserves surrounding bits", "[stream][bitstream][!mayfail]") {
+- SKIP("BitStream::Write is broken - doesn't byte-swap on store");
++TEST_CASE("BitStream Write preserves surrounding bits", "[stream][bitstream]") {
+
+ std::array<uint8_t, 16> buffer = {0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+ BitStream stream(buffer.data(), buffer.size() * 8);
+@@ -380,3 +375,73 @@ TEST_CASE("BitStream BitsRemaining decreases", "[stream][bitstream]") {
+ stream.Read(32);
+ CHECK(stream.BitsRemaining() == 16);
+ }
++
++TEST_CASE("BitStream Write exact boundary and failed writes preserve memory", "[stream][bitstream]") {
++ std::array<uint8_t, 3> buffer = {0xAA, 0xFF, 0xBB};
++ BitStream stream(buffer.data() + 1, 8);
++ REQUIRE(stream.Write(0, 0));
++ REQUIRE(stream.Write(0x35, 8));
++ CHECK(buffer[0] == 0xAA);
++ CHECK(buffer[1] == 0x35);
++ CHECK(buffer[2] == 0xBB);
++ CHECK_FALSE(stream.Write(1, 1));
++ CHECK_FALSE(stream.Write(0, 58));
++ CHECK(stream.offset_bits() == 8);
++ CHECK(buffer[1] == 0x35);
++}
++
++TEST_CASE("BitStream reads a short final byte and a zero-length end", "[stream][bitstream]") {
++ std::array<uint8_t, 1> buffer = {0xA5};
++ BitStream stream(buffer.data(), 8);
++ CHECK(stream.Read(4) == 0xA);
++ CHECK(stream.Read(4) == 0x5);
++ CHECK(stream.Peek(0) == 0);
++ CHECK(stream.offset_bits() == 8);
++}
++
++TEST_CASE("BitStream Copy preserves alignment and untouched destination bits", "[stream][bitstream]") {
++ // Exhaust all short copy lengths and source bit offsets against a bit oracle.
++ for (size_t offset = 0; offset < 8; ++offset) {
++ for (size_t length = 0; length <= 24 - offset; ++length) {
++ std::array<uint8_t, 3> source = {0xA5, 0x3C, 0xF0};
++ std::array<uint8_t, 4> output = {0x5A, 0x5A, 0x5A, 0x5A};
++ auto expected = output;
++ for (size_t bit = offset; bit < offset + length; ++bit) {
++ const uint8_t mask = uint8_t(1u << (7 - (bit & 7)));
++ expected[bit / 8] = uint8_t((expected[bit / 8] & ~mask) | (source[bit / 8] & mask));
++ }
++ BitStream stream(source.data(), 24);
++ stream.SetOffset(offset);
++ REQUIRE(stream.Copy(output.data(), length) == offset);
++ REQUIRE(output == expected);
++ REQUIRE(stream.offset_bits() == offset + length);
++ }
++ }
++}
++
++TEST_CASE("ByteStream rejects overflow and truncated strings in Release", "[stream][bytestream]") {
++ std::array<uint8_t, 8> buffer{};
++ ByteStream stream(buffer.data(), buffer.size());
++ SECTION("Advance overflow") {
++ stream.Advance(1);
++ REQUIRE_THROWS_AS(stream.Advance(std::numeric_limits<size_t>::max()), std::out_of_range);
++ CHECK(stream.offset() == 1);
++ }
++ SECTION("Read outside buffer") {
++ stream.set_offset(buffer.size());
++ REQUIRE_THROWS_AS(stream.Read<uint32_t>(), std::out_of_range);
++ CHECK(stream.offset() == buffer.size());
++ }
++ SECTION("Write outside buffer") {
++ stream.set_offset(buffer.size());
++ REQUIRE_THROWS_AS(stream.Write(uint32_t(42)), std::out_of_range);
++ CHECK(buffer == std::array<uint8_t, 8>{});
++ }
++ SECTION("Truncated string length") {
++ stream.Write(uint32_t(0xFFFFFFFFu));
++ stream.set_offset(0);
++ REQUIRE_THROWS_AS(stream.Read<std::string>(), std::out_of_range);
++ stream.set_offset(0);
++ REQUIRE_THROWS_AS(stream.Read<std::u16string>(), std::out_of_range);
++ }
++}
+diff --git a/tests/unit/system/function_dispatcher_test.cpp b/tests/unit/system/function_dispatcher_test.cpp
+index 88617f2..142d5b9 100644
+--- a/tests/unit/system/function_dispatcher_test.cpp
++++ b/tests/unit/system/function_dispatcher_test.cpp
+@@ -278,3 +278,59 @@ TEST_CASE("PPCContext: restoring a zeroed fpscr leaves host FP exception masks i
+ CHECK((ctx.fpscr.getcsr() & ~kGuestMask) == (host_before & ~kGuestMask));
+ CHECK(ctx.fpscr.csr == ctx.fpscr.getcsr());
+ }
++
++
++namespace {
++void ThrowingDispatchFn(PPCContext& ctx, uint8_t*) {
++ ctx.r1.u64 -= 32;
++ ctx.lr = 0;
++ ctx.r14.u64 = 0;
++ throw 42;
++}
++}
++
++TEST_CASE("FunctionDispatcher: invalid ranges and unaligned functions are rejected",
++ "[runtime][dispatcher]") {
++ auto& memory = GetTestMemory();
++ rex::runtime::ExportResolver resolver;
++ rex::runtime::FunctionDispatcher dispatcher(&memory, &resolver);
++ CHECK_FALSE(dispatcher.InitializeFunctionTable(0xFFFFFF00u, 0x10000u,
++ 0xFFFFFF00u, 0x100000u));
++ CHECK_FALSE(dispatcher.InitializeFunctionTable(0x8B000001u, 0x10000u,
++ 0x8B000000u, 0x100000u));
++ REQUIRE(dispatcher.InitializeFunctionTable(0x8B000000u, 0x10000u,
++ 0x8B000000u, 0x100000u));
++ CHECK_FALSE(dispatcher.SetFunction(0x8B000001u, &DummyFn));
++ CHECK(dispatcher.GetFunction(0x8B000001u) == nullptr);
++ REQUIRE(dispatcher.SetFunction(0x8B000000u, &DummyFn));
++ CHECK(dispatcher.GetFunction(0x8B000000u) == &DummyFn);
++}
++
++TEST_CASE("FunctionDispatcher: exceptions restore dispatch and trap state",
++ "[runtime][dispatcher]") {
++ auto& memory = GetTestMemory();
++ rex::runtime::ExportResolver resolver;
++ rex::runtime::FunctionDispatcher dispatcher(&memory, &resolver);
++ constexpr uint32_t base = 0x8A000000u;
++ REQUIRE(dispatcher.InitializeFunctionTable(base, 0x10000u, base, 0x100000u));
++ REQUIRE(dispatcher.SetFunction(base + 0x40, &ThrowingDispatchFn));
++ rex::runtime::ThreadState previous(1, 0x71000000u, 0x60000000u, &memory);
++ rex::runtime::ThreadState target(2, 0x70000000u, 0x60000000u, &memory);
++ auto* ctx = target.context();
++ ctx->lr = 0x12345678u;
++ ctx->r14.u64 = 0x14141414u;
++ rex::runtime::ThreadState::Bind(&previous);
++ SECTION("Execute") {
++ uint64_t args[] = {0};
++ REQUIRE_THROWS_AS(dispatcher.Execute(&target, base + 0x40, args, 1), int);
++ }
++ SECTION("ExecuteTrap") {
++ uint64_t args[] = {0};
++ REQUIRE_THROWS_AS(dispatcher.ExecuteTrap(&target, base + 0x40, args, 1), int);
++ CHECK(ctx->r14.u64 == 0x14141414u);
++ }
++ CHECK(ctx->r1.u64 == 0x70000000u);
++ CHECK(ctx->lr == 0x12345678u);
++ CHECK(rex::runtime::ThreadState::Get() == &previous);
++ rex::runtime::ThreadState::Bind(nullptr);
++}
+diff --git a/thirdparty/CMakeLists.txt b/thirdparty/CMakeLists.txt
+index f102b56..e23f430 100644
+--- a/thirdparty/CMakeLists.txt
++++ b/thirdparty/CMakeLists.txt
+@@ -374,6 +374,11 @@ if(REXGLUE_ENABLE_TRACY)
+
+ target_link_libraries(TracyClient PUBLIC Threads::Threads ${CMAKE_DL_LIBS})
+
++ if(WIN32 AND CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC")
++ # The Universal CRT exports _fileno; avoid the legacy POSIX alias.
++ target_compile_definitions(TracyClient PRIVATE fileno=_fileno)
++ endif()
++
+ if(WIN32 AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
+ target_link_libraries(TracyClient PUBLIC ws2_32 dbghelp)
+ endif()
+@@ -702,3 +707,8 @@ set_target_properties(libavutil libavcodec PROPERTIES
+ C_VISIBILITY_PRESET hidden
+ VISIBILITY_INLINES_HIDDEN ON
+ FOLDER "FFmpeg")
++
++if(WIN32 AND CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC")
++ target_compile_definitions(libavutil PRIVATE isatty=_isatty)
++ target_compile_definitions(SDL3-static PRIVATE itoa=_itoa)
++endif()
+diff --git a/include/rex/ui/vulkan/fence_wait_timing.h b/include/rex/ui/vulkan/fence_wait_timing.h
+new file mode 100644
+--- /dev/null
++++ b/include/rex/ui/vulkan/fence_wait_timing.h
+@@ -0,0 +1,67 @@
++#pragma once
++
++#include <algorithm>
++#include <chrono>
++#include <rex/cvar.h>
++#include <rex/logging.h>
++
++namespace rex::ui::vulkan {
++
++// Observe existing CPU fence waits without inserting any GPU operations.
++class FenceWaitTiming {
++ public:
++ enum class Reason { Other, Resolve, Memexport, FrameReuse, ResourceReuse, Occlusion, OutputDescriptors, IntermediateImage, PaintPipeline, AcquireImage, Count };
++ FenceWaitTiming(const char* role, const void* tracker,
++ Reason reason = Reason::Other, uint64_t fences = 1)
++ : role_(role), tracker_(tracker), reason_(reason), fences_(fences) {
++ // This diagnostic setting is selected before workers start, not hot-reloaded.
++ static thread_local const bool enabled = REXCVAR_QUERY(bool, vulkan_log_fence_waits);
++ enabled_ = enabled;
++ if (enabled_) start_ = Clock::now();
++ }
++ ~FenceWaitTiming() {
++ if (!enabled_) return;
++ const auto now = Clock::now();
++ const double ms = std::chrono::duration<double, std::milli>(now - start_).count();
++ struct Stats {
++ Clock::time_point start = Clock::now();
++ uint64_t calls = 0, over_8ms = 0, fences = 0;
++ double total = 0, maximum = 0;
++ };
++ static thread_local Stats all_stats[2][size_t(Reason::Count)];
++ const size_t role_index = role_[0] == 'g' ? 0 : 1;
++ Stats& stats = all_stats[role_index][size_t(reason_)];
++ ++stats.calls;
++ stats.fences += fences_;
++ stats.over_8ms += ms > 8.0;
++ stats.total += ms;
++ stats.maximum = std::max(stats.maximum, ms);
++ static thread_local Clock::time_point interval_start = Clock::now();
++ if (now - interval_start < std::chrono::seconds(5)) return;
++ constexpr const char* names[] = {"other", "resolve", "memexport", "frame_reuse",
++ "resource_reuse", "occlusion", "output_descriptors",
++ "intermediate_image", "paint_pipeline", "acquire_image"};
++ for (size_t role = 0; role < 2; ++role) {
++ for (size_t reason = 0; reason < size_t(Reason::Count); ++reason) {
++ Stats& entry = all_stats[role][reason];
++ if (!entry.calls) continue;
++ REXLOG_INFO("VulkanFenceWait: role={} reason={} calls={} fences={} "
++ "total={:.3f}ms max={:.3f}ms over8ms={}",
++ role == 0 ? "guest" : "presenter", names[reason], entry.calls,
++ entry.fences, entry.total, entry.maximum, entry.over_8ms);
++ entry = Stats{};
++ }
++ }
++ interval_start = now;
++ }
++ private:
++ using Clock = std::chrono::steady_clock;
++ const char* role_;
++ const void* tracker_;
++ Reason reason_;
++ uint64_t fences_;
++ bool enabled_ = false;
++ Clock::time_point start_{};
++};
++
++} // namespace rex::ui::vulkan
+diff --git a/src/graphics/shaders/bytecode/d3d12_5_1/float24_round_ps_position_only.h b/src/graphics/shaders/bytecode/d3d12_5_1/float24_round_ps_position_only.h
+new file mode 100644
+--- /dev/null
++++ b/src/graphics/shaders/bytecode/d3d12_5_1/float24_round_ps_position_only.h
+@@ -0,0 +1,73 @@
++// Derived from float24_round_ps.h: identical depth instructions, SV_Position at v0.
++// Generated by work/generate-position-only-depth.py; original licensing applies.
++const BYTE float24_round_ps_position_only[] = {
++ 68, 88, 66, 67, 162, 99, 171, 178, 104, 88, 180, 227, 99, 114, 31, 75, 42, 220, 126, 82,
++ 1, 0, 0, 0, 100, 5, 0, 0, 5, 0, 0, 0, 52, 0, 0, 0, 160, 0, 0, 0,
++ 212, 0, 0, 0, 8, 1, 0, 0, 200, 4, 0, 0, 82, 68, 69, 70, 100, 0, 0, 0,
++ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 0, 0, 0, 1, 5, 255, 255,
++ 0, 5, 0, 0, 60, 0, 0, 0, 19, 19, 68, 37, 60, 0, 0, 0, 24, 0, 0, 0,
++ 40, 0, 0, 0, 40, 0, 0, 0, 36, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0,
++ 77, 105, 99, 114, 111, 115, 111, 102, 116, 32, 40, 82, 41, 32, 72, 76, 83, 76, 32, 83,
++ 104, 97, 100, 101, 114, 32, 67, 111, 109, 112, 105, 108, 101, 114, 32, 49, 48, 46, 49, 0,
++ 73, 83, 71, 78, 44, 0, 0, 0, 1, 0, 0, 0, 8, 0, 0, 0, 32, 0, 0, 0,
++ 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 15, 4, 0, 0,
++ 83, 86, 95, 80, 111, 115, 105, 116, 105, 111, 110, 0, 79, 83, 71, 78, 44, 0, 0, 0,
++ 1, 0, 0, 0, 8, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
++ 3, 0, 0, 0, 255, 255, 255, 255, 1, 14, 0, 0, 83, 86, 95, 68, 101, 112, 116, 104,
++ 0, 171, 171, 171, 83, 72, 69, 88, 184, 3, 0, 0, 81, 0, 0, 0, 238, 0, 0, 0,
++ 106, 8, 0, 1, 100, 56, 0, 4, 66, 16, 16, 0, 0, 0, 0, 0, 1, 0, 0, 0,
++ 101, 0, 0, 2, 1, 192, 0, 0, 104, 0, 0, 2, 2, 0, 0, 0, 56, 32, 8, 7,
++ 18, 0, 16, 0, 0, 0, 0, 0, 42, 16, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0,
++ 0, 0, 0, 64, 80, 0, 16, 7, 34, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0,
++ 255, 255, 255, 127, 10, 0, 16, 0, 0, 0, 0, 0, 1, 0, 8, 7, 18, 0, 16, 0,
++ 0, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0,
++ 84, 0, 8, 7, 18, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0,
++ 1, 64, 0, 0, 248, 255, 255, 63, 140, 0, 16, 11, 34, 0, 16, 0, 0, 0, 0, 0,
++ 1, 64, 0, 0, 23, 0, 0, 0, 1, 64, 0, 0, 0, 0, 0, 0, 10, 0, 16, 0,
++ 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 128, 0, 85, 0, 32, 7, 66, 0, 16, 0,
++ 0, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 23, 0, 0, 0,
++ 30, 0, 32, 8, 66, 0, 16, 0, 0, 0, 0, 0, 42, 0, 16, 128, 65, 0, 0, 0,
++ 0, 0, 0, 0, 1, 64, 0, 0, 113, 0, 0, 0, 84, 0, 32, 7, 66, 0, 16, 0,
++ 0, 0, 0, 0, 42, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 24, 0, 0, 0,
++ 85, 0, 16, 7, 34, 0, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0,
++ 42, 0, 16, 0, 0, 0, 0, 0, 79, 0, 32, 7, 66, 0, 16, 0, 0, 0, 0, 0,
++ 10, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 128, 56, 30, 0, 8, 7,
++ 18, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0,
++ 0, 0, 0, 200, 55, 0, 8, 9, 18, 0, 16, 0, 0, 0, 0, 0, 42, 0, 16, 0,
++ 0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0,
++ 138, 0, 16, 9, 34, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 1, 0, 0, 0,
++ 1, 64, 0, 0, 3, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0, 30, 0, 8, 7,
++ 18, 0, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0,
++ 0, 0, 0, 0, 30, 0, 8, 7, 18, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0,
++ 0, 0, 0, 0, 1, 64, 0, 0, 3, 0, 0, 0, 138, 0, 56, 15, 114, 0, 16, 0,
++ 0, 0, 0, 0, 2, 64, 0, 0, 24, 0, 0, 0, 20, 0, 0, 0, 4, 0, 0, 0,
++ 0, 0, 0, 0, 2, 64, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 23, 0, 0, 0,
++ 0, 0, 0, 0, 6, 0, 16, 0, 0, 0, 0, 0, 135, 0, 64, 5, 130, 0, 16, 0,
++ 0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 30, 0, 64, 7, 130, 0, 16, 0,
++ 0, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 245, 255, 255, 255,
++ 55, 0, 64, 9, 130, 0, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0,
++ 58, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 21, 0, 0, 0, 30, 0, 8, 8,
++ 18, 0, 16, 0, 1, 0, 0, 0, 58, 0, 16, 128, 65, 0, 0, 0, 0, 0, 0, 0,
++ 1, 64, 0, 0, 1, 0, 0, 0, 55, 0, 8, 9, 18, 0, 16, 0, 1, 0, 0, 0,
++ 42, 0, 16, 0, 0, 0, 0, 0, 42, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0,
++ 1, 0, 0, 0, 41, 0, 64, 7, 130, 0, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0,
++ 0, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 1, 0, 64, 7, 130, 0, 16, 0,
++ 0, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 255, 255, 15, 0,
++ 55, 0, 16, 9, 34, 0, 16, 0, 0, 0, 0, 0, 42, 0, 16, 0, 0, 0, 0, 0,
++ 26, 0, 16, 0, 0, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 41, 0, 32, 7,
++ 66, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 1, 0, 0, 0, 1, 64, 0, 0,
++ 23, 0, 0, 0, 30, 0, 32, 7, 66, 0, 16, 0, 0, 0, 0, 0, 42, 0, 16, 0,
++ 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 128, 55, 41, 0, 16, 7, 34, 0, 16, 0,
++ 0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 3, 0, 0, 0,
++ 30, 0, 16, 7, 34, 0, 16, 0, 0, 0, 0, 0, 42, 0, 16, 0, 0, 0, 0, 0,
++ 26, 0, 16, 0, 0, 0, 0, 0, 55, 0, 8, 8, 1, 192, 0, 0, 10, 0, 16, 0,
++ 0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 0, 0,
++ 62, 0, 0, 1, 83, 84, 65, 84, 148, 0, 0, 0, 30, 0, 0, 0, 2, 0, 0, 0,
++ 0, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 11, 0, 0, 0, 8, 0, 0, 0,
++ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
++ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
++ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0,
++ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
++ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
++ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
++};
+diff --git a/src/graphics/shaders/bytecode/d3d12_5_1/float24_truncate_ps_position_only.h b/src/graphics/shaders/bytecode/d3d12_5_1/float24_truncate_ps_position_only.h
+new file mode 100644
+--- /dev/null
++++ b/src/graphics/shaders/bytecode/d3d12_5_1/float24_truncate_ps_position_only.h
+@@ -0,0 +1,42 @@
++// Derived from float24_truncate_ps.h: identical depth instructions, SV_Position at v0.
++// Generated by work/generate-position-only-depth.py; original licensing applies.
++const BYTE float24_truncate_ps_position_only[] = {
++ 68, 88, 66, 67, 58, 223, 9, 93, 150, 73, 58, 100, 233, 164, 57, 28, 8, 192, 95, 196,
++ 1, 0, 0, 0, 232, 2, 0, 0, 5, 0, 0, 0, 52, 0, 0, 0, 160, 0, 0, 0,
++ 212, 0, 0, 0, 16, 1, 0, 0, 76, 2, 0, 0, 82, 68, 69, 70, 100, 0, 0, 0,
++ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 0, 0, 0, 1, 5, 255, 255,
++ 0, 5, 0, 0, 60, 0, 0, 0, 19, 19, 68, 37, 60, 0, 0, 0, 24, 0, 0, 0,
++ 40, 0, 0, 0, 40, 0, 0, 0, 36, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0,
++ 77, 105, 99, 114, 111, 115, 111, 102, 116, 32, 40, 82, 41, 32, 72, 76, 83, 76, 32, 83,
++ 104, 97, 100, 101, 114, 32, 67, 111, 109, 112, 105, 108, 101, 114, 32, 49, 48, 46, 49, 0,
++ 73, 83, 71, 78, 44, 0, 0, 0, 1, 0, 0, 0, 8, 0, 0, 0, 32, 0, 0, 0,
++ 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 15, 4, 0, 0,
++ 83, 86, 95, 80, 111, 115, 105, 116, 105, 111, 110, 0, 79, 83, 71, 78, 52, 0, 0, 0,
++ 1, 0, 0, 0, 8, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
++ 3, 0, 0, 0, 255, 255, 255, 255, 1, 14, 0, 0, 83, 86, 95, 68, 101, 112, 116, 104,
++ 76, 101, 115, 115, 69, 113, 117, 97, 108, 0, 171, 171, 83, 72, 69, 88, 52, 1, 0, 0,
++ 81, 0, 0, 0, 77, 0, 0, 0, 106, 8, 0, 1, 100, 56, 0, 4, 66, 16, 16, 0,
++ 0, 0, 0, 0, 1, 0, 0, 0, 101, 0, 0, 2, 1, 112, 2, 0, 104, 0, 0, 2,
++ 1, 0, 0, 0, 56, 32, 8, 7, 18, 0, 16, 0, 0, 0, 0, 0, 42, 16, 16, 0,
++ 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 0, 64, 80, 0, 16, 7, 34, 0, 16, 0,
++ 0, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 128, 46,
++ 31, 0, 4, 3, 26, 0, 16, 0, 0, 0, 0, 0, 138, 0, 16, 9, 34, 0, 16, 0,
++ 0, 0, 0, 0, 1, 64, 0, 0, 8, 0, 0, 0, 1, 64, 0, 0, 23, 0, 0, 0,
++ 10, 0, 16, 0, 0, 0, 0, 0, 30, 0, 16, 8, 34, 0, 16, 0, 0, 0, 0, 0,
++ 26, 0, 16, 128, 65, 0, 0, 0, 0, 0, 0, 0, 1, 64, 0, 0, 116, 0, 0, 0,
++ 36, 0, 16, 7, 34, 0, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0,
++ 1, 64, 0, 0, 3, 0, 0, 0, 140, 0, 8, 11, 18, 0, 16, 0, 0, 0, 0, 0,
++ 26, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 0, 0, 1, 64, 0, 0,
++ 0, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0, 18, 0, 0, 1, 54, 0, 8, 5,
++ 18, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 0, 0, 21, 0, 0, 1,
++ 56, 0, 8, 6, 1, 112, 2, 0, 10, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0,
++ 0, 0, 0, 63, 62, 0, 0, 1, 83, 84, 65, 84, 148, 0, 0, 0, 12, 0, 0, 0,
++ 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0,
++ 1, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
++ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
++ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
++ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
++ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
++ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
++ 0, 0, 0, 0,
++};