diff --git a/.github/macports.yml b/.github/macports.yml index 976224723..c4a0974f7 100644 --- a/.github/macports.yml +++ b/.github/macports.yml @@ -18,4 +18,12 @@ ports: - name: opusfile select: [ universal ] - name: libvorbis + select: [ universal ] + - name: vulkan-headers + select: [ universal ] + - name: vulkan-loader + select: [ universal ] + - name: MoltenVK + select: [ universal ] + - name: shaderc select: [ universal ] \ No newline at end of file diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index c0b68d29d..8d7ac61b9 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -8,27 +8,47 @@ jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: submodules: recursive + fetch-depth: 0 # full history so the libultraship submodule gitlink resolves - name: Update machine run: sudo apt update - name: Install dependencies - run: sudo apt-get install gcc g++ git cmake ninja-build lsb-release libsdl2-dev libpng-dev libsdl2-net-dev libzip-dev zipcmp zipmerge ziptool nlohmann-json3-dev libtinyxml2-dev libspdlog-dev libboost-dev libopengl-dev libogg-dev libvorbis-dev + run: sudo apt-get install gcc g++ git cmake ninja-build lsb-release libsdl2-dev libpng-dev libsdl2-net-dev libzip-dev zipcmp zipmerge ziptool nlohmann-json3-dev libtinyxml2-dev libspdlog-dev libboost-dev libopengl-dev libogg-dev libvorbis-dev libtcc-dev libvulkan-dev libshaderc-dev glslang-dev spirv-tools + - name: ccache + uses: hendrikmuhs/ccache-action@v1.2.14 + with: + key: linux-validation-ccache-${{ github.ref }}-${{ github.sha }} + restore-keys: | + linux-validation-ccache-${{ github.ref }} + linux-validation-ccache- + - name: Cache build folders + uses: actions/cache@v6 + with: + key: linux-validation-build-${{ github.ref }}-${{ github.sha }} + restore-keys: | + linux-validation-build-${{ github.ref }} + linux-validation-build- + path: | + SDL2-2.24.1 + tinyxml2-10.0.0 - name: Install latest SDL run: | - export PATH="/usr/lib/ccache:/usr/local/opt/ccache/libexec:$PATH" - wget https://www.libsdl.org/release/SDL2-2.24.1.tar.gz - tar -xzf SDL2-2.24.1.tar.gz + if [ ! -d "SDL2-2.24.1" ]; then + wget https://www.libsdl.org/release/SDL2-2.24.1.tar.gz + tar -xzf SDL2-2.24.1.tar.gz + fi cd SDL2-2.24.1 ./configure make -j 10 sudo make install - name: Install latest tinyxml2 run: | - export PATH="/usr/lib/ccache:/usr/local/opt/ccache/libexec:$PATH" - wget https://github.com/leethomason/tinyxml2/archive/refs/tags/10.0.0.tar.gz - tar -xzf 10.0.0.tar.gz + if [ ! -d "tinyxml2-10.0.0" ]; then + wget https://github.com/leethomason/tinyxml2/archive/refs/tags/10.0.0.tar.gz + tar -xzf 10.0.0.tar.gz + fi cd tinyxml2-10.0.0 mkdir -p build cd build @@ -37,7 +57,8 @@ jobs: sudo make install - name: Build run: | - cmake -H. -Bbuild-cmake -GNinja -DCMAKE_BUILD_TYPE=Release + # Route the compiler through ccache (Ninja honors COMPILER_LAUNCHER). + cmake -H. -Bbuild-cmake -GNinja -DCMAKE_BUILD_TYPE=Release -D CMAKE_C_COMPILER_LAUNCHER=ccache -D CMAKE_CXX_COMPILER_LAUNCHER=ccache cmake --build build-cmake -j - name: Create Package run: | @@ -48,4 +69,4 @@ jobs: with: name: starship-linux-x64 path: starship-release - retention-days: 1 + retention-days: 1 \ No newline at end of file diff --git a/.github/workflows/mac.yml b/.github/workflows/mac.yml index 569dcca20..c6fdf7c04 100644 --- a/.github/workflows/mac.yml +++ b/.github/workflows/mac.yml @@ -11,13 +11,17 @@ jobs: - uses: actions/checkout@v6 with: submodules: recursive + fetch-depth: 0 # full history so the libultraship submodule gitlink resolves - uses: melusina-org/setup-macports@v1 with: parameters: '.github/macports.yml' - - uses: hendrikmuhs/ccache-action@v1.2 + - uses: hendrikmuhs/ccache-action@v1.2.14 with: key: macos # ccache-macos - name: Build run: | + # MacPorts installs the (universal) Vulkan SDK under /opt/local; point the build + # at it so the Vulkan backend is compiled in. + export VULKAN_SDK=/opt/local cmake -H. -Bbuild-cmake -GNinja -DCMAKE_BUILD_TYPE=Release -D CMAKE_C_COMPILER_LAUNCHER=ccache -D CMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_OSX_ARCHITECTURES="x86_64;arm64" cmake --build build-cmake -j \ No newline at end of file diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 6d98ae4e1..d2885b54a 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -11,20 +11,21 @@ jobs: generate-port-o2r: runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: submodules: true + fetch-depth: 0 # full history so the libultraship submodule gitlink (on a non-default branch of the fork) resolves - name: Install dependencies run: sudo apt-get install gcc g++ git cmake ninja-build lsb-release - name: ccache - uses: hendrikmuhs/ccache-action@v1.2.13 + uses: hendrikmuhs/ccache-action@v1.2.14 with: key: ${{ runner.os }}-o2r-ccache-${{ github.ref }}-${{ github.sha }} restore-keys: | ${{ runner.os }}-o2r-ccache-${{ github.ref }} ${{ runner.os }}-o2r-ccache- - name: Cache build folders - uses: actions/cache@v4 + uses: actions/cache@v6 with: key: ${{ runner.os }}-o2r-build-${{ github.ref }}-${{ github.sha }} restore-keys: | @@ -34,6 +35,9 @@ jobs: tools/Torch/cmake-build-release - name: Generate starship.o2r run: | + # Route the CMake-wrapped Torch build through ccache via env-var launchers + # (honored by Ninja/Makefile generators regardless of /usr/lib/ccache symlinks). + export CMAKE_C_COMPILER_LAUNCHER=ccache CMAKE_CXX_COMPILER_LAUNCHER=ccache export PATH="/usr/lib/ccache:/usr/local/opt/ccache/libexec:$PATH" make -C tools/Torch type=release -j3 tools/Torch/cmake-build-release/torch pack port starship.o2r o2r @@ -46,32 +50,111 @@ jobs: build-windows: needs: generate-port-o2r runs-on: windows-2022 + env: + WINDOWS_CERT_PFX_BASE64: ${{ secrets.WINDOWS_CERT_PFX_BASE64 }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: submodules: recursive + fetch-depth: 0 # full history so the libultraship submodule gitlink (on a non-default branch of the fork) resolves + - name: Setup MSVC + uses: ilammy/msvc-dev-cmd@v1 + - name: Cache Vulkan SDK + uses: actions/cache@v6 + with: + key: windows-vulkan-sdk-v1 + path: C:\VulkanSDK + - name: Install Vulkan SDK + shell: pwsh + run: | + # Skip the (large) download+install when the cache already restored the SDK. + if (-not (Test-Path "C:\VulkanSDK\Lib")) { + $url = "https://sdk.lunarg.com/sdk/download/latest/windows/vulkan_sdk.exe" + Invoke-WebRequest -Uri $url -OutFile "$env:RUNNER_TEMP\vulkan_sdk.exe" + $p = Start-Process -FilePath "$env:RUNNER_TEMP\vulkan_sdk.exe" -ArgumentList "--root","C:\VulkanSDK","--accept-licenses","--default-answer","--confirm-command","install" -Wait -PassThru + if ($p.ExitCode -ne 0) { throw "Vulkan SDK install failed with exit code $($p.ExitCode)" } + } + "VULKAN_SDK=C:\VulkanSDK" | Out-File -FilePath $env:GITHUB_ENV -Append + - name: Cache vcpkg binaries + uses: actions/cache@v6 + with: + key: windows-vcpkg-${{ github.ref }}-${{ github.sha }} + restore-keys: | + windows-vcpkg-${{ github.ref }} + windows-vcpkg- + path: | + ~\AppData\Local\vcpkg\archives + - name: sccache + uses: hendrikmuhs/ccache-action@v1.2.14 + with: + variant: sccache + key: windows-sccache-${{ github.ref }}-${{ github.sha }} + restore-keys: | + windows-sccache-${{ github.ref }} + windows-sccache- - name: Build run: | - cmake -S . -B "build/x64" -G "Visual Studio 17 2022" -T v143 -A x64 -DCMAKE_BUILD_TYPE=Release - cmake --build ./build/x64 --config Release --parallel 10 + # Use the runner's preinstalled vcpkg (blanking VCPKG_ROOT made automate-vcpkg + # try to clone into an empty path and fail). + $env:VCPKG_ROOT=$env:VCPKG_INSTALLATION_ROOT + # Ninja (single-config) so the compiler launcher works; sccache caches MSVC objects. + # msvc-dev-cmd (arch x64) puts cl.exe on PATH; the x64-windows-static triplet is + # set unconditionally in CMakeLists, so dropping -A x64 doesn't change it. + cmake -S . -B "build/x64" -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_COMPILER_LAUNCHER=sccache + cmake --build ./build/x64 --parallel 10 - name: Download starship.o2r uses: actions/download-artifact@v4 with: name: starship.o2r - path: ./build/x64/Release + path: ./build/x64 - name: Create Package + shell: pwsh run: | - mkdir starship-release - mv build/x64/Release/Starship.exe starship-release/ - mv build/x64/Release/starship.o2r starship-release/ - mv config.yml starship-release/ - mv assets starship-release/ + Write-Host "=== build/x64 contents ===" + Get-ChildItem build/x64 -Force | Format-Table Name, Length, Mode + New-Item -ItemType Directory -Force -Path starship-release | Out-Null + Move-Item build/x64/Starship.exe starship-release/ + Move-Item build/x64/starship.o2r starship-release/ + # Runtime DLLs the CMake POST_BUILD staged next to the exe (tcc.dll, shaderc_shared.dll, ...). + # Tolerant: moves whatever .dll files are present without erroring if there are none. + Get-ChildItem build/x64 -Filter *.dll | Move-Item -Destination starship-release/ + # Belt-and-suspenders: shaderc ships straight from the SDK even if it wasn't staged. + if (Test-Path "$env:VULKAN_SDK/Bin/shaderc_shared.dll") { + Copy-Item "$env:VULKAN_SDK/Bin/shaderc_shared.dll" starship-release/ -Force + } + # TCC runtime tree (hidden dir). Locate it under build/x64 wherever it landed. + $tcc = Get-ChildItem build/x64 -Filter .tcc -Directory -Force -Recurse | Select-Object -First 1 + if ($tcc) { + Move-Item $tcc.FullName starship-release/.tcc + } else { + Write-Warning ".tcc was not produced in build/x64 - scripting runtime will be missing!" + } + Move-Item config.yml starship-release/ + Move-Item assets starship-release/ Invoke-WebRequest -Uri "https://raw.githubusercontent.com/mdqinc/SDL_GameControllerDB/master/gamecontrollerdb.txt" -OutFile "starship-release/gamecontrollerdb.txt" + Write-Host "=== starship-release contents ===" + Get-ChildItem starship-release -Force -Recurse | Select-Object FullName + - name: Sign binaries + if: ${{ env.WINDOWS_CERT_PFX_BASE64 != '' }} + env: + WINDOWS_CERT_PASSWORD: ${{ secrets.WINDOWS_CERT_PASSWORD }} + shell: pwsh + run: | + $pfx = "$env:RUNNER_TEMP\codesign.pfx" + [IO.File]::WriteAllBytes($pfx, [Convert]::FromBase64String($env:WINDOWS_CERT_PFX_BASE64)) + $signtool = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\bin\*\x64\signtool.exe" | Sort-Object FullName -Descending | Select-Object -First 1).FullName + Get-ChildItem "starship-release" -Include *.exe,*.dll -Recurse | ForEach-Object { + & $signtool sign /f $pfx /p $env:WINDOWS_CERT_PASSWORD /fd SHA256 /tr http://timestamp.digicert.com /td SHA256 $_.FullName + if ($LASTEXITCODE -ne 0) { throw "signtool failed for $($_.FullName)" } + } + Remove-Item $pfx -Force - name: Upload build uses: actions/upload-artifact@v4 with: name: starship-windows path: starship-release + # `.tcc` is a hidden dir; upload-artifact@v4 drops hidden files by default. + include-hidden-files: true build-macos: needs: generate-port-o2r @@ -80,14 +163,19 @@ jobs: - uses: actions/checkout@v6 with: submodules: recursive + fetch-depth: 0 # full history so the libultraship submodule gitlink (on a non-default branch of the fork) resolves - uses: melusina-org/setup-macports@v1 with: parameters: '.github/macports.yml' - - uses: hendrikmuhs/ccache-action@v1.2 + - uses: hendrikmuhs/ccache-action@v1.2.14 with: key: macos # ccache-macos - name: Build run: | + # MacPorts installs the (universal) Vulkan SDK under /opt/local; point the + # build at it so find_package(Vulkan) + shaderc resolve and the Vulkan backend + # is compiled into the universal binary. + export VULKAN_SDK=/opt/local cmake -H. -Bbuild-cmake -GNinja -DCMAKE_BUILD_TYPE=Release -D CMAKE_C_COMPILER_LAUNCHER=ccache -D CMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_OSX_ARCHITECTURES="x86_64;arm64" cmake --build build-cmake -j - name: Download starship.o2r @@ -97,6 +185,7 @@ jobs: path: ./build-cmake - name: Create Package run: | + cp -r build-cmake/.tcc .tcc (cd build-cmake && cpack) mv _packages/*.dmg Starship.dmg mv README.md readme.txt @@ -107,18 +196,22 @@ jobs: path: | Starship.dmg readme.txt + .tcc + # `.tcc` is a hidden dir; upload-artifact@v4 drops hidden files by default. + include-hidden-files: true build-linux: needs: generate-port-o2r runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: submodules: recursive + fetch-depth: 0 # full history so the libultraship submodule gitlink (on a non-default branch of the fork) resolves - name: Update machine run: sudo apt update - name: Install dependencies - run: sudo apt-get install gcc g++ git cmake ninja-build lsb-release libsdl2-dev libpng-dev libsdl2-net-dev libzip-dev zipcmp zipmerge ziptool nlohmann-json3-dev libtinyxml2-dev libspdlog-dev libboost-dev libopengl-dev libogg-dev libvorbis-dev + run: sudo apt-get install gcc g++ git cmake ninja-build lsb-release libsdl2-dev libpng-dev libsdl2-net-dev libzip-dev zipcmp zipmerge ziptool nlohmann-json3-dev libtinyxml2-dev libspdlog-dev libboost-dev libopengl-dev libogg-dev libvorbis-dev libtcc-dev libvulkan-dev libshaderc-dev glslang-dev spirv-tools - name: ccache uses: hendrikmuhs/ccache-action@v1.2.14 with: @@ -127,7 +220,7 @@ jobs: linux-ccache-${{ github.ref }} linux-ccache- - name: Cache build folders - uses: actions/cache@v4 + uses: actions/cache@v6 with: key: linux-build-${{ github.ref }}-${{ github.sha }} restore-keys: | @@ -152,8 +245,10 @@ jobs: - name: Install latest tinyxml2 run: | export PATH="/usr/lib/ccache:/usr/local/opt/ccache/libexec:$PATH" - wget https://github.com/leethomason/tinyxml2/archive/refs/tags/10.0.0.tar.gz - tar -xzf 10.0.0.tar.gz + if [ ! -d "tinyxml2-10.0.0" ]; then + wget https://github.com/leethomason/tinyxml2/archive/refs/tags/10.0.0.tar.gz + tar -xzf 10.0.0.tar.gz + fi cd tinyxml2-10.0.0 mkdir -p build cd build @@ -181,12 +276,14 @@ jobs: path: ./build-cmake - name: Build run: | - cmake -H. -Bbuild-cmake -GNinja -DCMAKE_BUILD_TYPE=Release + # Route the compiler through ccache so the linux-ccache cache is actually used. + cmake -H. -Bbuild-cmake -GNinja -DCMAKE_BUILD_TYPE=Release -D CMAKE_C_COMPILER_LAUNCHER=ccache -D CMAKE_CXX_COMPILER_LAUNCHER=ccache cmake --build build-cmake --config Release -j3 (cd build-cmake && cpack -G External) wget -O gamecontrollerdb.txt https://raw.githubusercontent.com/mdqinc/SDL_GameControllerDB/master/gamecontrollerdb.txt mv README.md readme.txt mv build-cmake/*.appimage starship.appimage + cp -r build-cmake/.tcc .tcc - name: Upload build uses: actions/upload-artifact@v4 with: @@ -196,6 +293,9 @@ jobs: config.yml assets gamecontrollerdb.txt + .tcc + # `.tcc` is a hidden dir; upload-artifact@v4 drops hidden files by default. + include-hidden-files: true build-switch: needs: generate-port-o2r @@ -203,20 +303,35 @@ jobs: container: image: devkitpro/devkita64:20241023 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: submodules: recursive + fetch-depth: 0 # full history so the libultraship submodule gitlink (on a non-default branch of the fork) resolves + # ccache-action doesn't run cleanly inside the devkitpro container, so cache the + # ccache dir directly (workspace-relative so host and container share it). + - name: Cache ccache + uses: actions/cache@v6 + with: + key: switch-ccache-${{ github.ref }}-${{ github.sha }} + restore-keys: | + switch-ccache-${{ github.ref }} + switch-ccache- + path: | + .ccache - name: Install dependencies run: | sudo apt-get update - sudo apt-get install -y ninja-build + sudo apt-get install -y ninja-build ccache sudo apt-get remove -y cmake - git -C libultraship remote add nx https://github.com/sonicdcer/libultraship.git + git -C libultraship remote add nx https://github.com/Net64DD/libultraship.git git -C libultraship fetch nx - git -C libultraship checkout nx/main-nx_backup + git -C libultraship checkout nx/main-nx-nightly wget https://github.com/Kitware/CMake/releases/download/v3.28.3/cmake-3.28.3-linux-x86_64.sh -O /tmp/cmake.sh sudo sh /tmp/cmake.sh --prefix=/usr/local/ --exclude-subdir - cmake -H. -Bbuild-switch -GNinja -DCMAKE_TOOLCHAIN_FILE=/opt/devkitpro/cmake/Switch.cmake + # Route the devkitA64 cross-compiler through ccache; CCACHE_DIR is workspace-relative + # so the cached dir restored on the host is visible inside the container. + export CCACHE_DIR="$GITHUB_WORKSPACE/.ccache" + cmake -H. -Bbuild-switch -GNinja -DCMAKE_TOOLCHAIN_FILE=/opt/devkitpro/cmake/Switch.cmake -D CMAKE_C_COMPILER_LAUNCHER=ccache -D CMAKE_CXX_COMPILER_LAUNCHER=ccache cmake --build build-switch --config Release -j3 wget -O gamecontrollerdb.txt https://raw.githubusercontent.com/mdqinc/SDL_GameControllerDB/master/gamecontrollerdb.txt mv README.md readme.txt @@ -229,4 +344,4 @@ jobs: Starship.nro config.yml assets - gamecontrollerdb.txt + gamecontrollerdb.txt \ No newline at end of file diff --git a/.github/workflows/switch.yml b/.github/workflows/switch.yml index 3d83c850f..6cf71949a 100644 --- a/.github/workflows/switch.yml +++ b/.github/workflows/switch.yml @@ -10,20 +10,35 @@ jobs: container: image: devkitpro/devkita64:20241023 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: submodules: recursive + fetch-depth: 0 # full history so the libultraship submodule gitlink resolves + # ccache-action doesn't run cleanly inside the devkitpro container, so cache the + # ccache dir directly (workspace-relative so host and container share it). + - name: Cache ccache + uses: actions/cache@v6 + with: + key: switch-validation-ccache-${{ github.ref }}-${{ github.sha }} + restore-keys: | + switch-validation-ccache-${{ github.ref }} + switch-validation-ccache- + path: | + .ccache - name: Install dependencies run: | sudo apt-get update - sudo apt-get install -y ninja-build + sudo apt-get install -y ninja-build ccache sudo apt-get remove -y cmake git -C libultraship remote add nx https://github.com/sonicdcer/libultraship.git git -C libultraship fetch nx git -C libultraship checkout nx/main-nx_backup wget https://github.com/Kitware/CMake/releases/download/v3.28.3/cmake-3.28.3-linux-x86_64.sh -O /tmp/cmake.sh sudo sh /tmp/cmake.sh --prefix=/usr/local/ --exclude-subdir - cmake -H. -Bbuild-switch -GNinja -DCMAKE_TOOLCHAIN_FILE=/opt/devkitpro/cmake/Switch.cmake + # Route the devkitA64 cross-compiler through ccache; CCACHE_DIR is workspace-relative + # so the cached dir restored on the host is visible inside the container. + export CCACHE_DIR="$GITHUB_WORKSPACE/.ccache" + cmake -H. -Bbuild-switch -GNinja -DCMAKE_TOOLCHAIN_FILE=/opt/devkitpro/cmake/Switch.cmake -D CMAKE_C_COMPILER_LAUNCHER=ccache -D CMAKE_CXX_COMPILER_LAUNCHER=ccache cmake --build build-switch --config Release -j3 wget -O gamecontrollerdb.txt https://raw.githubusercontent.com/mdqinc/SDL_GameControllerDB/master/gamecontrollerdb.txt mv README.md readme.txt diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 842e34350..9a9ddb834 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -7,17 +7,88 @@ on: jobs: build: runs-on: windows-2022 + env: + WINDOWS_CERT_PFX_BASE64: ${{ secrets.WINDOWS_CERT_PFX_BASE64 }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: submodules: recursive + fetch-depth: 0 # full history so the libultraship submodule gitlink resolves + - name: Setup MSVC + uses: ilammy/msvc-dev-cmd@v1 + - name: Cache Vulkan SDK + uses: actions/cache@v6 + with: + key: windows-vulkan-sdk-v1 + path: C:\VulkanSDK + - name: Install Vulkan SDK + shell: pwsh + run: | + # Skip the (large) download+install when the cache already restored the SDK. + if (-not (Test-Path "C:\VulkanSDK\Lib")) { + $url = "https://sdk.lunarg.com/sdk/download/latest/windows/vulkan_sdk.exe" + Invoke-WebRequest -Uri $url -OutFile "$env:RUNNER_TEMP\vulkan_sdk.exe" + $p = Start-Process -FilePath "$env:RUNNER_TEMP\vulkan_sdk.exe" -ArgumentList "--root","C:\VulkanSDK","--accept-licenses","--default-answer","--confirm-command","install" -Wait -PassThru + if ($p.ExitCode -ne 0) { throw "Vulkan SDK install failed with exit code $($p.ExitCode)" } + } + "VULKAN_SDK=C:\VulkanSDK" | Out-File -FilePath $env:GITHUB_ENV -Append + - name: Cache vcpkg binaries + uses: actions/cache@v6 + with: + key: windows-validation-vcpkg-${{ github.ref }}-${{ github.sha }} + restore-keys: | + windows-validation-vcpkg-${{ github.ref }} + windows-validation-vcpkg- + path: | + ~\AppData\Local\vcpkg\archives + - name: sccache + uses: hendrikmuhs/ccache-action@v1.2.14 + with: + variant: sccache + key: windows-validation-sccache-${{ github.ref }}-${{ github.sha }} + restore-keys: | + windows-validation-sccache-${{ github.ref }} + windows-validation-sccache- - name: Build run: | - cmake -S . -B "build/x64" -G "Visual Studio 17 2022" -T v143 -A x64 -DCMAKE_BUILD_TYPE=Release - cmake --build ./build/x64 + # Use the runner's preinstalled vcpkg (blanking VCPKG_ROOT made automate-vcpkg + # try to clone into an empty path and fail). + $env:VCPKG_ROOT=$env:VCPKG_INSTALLATION_ROOT + # Ninja (single-config) so the compiler launcher works; sccache caches MSVC objects. + cmake -S . -B "build/x64" -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_COMPILER_LAUNCHER=sccache + cmake --build ./build/x64 --parallel 10 + - name: Stage runtime deps + shell: pwsh + run: | + Write-Host "=== build/x64 contents (top level) ===" + Get-ChildItem build/x64 -Force | Format-Table Name, Length, Mode + # Ensure shaderc ships even if the CMake POST_BUILD didn't stage it. + if ((Test-Path "$env:VULKAN_SDK/Bin/shaderc_shared.dll") -and -not (Test-Path "build/x64/shaderc_shared.dll")) { + Copy-Item "$env:VULKAN_SDK/Bin/shaderc_shared.dll" build/x64/ -Force + Write-Host "Copied shaderc_shared.dll from the Vulkan SDK." + } + Write-Host "=== .tcc present? ===" + if (Test-Path build/x64/.tcc) { Get-ChildItem build/x64/.tcc -Recurse -Force | Select-Object FullName } + else { Write-Warning ".tcc was not produced in build/x64!" } + - name: Sign binaries + if: ${{ env.WINDOWS_CERT_PFX_BASE64 != '' }} + env: + WINDOWS_CERT_PASSWORD: ${{ secrets.WINDOWS_CERT_PASSWORD }} + shell: pwsh + run: | + $pfx = "$env:RUNNER_TEMP\codesign.pfx" + [IO.File]::WriteAllBytes($pfx, [Convert]::FromBase64String($env:WINDOWS_CERT_PFX_BASE64)) + $signtool = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\bin\*\x64\signtool.exe" | Sort-Object FullName -Descending | Select-Object -First 1).FullName + # Sign the exe and the bundled DLLs we ship (tcc.dll is the usual AV trigger). + Get-ChildItem "build/x64" -Include Starship.exe,tcc.dll,shaderc_shared.dll -Recurse | ForEach-Object { + & $signtool sign /f $pfx /p $env:WINDOWS_CERT_PASSWORD /fd SHA256 /tr http://timestamp.digicert.com /td SHA256 $_.FullName + if ($LASTEXITCODE -ne 0) { throw "signtool failed for $($_.FullName)" } + } + Remove-Item $pfx -Force - name: Upload build uses: actions/upload-artifact@v4 with: name: starship-windows - path: ./build/x64/Debug - retention-days: 1 \ No newline at end of file + path: ./build/x64 + retention-days: 1 + include-hidden-files: true \ No newline at end of file diff --git a/.gitignore b/.gitignore index 0ef6aa298..703c5f405 100644 --- a/.gitignore +++ b/.gitignore @@ -58,4 +58,18 @@ src/eu/ src/cn/ properties.h -mods*/ \ No newline at end of file +mods*/ +/src/port/build.c +!/src/port/build.h +!/src/port/build.c.in +!/src/port/mods/ +workspace/* +!workspace/template +workspace/template/output/* +!workspace/template/output/manifest.json +*.pem +.tcc +sf64.aliases.json +*.raw +*.ssproj +*.wav diff --git a/.gitmodules b/.gitmodules index a893b7a82..f4a657392 100644 --- a/.gitmodules +++ b/.gitmodules @@ -6,4 +6,4 @@ url = https://github.com/HarbourMasters/Torch [submodule "libultraship"] path = libultraship - url = https://github.com/Kenix3/libultraship.git + url = https://github.com/KiritoDv/libultraship.git diff --git a/CMakeLists.txt b/CMakeLists.txt index e7d0e797a..f532a5e69 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4,6 +4,9 @@ cmake_minimum_required(VERSION 3.16.0 FATAL_ERROR) project(Starship VERSION 2.0.0 LANGUAGES C CXX ASM) include(FetchContent) +include(cmake/starship-cvars.cmake) +include(cmake/lus-cvars.cmake) + set(NATO_PHONETIC_ALPHABET "Alfa" "Bravo" "Charlie" "Delta" "Echo" "Foxtrot" "Golf" "Hotel" "India" "Juliett" "Kilo" "Lima" "Mike" "November" "Oscar" "Papa" @@ -20,6 +23,41 @@ list(GET NATO_PHONETIC_ALPHABET ${PATCH_INDEX} PROJECT_PATCH_WORD) set(PROJECT_BUILD_NAME "Barnard ${PROJECT_PATCH_WORD}" CACHE STRING "" FORCE) set(PROJECT_TEAM "SonicDcer & Lywx" CACHE STRING "" FORCE) +# Get Git Information +execute_process( + COMMAND git branch --show-current + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + OUTPUT_VARIABLE GIT_BRANCH + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +set(CMAKE_PROJECT_GIT_BRANCH "${GIT_BRANCH}" CACHE STRING "Git branch" FORCE) + +execute_process( + COMMAND git rev-parse HEAD + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + OUTPUT_VARIABLE GIT_COMMIT_HASH + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +# Get only the first 7 characters of the hash +string(SUBSTRING "${GIT_COMMIT_HASH}" 0 7 SHORT_COMMIT_HASH) + +set(CMAKE_PROJECT_GIT_COMMIT_HASH "${SHORT_COMMIT_HASH}" CACHE STRING "Git commit hash" FORCE) + +execute_process( + COMMAND git describe --tags --abbrev=0 --exact-match HEAD + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + OUTPUT_VARIABLE GIT_COMMIT_TAG + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +if(NOT GIT_COMMIT_TAG) + set(GIT_COMMIT_TAG "" CACHE STRING "Git commit tag" FORCE) +endif() + +set(CMAKE_PROJECT_GIT_COMMIT_TAG "${GIT_COMMIT_TAG}" CACHE STRING "Git commit tag" FORCE) + if(APPLE) enable_language(OBJCXX) endif() @@ -30,8 +68,8 @@ set(CMAKE_OSX_DEPLOYMENT_TARGET "10.15" CACHE STRING "Minimum OS X deployment ve # Set the C++ standard and enable the MSVC parallel build option set(CMAKE_CXX_STANDARD 20 CACHE STRING "The C++ standard to use") set(CMAKE_C_STANDARD 11 CACHE STRING "The C standard to use") -#add_compile_options(-fsanitize=address) -#add_link_options(-fsanitize=address) +# add_compile_options(-fsanitize=address) +# add_link_options(-fsanitize=address) # Add a custom module path to locate additional CMake modules set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/modules/") @@ -43,7 +81,7 @@ include(cmake/automate-vcpkg.cmake) set(VCPKG_TRIPLET x64-windows-static) set(VCPKG_TARGET_TRIPLET x64-windows-static) vcpkg_bootstrap() -vcpkg_install_packages(zlib bzip2 libzip libpng sdl2 glew glfw3 nlohmann-json tinyxml2 spdlog libogg libvorbis) +vcpkg_install_packages(zlib bzip2 libzip libpng sdl2[vulkan] glew glfw3 nlohmann-json tinyxml2 spdlog libogg libvorbis) set_property(DIRECTORY ${CMAKE_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT ${PROJECT_NAME}) set_property(DIRECTORY ${CMAKE_SOURCE_DIR} PROPERTY VS_DEBUGGER_WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}) @@ -56,15 +94,20 @@ set(CPP "${CMAKE_C_COMPILER}" "-E" "-P" "-Wno-trigraphs" "-x" "c") endif() if(IOS) -set(PLATFORM "OS64") -include(cmake/ios.toolchain.cmake) -add_compile_definitions( - PLATFORM_IOS=1 -) -set(CMAKE_XCODE_ATTRIBUTE_DEVELOPMENT_TEAM "YOUR_TEAM_ID") -set(PROJECT_ID "dev.net64.game") + set(PLATFORM "OS64") + include(cmake/ios.toolchain.cmake) + add_compile_definitions( + PLATFORM_IOS=1 + ) + set(CMAKE_XCODE_ATTRIBUTE_DEVELOPMENT_TEAM "YOUR_TEAM_ID") + set(PROJECT_ID "${BUNDLE_ID}") endif() +################################################################################ +# Sources +################################################################################ +configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/src/port/build.c.in ${CMAKE_CURRENT_SOURCE_DIR}/src/port/build.c @ONLY) + ################################################################################ # Set target arch type if empty. Visual studio solution generator provides it. ################################################################################ @@ -80,6 +123,11 @@ if (CMAKE_SYSTEM_NAME STREQUAL "Windows") endif() endif() +################################################################################ +# Use solution folders feature +################################################################################ +set_property(GLOBAL PROPERTY USE_FOLDERS ON) + ################################################################################ # Global configuration types ################################################################################ @@ -106,10 +154,9 @@ add_compile_definitions( F3DEX_GBI=1 _LANGUAGE_C _USE_MATH_DEFINES - CIMGUI_DEFINE_ENUMS_AND_STRUCTS NON_MATCHING=1 NON_EQUIVALENT=1 - AVOID_UB=1 + AVOID_UB=1 GBI_FLOATS=1 ) @@ -165,8 +212,15 @@ list(FILTER ALL_FILES EXCLUDE REGEX "src/sys/sys_timer.c") list(FILTER ALL_FILES EXCLUDE REGEX "src/sys/sys_fault.c") list(FILTER ALL_FILES EXCLUDE REGEX "src/mods/object_ram.c") +# Create source groups that match the real file directory paths +foreach(source IN LISTS ALL_FILES) + get_filename_component(source_path "${source}" PATH) + string(REPLACE "/" "\\" source_path_adjusted "${source_path}") + source_group("${source_path_adjusted}" FILES "${source}") +endforeach() + if (CMAKE_SYSTEM_NAME STREQUAL "iOS") - set(IOS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/ios) + set(IOS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/ios) set(STORYBOARD_FILE ${IOS_DIR}/Launch.storyboard) set(IMAGE_FILES ${IOS_DIR}/PoweredBy.png) @@ -175,7 +229,6 @@ if (CMAKE_SYSTEM_NAME STREQUAL "iOS") list(APPEND ALL_FILES ${STORYBOARD_FILE} ${IMAGE_FILES} ${ICON_FILES}) add_executable(${PROJECT_NAME} ${ALL_FILES}) - set_xcode_property(${PROJECT_NAME} PRODUCT_BUNDLE_IDENTIFIER ${PROJECT_ID} All) set_target_properties( ${PROJECT_NAME} PROPERTIES @@ -227,7 +280,7 @@ include_directories(${SSE2NEON_DIR}) FetchContent_Declare( dr_libs GIT_REPOSITORY https://github.com/mackron/dr_libs.git - GIT_TAG da35f9d6c7374a95353fd1df1d394d44ab66cf01 + GIT_TAG da35f9d6c7374a95353fd1df1d394d44ab66cf01 ) FetchContent_MakeAvailable(dr_libs) @@ -235,44 +288,90 @@ FetchContent_MakeAvailable(dr_libs) # Libultraship Integration # #==============================================================================# +# Removes MPQ/OTR support +set(EXCLUDE_MPQ_SUPPORT TRUE CACHE BOOL "") +set(ENABLE_EXP_AUTO_CONFIGURE_CONTROLLERS ON CACHE BOOL "") +add_compile_definitions(EXCLUDE_MPQ_SUPPORT) + +if(CMAKE_SYSTEM_NAME STREQUAL "NintendoSwitch") + find_package(SDL2) +endif() + include_directories( ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/src - ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/include ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/include/libultraship - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/src - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/src/log - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/src/debug - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/src/menu - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/src/utils - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/src/utils/binarytools - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/src/config - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/src/resource - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/src/resource/type - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/src/resource/factory - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/src/audio - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/src/window - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/src/window/gui - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/src/config - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/src/public - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/src/public/libultra - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/src/public/bridge - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/extern - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/extern/tinyxml2 - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/libultraship/Lib/ - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/libultraship/Lib/libjpeg/include/ - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/libultraship/Lib/spdlog/include/ - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/src/graphic/Fast3D/U64/PR - ${CMAKE_CURRENT_SOURCE_DIR}/libultraship/src/graphic ${SDL2_INCLUDE_DIRS} ${GLEW_INCLUDE_DIRS} ${dr_libs_SOURCE_DIR} ) +if(NOT CMAKE_SYSTEM_NAME STREQUAL "NintendoSwitch") + set(ENABLE_SCRIPTING ON CACHE BOOL "" FORCE) +else() + #=================== tinyxml2 =================== + # devkitPro portlibs may have tinyxml2 headers/lib but no CMake config that + # exports tinyxml2::tinyxml2. Always fetch from source so both this project + # and libultraship's find_package(tinyxml2 REQUIRED) get a proper target. + set(tinyxml2_BUILD_TESTING OFF) + FetchContent_Declare( + tinyxml2 + GIT_REPOSITORY https://github.com/leethomason/tinyxml2.git + GIT_TAG 10.0.0 + OVERRIDE_FIND_PACKAGE + ) + FetchContent_MakeAvailable(tinyxml2) +endif() +set(GBI_UCODE F3DEX_GBI CACHE STRING "GBI ucode version" FORCE) add_subdirectory(libultraship ${CMAKE_CURRENT_SOURCE_DIR}/libultraship) add_dependencies(${PROJECT_NAME} libultraship) -target_link_libraries(${PROJECT_NAME} PRIVATE libultraship) +if(CMAKE_SYSTEM_NAME STREQUAL "NintendoSwitch") + target_link_libraries(${PROJECT_NAME} PRIVATE libultraship) +else() + target_link_libraries(${PROJECT_NAME} PRIVATE "$") +endif() +set_target_properties(${PROJECT_NAME} PROPERTIES ENABLE_EXPORTS TRUE) +set_target_properties(${PROJECT_NAME} PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS TRUE) + +#=================== cimgui =================== +FetchContent_Declare( + cimgui + GIT_REPOSITORY https://github.com/cimgui/cimgui.git + GIT_TAG 1.91.9bdock + GIT_SUBMODULES "" +) +if(POLICY CMP0169) + cmake_policy(SET CMP0169 OLD) +endif() +FetchContent_Populate(cimgui) +FetchContent_GetProperties(ImGui) +file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/_deps") +file(CREATE_LINK "${imgui_SOURCE_DIR}" "${CMAKE_BINARY_DIR}/_deps/imgui" SYMBOLIC) + +add_library(cimgui STATIC ${cimgui_SOURCE_DIR}/cimgui.cpp) + +target_include_directories(cimgui + PRIVATE "${CMAKE_BINARY_DIR}/_deps" + PUBLIC "${cimgui_SOURCE_DIR}" +) + +target_compile_definitions(cimgui + INTERFACE CIMGUI_DEFINE_ENUMS_AND_STRUCTS +) + +target_link_libraries(cimgui PUBLIC ImGui) +if(CMAKE_SYSTEM_NAME STREQUAL "NintendoSwitch") + target_link_libraries(${PROJECT_NAME} PRIVATE cimgui) +else() + target_link_libraries(${PROJECT_NAME} PRIVATE "$") +endif() + +if(${CMAKE_SYSTEM_NAME} STREQUAL "iOS") + get_property(IOS_TOOLCHAIN_FILE GLOBAL PROPERTY IOS_TOOLCHAIN_FILE) + include(${IOS_TOOLCHAIN_FILE}) + set(BUNDLE_ID "dev.hm64.soh") + set(SIGN_LIBRARY ON) +endif() if (CMAKE_SYSTEM_NAME STREQUAL "Windows") target_compile_definitions(${PROJECT_NAME} PRIVATE @@ -329,7 +428,7 @@ if (CMAKE_SYSTEM_NAME STREQUAL "Windows") find_package(Vorbis CONFIG REQUIRED) link_libraries(Vorbis::vorbisfile) - set(ADDITIONAL_LIBRARY_DEPENDENCIES + set(ADDITIONAL_LIBRARY_DEPENDENCIES "$<$:SDL2_net::SDL2_net-static>" "Ogg::ogg" "Vorbis::vorbis" @@ -377,17 +476,7 @@ if(USE_NETWORKING) target_compile_definitions(${PROJECT_NAME} PRIVATE USE_NETWORKING) endif() -option(USE_STANDALONE "Build as a standalone executable" OFF) -option(BUILD_STORMLIB "Build with StormLib support" OFF) - -option(BUILD_SM64 "Build with Super Mario 64 support" OFF) -option(BUILD_MK64 "Build with Mario Kart 64 support" OFF) -option(BUILD_FZERO "Build with F-Zero X support" OFF) -add_subdirectory(tools/Torch) -target_link_libraries(${PROJECT_NAME} PRIVATE torch "${ADDITIONAL_LIBRARY_DEPENDENCIES}") - if(CMAKE_SYSTEM_NAME MATCHES "NintendoSwitch") - nx_generate_nacp(${PROJECT_NAME}.nacp NAME "${PROJECT_NAME}" AUTHOR "${PROJECT_TEAM}" @@ -400,81 +489,62 @@ nx_create_nro(${PROJECT_NAME} ) INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.nro DESTINATION . COMPONENT ${PROJECT_NAME}) +else() +option(USE_STANDALONE "Build as a standalone executable" OFF) +option(BUILD_STORMLIB "Build with StormLib support" OFF) + +option(BUILD_SM64 "Build with Super Mario 64 support" OFF) +option(BUILD_MK64 "Build with Mario Kart 64 support" OFF) +option(BUILD_SF64 "Build with Star Fox 64 support" ON) +option(BUILD_FZERO "Build with F-Zero X support" OFF) +option(BUILD_MARIO_ARTIST "Build with Mario Artist support" OFF) +add_subdirectory(tools/Torch) +list(APPEND ADDITIONAL_LIBRARY_DEPENDENCIES torch) endif() +target_link_libraries(${PROJECT_NAME} PRIVATE "${ADDITIONAL_LIBRARY_DEPENDENCIES}") ################################################################################ # Compile and link options ################################################################################ if(MSVC) - if("${CMAKE_VS_PLATFORM_NAME}" STREQUAL "x64") - target_compile_options(${PROJECT_NAME} PRIVATE - $<$: - /w; - /Od; - /MTd - > - $<$: - /Oi; - /Gy; - /W3; - /MT - > - /permissive-; - /MP; - ${DEFAULT_CXX_DEBUG_INFORMATION_FORMAT}; - ${DEFAULT_CXX_EXCEPTION_HANDLING} - ) - target_compile_options(${PROJECT_NAME} PRIVATE $<$:/ZI;>) - target_compile_options(${PROJECT_NAME} PRIVATE $<$:/Zi;>) - elseif("${CMAKE_VS_PLATFORM_NAME}" STREQUAL "Win32") - target_compile_options(${PROJECT_NAME} PRIVATE - $<$: - /MTd - > - $<$: - /O2; - /Oi; - /Gy; - /MT - > - /permissive-; - /MP; - /w; - ${DEFAULT_CXX_DEBUG_INFORMATION_FORMAT}; - ${DEFAULT_CXX_EXCEPTION_HANDLING} - ) - endif() - if("${CMAKE_VS_PLATFORM_NAME}" STREQUAL "x64") - target_link_options(${PROJECT_NAME} PRIVATE - $<$: - /INCREMENTAL - > - $<$: - /OPT:REF; - /OPT:ICF; - /INCREMENTAL:NO; - /FORCE:MULTIPLE - > - /MANIFEST:NO; - /DEBUG; - /SUBSYSTEM:WINDOWS - ) - elseif("${CMAKE_VS_PLATFORM_NAME}" STREQUAL "Win32") - target_link_options(${PROJECT_NAME} PRIVATE - $<$: - /STACK:8777216 - > - $<$: - /OPT:REF; - /OPT:ICF; - /INCREMENTAL:NO; - /FORCE:MULTIPLE - > - /MANIFEST:NO; - /DEBUG; - /SUBSYSTEM:WINDOWS - ) - endif() + target_compile_options(${PROJECT_NAME} PRIVATE + $<$: + /w; + /Od + > + $<$: + /Oi; + /Gy; + /W3 + > + + /wd4024 #different types for formal and actual parameter [x]. Usually seen along side 4047. + /wd4047 #'uintptr_t' differs in levels of indirection from 'Gfx *'. Usually caused by passing a uintptr_t into a function expecting a pointer-types + /wd4090 #'initializing': different 'const' qualifiers. Caused when initializing a non const struct member with a const char*. + /wd4101 # unreferenced local variable. Things like stack pads. + /wd4133 #incompatible types. Usually caused by passing a c string into a function that takes a pointer. + /wd4244 #conversion from [a] to [b]. Used to warn when copying to smaller type without a cast. + /sdl-; + /permissive-; + /MP; + ${DEFAULT_CXX_DEBUG_INFORMATION_FORMAT}; + ${DEFAULT_CXX_EXCEPTION_HANDLING} + ) + target_compile_options(${PROJECT_NAME} PRIVATE $<$:/ZI;>) + target_link_options(${PROJECT_NAME} PRIVATE + $<$: + /INCREMENTAL + > + $<$: + /OPT:REF; + /OPT:ICF; + /INCREMENTAL:NO; + /FORCE:MULTIPLE + > + /MANIFEST:NO; + /DEBUG; + /SUBSYSTEM:WINDOWS + ) # Remove /RTC from msvc flags foreach (fentry @@ -604,6 +674,38 @@ add_custom_command( COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/assets/" "$/assets/" ) +include(${CMAKE_CURRENT_SOURCE_DIR}/libultraship/cmake/SetupTccRuntime.cmake) + + +set(PROPERTY_READER_GUARD_DISABLED TRUE) +if(CMAKE_SYSTEM_NAME MATCHES "Darwin") + lus_setup_tcc_runtime(${PROJECT_NAME} RESOURCES_DIR "../Resources/.tcc") +else() + lus_setup_tcc_runtime(${PROJECT_NAME}) +endif() +unset(PROPERTY_READER_GUARD_DISABLED) + +if (CMAKE_SYSTEM_NAME STREQUAL "Windows") + add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "$" + "$" + COMMAND_EXPAND_LISTS + COMMENT "Copying runtime DLL dependencies next to ${PROJECT_NAME}.exe..." + ) + # TARGET_RUNTIME_DLLS can miss shaderc depending on how the Vulkan SDK exports it, + # so also copy it explicitly from the SDK when present. + find_file(STARSHIP_SHADERC_DLL NAMES shaderc_shared.dll + HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") + if (STARSHIP_SHADERC_DLL) + add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${STARSHIP_SHADERC_DLL}" "$" + COMMENT "Copying shaderc_shared.dll next to ${PROJECT_NAME}.exe..." + ) + endif() +endif() + if(NOT CMAKE_SYSTEM_NAME STREQUAL "NintendoSwitch") include(ExternalProject) ExternalProject_Add(TorchExternal @@ -621,7 +723,7 @@ add_custom_target( ExtractAssets DEPENDS TorchExternal WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} - COMMAND ${TORCH_EXECUTABLE} o2r baserom.z64 + COMMAND ${TORCH_EXECUTABLE} o2r baserom.z64 -u ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH} COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_SOURCE_DIR}/sf64.o2r" "${CMAKE_BINARY_DIR}/sf64.o2r" ) @@ -629,15 +731,25 @@ add_custom_target( GeneratePortO2R DEPENDS TorchExternal WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} - COMMAND ${TORCH_EXECUTABLE} pack port starship.o2r o2r + COMMAND ${TORCH_EXECUTABLE} pack port starship.o2r o2r -u ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH} COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_SOURCE_DIR}/starship.o2r" "${CMAKE_BINARY_DIR}/starship.o2r" ) find_program(CURL NAMES curl DOC "Path to the curl program. Used to download files.") -execute_process(COMMAND ${CURL} -sSfL https://raw.githubusercontent.com/gabomdq/SDL_GameControllerDB/master/gamecontrollerdb.txt -o ${CMAKE_BINARY_DIR}/gamecontrollerdb.txt OUTPUT_VARIABLE RESULT) +execute_process(COMMAND ${CURL} -sSfL https://raw.githubusercontent.com/gabomdq/SDL_GameControllerDB/master/gamecontrollerdb.txt -o ${CMAKE_BINARY_DIR}/gamecontrollerdb.txt OUTPUT_VARIABLE RESULT ERROR_QUIET) if("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux") install(FILES "${CMAKE_BINARY_DIR}/starship.o2r" DESTINATION . COMPONENT ${PROJECT_NAME}) + install(DIRECTORY "${CMAKE_SOURCE_DIR}/assets/" DESTINATION ./assets COMPONENT ${PROJECT_NAME}) + install(FILES "${CMAKE_BINARY_DIR}/config.yml" DESTINATION . COMPONENT ${PROJECT_NAME}) +endif() + +if ("${CMAKE_SYSTEM_NAME}" STREQUAL "Windows") + install(FILES $ DESTINATION ./debug COMPONENT ${PROJECT_NAME}) + install(FILES "${CMAKE_BINARY_DIR}/starship.o2r" DESTINATION . COMPONENT ${PROJECT_NAME}) + # Ship the resolved runtime DLLs (shaderc_shared.dll, tcc.dll, SDL2.dll, ...) + # so the install/zip package runs standalone, matching the build-tree copy above. + install(FILES "$" DESTINATION . COMPONENT ${PROJECT_NAME}) endif() if(CMAKE_SYSTEM_NAME MATCHES "Darwin") @@ -665,15 +777,19 @@ add_custom_target(CreateOSXIcons INSTALL(FILES ${CMAKE_BINARY_DIR}/config.yml DESTINATION ../Resources COMPONENT Starship) INSTALL(DIRECTORY ${CMAKE_BINARY_DIR}/assets/ DESTINATION ../Resources/assets COMPONENT Starship) + if(ENABLE_SCRIPTING) + INSTALL(FILES "$" DESTINATION ../MacOS COMPONENT Starship) + endif() + # Fix bundle to include and relink all dependencies install(CODE " include(BundleUtilities) - fixup_bundle(\"\${CMAKE_INSTALL_PREFIX}/../MacOS/Starship\" \"\" \"${dirs}\") + fixup_bundle(\"\${CMAKE_INSTALL_PREFIX}/../MacOS/Starship\" \"\" \"${CMAKE_BINARY_DIR}\") ") endif() set_property(TARGET ${PROJECT_NAME} PROPERTY APPIMAGE_DESKTOP_FILE_TERMINAL YES) -set_property(TARGET ${PROJECT_NAME} PROPERTY APPIMAGE_DESKTOP_FILE "${CMAKE_SOURCE_DIR}/Starship.desktop") +set_property(TARGET ${PROJECT_NAME} PROPERTY APPIMAGE_DESKTOP_FILE "${CMAKE_SOURCE_DIR}/${PROJECT_NAME}.desktop") set_property(TARGET ${PROJECT_NAME} PROPERTY APPIMAGE_ICON_FILE "${CMAKE_SOURCE_DIR}/logo.png") endif() diff --git a/assets/yaml/us/rev1/ast_audio.yaml b/assets/yaml/us/rev1/ast_audio.yaml index cb0727b7e..a695d5ebc 100644 --- a/assets/yaml/us/rev1/ast_audio.yaml +++ b/assets/yaml/us/rev1/ast_audio.yaml @@ -28,4 +28,7852 @@ audio_soundfont_table: { type: NAUDIO:V1:AUDIO_TABLE, format: SOUNDFONT, offset: 0xC4690, symbol: gSoundFontTableInit } audio_seq_font_table: - { type: ARRAY, count: 283, array_type: u8, offset: 0xC48B0, symbol: gSeqFontTableInit } \ No newline at end of file + { type: ARRAY, count: 283, array_type: u8, offset: 0xC48B0, symbol: gSeqFontTableInit } + +a6_caiman_caiman_here: + type: NAUDIO:V1:SAMPLE + offset: 0x98A0 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_caiman_caiman_here + +a6_caiman_do_you_copy: + type: NAUDIO:V1:SAMPLE + offset: 0x9970 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_caiman_do_you_copy + +a6_caiman_emergency_maneuvers: + type: NAUDIO:V1:SAMPLE + offset: 0x9990 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_caiman_emergency_maneuvers + +a6_caiman_no_problems: + type: NAUDIO:V1:SAMPLE + offset: 0x9950 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_caiman_no_problems + +a6_caiman_not_yet_sir: + type: NAUDIO:V1:SAMPLE + offset: 0x9B30 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_caiman_not_yet_sir + +a6_caiman_the_last_line_has_been_breached: + type: NAUDIO:V1:SAMPLE + offset: 0x9EB0 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_caiman_the_last_line_has_been_breached + +a6_caiman_theyre_through_the_second_line: + type: NAUDIO:V1:SAMPLE + offset: 0x9E10 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_caiman_theyre_through_the_second_line + +a6_caiman_theyve_broken_through_the_first_line: + type: NAUDIO:V1:SAMPLE + offset: 0x9DF0 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_caiman_theyve_broken_through_the_first_line + +a6_commander_are_crazy: + type: NAUDIO:V1:SAMPLE + offset: 0x9E50 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_commander_are_crazy + +a6_commander_dang: + type: NAUDIO:V1:SAMPLE + offset: 0x9E70 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_commander_dang + +a6_commander_deploy_it_now: + type: NAUDIO:V1:SAMPLE + offset: 0x9E90 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_commander_deploy_it_now + +a6_commander_did_we_get_em: + type: NAUDIO:V1:SAMPLE + offset: 0x9B10 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_commander_did_we_get_em + +a6_commander_dont_let_em_through: + type: NAUDIO:V1:SAMPLE + offset: 0x9DD0 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_commander_dont_let_em_through + +a6_commander_fire: + type: NAUDIO:V1:SAMPLE + offset: 0x9D90 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_commander_fire + +a6_commander_these_guys: + type: NAUDIO:V1:SAMPLE + offset: 0x9E30 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_commander_these_guys + +a6_falco_am_i_getting_slow: + type: NAUDIO:V1:SAMPLE + offset: 0x9C30 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_falco_am_i_getting_slow + +a6_falco_and_let_me_shoot_you: + type: NAUDIO:V1:SAMPLE + offset: 0x9A90 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_falco_and_let_me_shoot_you + +a6_falco_bogey_behind_me: + type: NAUDIO:V1:SAMPLE + offset: 0x9C10 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_falco_bogey_behind_me + +a6_falco_crud: + type: NAUDIO:V1:SAMPLE + offset: 0x9BD0 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_falco_crud + +a6_falco_game_over_pal: + type: NAUDIO:V1:SAMPLE + offset: 0x99F0 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_falco_game_over_pal + +a6_falco_hold_still: + type: NAUDIO:V1:SAMPLE + offset: 0x9A70 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_falco_hold_still + +a6_falco_scream: + type: NAUDIO:V1:SAMPLE + offset: 0x14650 + parent: 0x134A0 + sampleBankId: 2 + symbol: a6_falco_scream + +a6_falco_too_late: + type: NAUDIO:V1:SAMPLE + offset: 0x99B0 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_falco_too_late + +a6_falco_we_were_so_close_to_venom: + type: NAUDIO:V1:SAMPLE + offset: 0x9BF0 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_falco_we_were_so_close_to_venom + +a6_fox_entering_venom_air_defence_zone: + type: NAUDIO:V1:SAMPLE + offset: 0x9A10 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_fox_entering_venom_air_defence_zone + +a6_fox_hold_on: + type: NAUDIO:V1:SAMPLE + offset: 0x9D50 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_fox_hold_on + +a6_fox_were_entering_venom_air_space: + type: NAUDIO:V1:SAMPLE + offset: 0x9D70 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_fox_were_entering_venom_air_space + +a6_peppy_destroy_all_3_energy_balls: + type: NAUDIO:V1:SAMPLE + offset: 0x9CB0 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_peppy_destroy_all_3_energy_balls + +a6_peppy_scream: + type: NAUDIO:V1:SAMPLE + offset: 0x14690 + parent: 0x134A0 + sampleBankId: 2 + symbol: a6_peppy_scream + +a6_peppy_shoot_em_down_were_being_marked: + type: NAUDIO:V1:SAMPLE + offset: 0x9AF0 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_peppy_shoot_em_down_were_being_marked + +a6_peppy_shoot_the_tentacles_to_open_the_core: + type: NAUDIO:V1:SAMPLE + offset: 0x9C90 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_peppy_shoot_the_tentacles_to_open_the_core + +a6_peppy_the_shield_is_gone_shoot_the_core: + type: NAUDIO:V1:SAMPLE + offset: 0x9D30 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_peppy_the_shield_is_gone_shoot_the_core + +a6_rob_great_fox_will_cover_you: + type: NAUDIO:V1:SAMPLE + offset: 0x9B50 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_rob_great_fox_will_cover_you + +a6_slippy_different: + type: NAUDIO:V1:SAMPLE + offset: 0x9BB0 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_slippy_different + +a6_slippy_enemy_ahead: + type: NAUDIO:V1:SAMPLE + offset: 0x9B70 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_slippy_enemy_ahead + +a6_slippy_incoming_enemy_missile: + type: NAUDIO:V1:SAMPLE + offset: 0x9AD0 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_slippy_incoming_enemy_missile + +a6_slippy_scream: + type: NAUDIO:V1:SAMPLE + offset: 0x14670 + parent: 0x134A0 + sampleBankId: 2 + symbol: a6_slippy_scream + +a6_slippy_space_mines_ahead: + type: NAUDIO:V1:SAMPLE + offset: 0x9A50 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_slippy_space_mines_ahead + +a6_slippy_this_ones: + type: NAUDIO:V1:SAMPLE + offset: 0x9B90 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_slippy_this_ones + +a6_slippy_venoms_right_there: + type: NAUDIO:V1:SAMPLE + offset: 0x9C70 + parent: 0x96A0 + sampleBankId: 2 + symbol: a6_slippy_venoms_right_there + +aq_falco_ill_take_the_sky_any_day: + type: NAUDIO:V1:SAMPLE + offset: 0xF110 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_falco_ill_take_the_sky_any_day + +aq_falco_shoot_a_torpedo_to_help_you_see: + type: NAUDIO:V1:SAMPLE + offset: 0xF170 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_falco_shoot_a_torpedo_to_help_you_see + +aq_falco_thing_will_never_hold_together: + type: NAUDIO:V1:SAMPLE + offset: 0xEF30 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_falco_thing_will_never_hold_together + +aq_falco_this: + type: NAUDIO:V1:SAMPLE + offset: 0xEF10 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_falco_this + +aq_fox_blue_marine_came_through: + type: NAUDIO:V1:SAMPLE + offset: 0xF270 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_fox_blue_marine_came_through + +aq_fox_i_found_the_bio_weapon: + type: NAUDIO:V1:SAMPLE + offset: 0xEFD0 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_fox_i_found_the_bio_weapon + +aq_fox_im_gonna_check_out_the_bio_weapon: + type: NAUDIO:V1:SAMPLE + offset: 0xEDA0 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_fox_im_gonna_check_out_the_bio_weapon + +aq_fox_im_sending_the_data_to_you_guys: + type: NAUDIO:V1:SAMPLE + offset: 0xEE50 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_fox_im_sending_the_data_to_you_guys + +aq_fox_thanks_slip: + type: NAUDIO:V1:SAMPLE + offset: 0xF250 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_fox_thanks_slip + +aq_fox_were_preparing_to_dock: + type: NAUDIO:V1:SAMPLE + offset: 0xF090 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_fox_were_preparing_to_dock + +aq_peppy_aim_for_the_two_columns: + type: NAUDIO:V1:SAMPLE + offset: 0xEFF0 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_peppy_aim_for_the_two_columns + +aq_peppy_go_for_the_eyes: + type: NAUDIO:V1:SAMPLE + offset: 0xF070 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_peppy_go_for_the_eyes + +aq_peppy_its_a_good_thing_you_prepared_slip: + type: NAUDIO:V1:SAMPLE + offset: 0xEEF0 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_peppy_its_a_good_thing_you_prepared_slip + +aq_peppy_looks_like_the_pollution_has_started: + type: NAUDIO:V1:SAMPLE + offset: 0xEE70 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_peppy_looks_like_the_pollution_has_started + +aq_peppy_slippys_not_such_a_screw_up_after_all: + type: NAUDIO:V1:SAMPLE + offset: 0xF0B0 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_peppy_slippys_not_such_a_screw_up_after_all + +aq_peppy_youre_the_best_slippy: + type: NAUDIO:V1:SAMPLE + offset: 0xEF90 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_peppy_youre_the_best_slippy + +aq_slippy_awful: + type: NAUDIO:V1:SAMPLE + offset: 0xEEB0 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_slippy_awful + +aq_slippy_fire_a_homing_torpedo: + type: NAUDIO:V1:SAMPLE + offset: 0xF010 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_slippy_fire_a_homing_torpedo + +aq_slippy_hows_the_blue_marine_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xEED0 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_slippy_hows_the_blue_marine_fox + +aq_slippy_its: + type: NAUDIO:V1:SAMPLE + offset: 0xEE90 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_slippy_its + +aq_slippy_its_beautiful: + type: NAUDIO:V1:SAMPLE + offset: 0xF1D0 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_slippy_its_beautiful + +aq_slippy_keep_shooting: + type: NAUDIO:V1:SAMPLE + offset: 0xEF50 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_slippy_keep_shooting + +aq_slippy_look_at_that: + type: NAUDIO:V1:SAMPLE + offset: 0xF1B0 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_slippy_look_at_that + +aq_slippy_peppy: + type: NAUDIO:V1:SAMPLE + offset: 0xF0F0 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_slippy_peppy + +aq_slippy_sheesh_falco: + type: NAUDIO:V1:SAMPLE + offset: 0xF130 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_slippy_sheesh_falco + +aq_slippy_thanks_alot: + type: NAUDIO:V1:SAMPLE + offset: 0xF0D0 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_slippy_thanks_alot + +aq_slippy_thanks_peppy: + type: NAUDIO:V1:SAMPLE + offset: 0xEFB0 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_slippy_thanks_peppy + +aq_slippy_weve_got_lots_of_torpedos: + type: NAUDIO:V1:SAMPLE + offset: 0xEF70 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_slippy_weve_got_lots_of_torpedos + +aq_slippy_wow: + type: NAUDIO:V1:SAMPLE + offset: 0xF190 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_slippy_wow + +aq_slippy_you_too: + type: NAUDIO:V1:SAMPLE + offset: 0xF150 + parent: 0xEBA0 + sampleBankId: 2 + symbol: aq_slippy_you_too + +bo_andrew_youll_be_sorry_you_crossed_us: + type: NAUDIO:V1:SAMPLE + offset: 0xD850 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_andrew_youll_be_sorry_you_crossed_us + +bo_falco_ill_cover_you_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xD730 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_falco_ill_cover_you_fox + +bo_falco_takin_him_down_today: + type: NAUDIO:V1:SAMPLE + offset: 0xD910 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_falco_takin_him_down_today + +bo_falco_you_are_not: + type: NAUDIO:V1:SAMPLE + offset: 0xD8F0 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_falco_you_are_not + +bo_fox_destroy_all_barriers: + type: NAUDIO:V1:SAMPLE + offset: 0xD6F0 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_fox_destroy_all_barriers + +bo_fox_hey: + type: NAUDIO:V1:SAMPLE + offset: 0xD770 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_fox_hey + +bo_fox_okay_guys: + type: NAUDIO:V1:SAMPLE + offset: 0xD640 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_fox_okay_guys + +bo_fox_star_wolf_again: + type: NAUDIO:V1:SAMPLE + offset: 0xD9D0 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_fox_star_wolf_again + +bo_fox_the_force_field_is_disappearing: + type: NAUDIO:V1:SAMPLE + offset: 0xD790 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_fox_the_force_field_is_disappearing + +bo_fox_venom_here_we_come: + type: NAUDIO:V1:SAMPLE + offset: 0xD8B0 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_fox_venom_here_we_come + +bo_fox_why_now: + type: NAUDIO:V1:SAMPLE + offset: 0xD9F0 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_fox_why_now + +bo_leon_i_think_ill_torture_you_for_a_while: + type: NAUDIO:V1:SAMPLE + offset: 0xD810 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_leon_i_think_ill_torture_you_for_a_while + +bo_peppy_aim_for_the_6_energy_towers: + type: NAUDIO:V1:SAMPLE + offset: 0xD710 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_peppy_aim_for_the_6_energy_towers + +bo_peppy_destroy_the_satellite_core: + type: NAUDIO:V1:SAMPLE + offset: 0xD890 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_peppy_destroy_the_satellite_core + +bo_peppy_good_i_see_the_enemy_core: + type: NAUDIO:V1:SAMPLE + offset: 0xD870 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_peppy_good_i_see_the_enemy_core + +bo_peppy_whats_takin_so_long_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xD930 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_peppy_whats_takin_so_long_fox + +bo_pigma_daddy_screamed_real_good_before_he_died: + type: NAUDIO:V1:SAMPLE + offset: 0xD830 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_pigma_daddy_screamed_real_good_before_he_died + +bo_slippy_give_up: + type: NAUDIO:V1:SAMPLE + offset: 0xD970 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_slippy_give_up + +bo_slippy_they_dont: + type: NAUDIO:V1:SAMPLE + offset: 0xD950 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_slippy_they_dont + +bo_slippy_those_ships_are_shielded_too: + type: NAUDIO:V1:SAMPLE + offset: 0xD8D0 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_slippy_those_ships_are_shielded_too + +bo_slippy_your_carcass_is_mine: + type: NAUDIO:V1:SAMPLE + offset: 0xD750 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_slippy_your_carcass_is_mine + +bo_wolf_play_time_is_over_star_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xD7F0 + parent: 0xD440 + sampleBankId: 2 + symbol: bo_wolf_play_time_is_over_star_fox + +co_attack_carrier_ahhh_someone_wants_to_play: + type: NAUDIO:V1:SAMPLE + offset: 0x4EB0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_attack_carrier_ahhh_someone_wants_to_play + +co_attack_carrier_charge: + type: NAUDIO:V1:SAMPLE + offset: 0x4EF0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_attack_carrier_charge + +co_attack_carrier_deploy_all_units: + type: NAUDIO:V1:SAMPLE + offset: 0x4ED0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_attack_carrier_deploy_all_units + +co_attack_carrier_go: + type: NAUDIO:V1:SAMPLE + offset: 0x4F30 + parent: 0x4520 + sampleBankId: 2 + symbol: co_attack_carrier_go + +co_attack_carrier_ive_got_a_present_for_ya: + type: NAUDIO:V1:SAMPLE + offset: 0x4F10 + parent: 0x4520 + sampleBankId: 2 + symbol: co_attack_carrier_ive_got_a_present_for_ya + +co_attack_carrier_who_are_you_guys: + type: NAUDIO:V1:SAMPLE + offset: 0x4F50 + parent: 0x4520 + sampleBankId: 2 + symbol: co_attack_carrier_who_are_you_guys + +co_attack_carrier_youll_never_defeat_andross: + type: NAUDIO:V1:SAMPLE + offset: 0x4F90 + parent: 0x4520 + sampleBankId: 2 + symbol: co_attack_carrier_youll_never_defeat_andross + +co_falco_back_off: + type: NAUDIO:V1:SAMPLE + offset: 0x49F0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_falco_back_off + +co_falco_falco_here: + type: NAUDIO:V1:SAMPLE + offset: 0x47F0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_falco_falco_here + +co_falco_fine: + type: NAUDIO:V1:SAMPLE + offset: 0x4830 + parent: 0x4520 + sampleBankId: 2 + symbol: co_falco_fine + +co_falco_follow_me: + type: NAUDIO:V1:SAMPLE + offset: 0x4B70 + parent: 0x4520 + sampleBankId: 2 + symbol: co_falco_follow_me + +co_falco_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x4A10 + parent: 0x4520 + sampleBankId: 2 + symbol: co_falco_fox + +co_falco_get_the_one_behind_me: + type: NAUDIO:V1:SAMPLE + offset: 0x4AF0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_falco_get_the_one_behind_me + +co_falco_go: + type: NAUDIO:V1:SAMPLE + offset: 0x4C90 + parent: 0x4520 + sampleBankId: 2 + symbol: co_falco_go + +co_falco_gotcha: + type: NAUDIO:V1:SAMPLE + offset: 0x49D0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_falco_gotcha + +co_falco_i_could_use_some_help_here_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x4B10 + parent: 0x4520 + sampleBankId: 2 + symbol: co_falco_i_could_use_some_help_here_fox + +co_falco_i_found_the_target: + type: NAUDIO:V1:SAMPLE + offset: 0x4BF0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_falco_i_found_the_target + +co_falco_ill_take_this_one: + type: NAUDIO:V1:SAMPLE + offset: 0x4AB0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_falco_ill_take_this_one + +co_falco_im: + type: NAUDIO:V1:SAMPLE + offset: 0x4810 + parent: 0x4520 + sampleBankId: 2 + symbol: co_falco_im + +co_falco_lets: + type: NAUDIO:V1:SAMPLE + offset: 0x4C70 + parent: 0x4520 + sampleBankId: 2 + symbol: co_falco_lets + +co_falco_pretty_smooth_flyin_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x4B50 + parent: 0x4520 + sampleBankId: 2 + symbol: co_falco_pretty_smooth_flyin_fox + +co_falco_somethings_wrong_with_the_g_diffuser: + type: NAUDIO:V1:SAMPLE + offset: 0x4B30 + parent: 0x4520 + sampleBankId: 2 + symbol: co_falco_somethings_wrong_with_the_g_diffuser + +co_falco_this_is_horrible: + type: NAUDIO:V1:SAMPLE + offset: 0x4910 + parent: 0x4520 + sampleBankId: 2 + symbol: co_falco_this_is_horrible + +co_falco_try_to_keep_up: + type: NAUDIO:V1:SAMPLE + offset: 0x4C10 + parent: 0x4520 + sampleBankId: 2 + symbol: co_falco_try_to_keep_up + +co_falco_you_okay_over_there_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x50D0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_falco_you_okay_over_there_fox + +co_fox_all_aircraft_report: + type: NAUDIO:V1:SAMPLE + offset: 0x5110 + parent: 0x4520 + sampleBankId: 2 + symbol: co_fox_all_aircraft_report + +co_fox_check_your_g_diffuser_system: + type: NAUDIO:V1:SAMPLE + offset: 0x47D0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_fox_check_your_g_diffuser_system + +co_fox_falco: + type: NAUDIO:V1:SAMPLE + offset: 0x4BB0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_fox_falco + +co_fox_i_see_em_up_ahead: + type: NAUDIO:V1:SAMPLE + offset: 0x48B0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_fox_i_see_em_up_ahead + +co_fox_lets_rock_and_roll: + type: NAUDIO:V1:SAMPLE + offset: 0x48D0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_fox_lets_rock_and_roll + +co_fox_open_the_wings: + type: NAUDIO:V1:SAMPLE + offset: 0x4720 + parent: 0x4520 + sampleBankId: 2 + symbol: co_fox_open_the_wings + +co_fox_were_entering_corneria_city_now: + type: NAUDIO:V1:SAMPLE + offset: 0x48F0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_fox_were_entering_corneria_city_now + +co_fox_were_heading_out: + type: NAUDIO:V1:SAMPLE + offset: 0x50F0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_fox_were_heading_out + +co_fox_were_star_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x4F70 + parent: 0x4520 + sampleBankId: 2 + symbol: co_fox_were_star_fox + +co_fox_where_ya_goin: + type: NAUDIO:V1:SAMPLE + offset: 0x4BD0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_fox_where_ya_goin + +co_granga_ah_so_this_is_star_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x4D70 + parent: 0x4520 + sampleBankId: 2 + symbol: co_granga_ah_so_this_is_star_fox + +co_granga_failed_you: + type: NAUDIO:V1:SAMPLE + offset: 0x4E70 + parent: 0x4520 + sampleBankId: 2 + symbol: co_granga_failed_you + +co_granga_i_will_not_be_defeated_by_this_worm: + type: NAUDIO:V1:SAMPLE + offset: 0x4E30 + parent: 0x4520 + sampleBankId: 2 + symbol: co_granga_i_will_not_be_defeated_by_this_worm + +co_granga_im_going_to_crush_you: + type: NAUDIO:V1:SAMPLE + offset: 0x4D90 + parent: 0x4520 + sampleBankId: 2 + symbol: co_granga_im_going_to_crush_you + +co_granga_my_emperor_ive: + type: NAUDIO:V1:SAMPLE + offset: 0x4E50 + parent: 0x4520 + sampleBankId: 2 + symbol: co_granga_my_emperor_ive + +co_granga_no: + type: NAUDIO:V1:SAMPLE + offset: 0x4E10 + parent: 0x4520 + sampleBankId: 2 + symbol: co_granga_no + +co_granga_stop_moving_so_i_can_squash_you: + type: NAUDIO:V1:SAMPLE + offset: 0x4DD0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_granga_stop_moving_so_i_can_squash_you + +co_granga_those_who_cross_andross_will_die: + type: NAUDIO:V1:SAMPLE + offset: 0x4DB0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_granga_those_who_cross_andross_will_die + +co_granga_you_annoying_little_flies: + type: NAUDIO:V1:SAMPLE + offset: 0x4CB0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_granga_you_annoying_little_flies + +co_granga_you_are_starting_to_annoy_me: + type: NAUDIO:V1:SAMPLE + offset: 0x4DF0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_granga_you_are_starting_to_annoy_me + +co_peppy_aim_for_his_back: + type: NAUDIO:V1:SAMPLE + offset: 0x4D10 + parent: 0x4520 + sampleBankId: 2 + symbol: co_peppy_aim_for_his_back + +co_peppy_aim_for_the_open_spot: + type: NAUDIO:V1:SAMPLE + offset: 0x4FF0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_peppy_aim_for_the_open_spot + +co_peppy_bogey_on_your_tail: + type: NAUDIO:V1:SAMPLE + offset: 0x4950 + parent: 0x4520 + sampleBankId: 2 + symbol: co_peppy_bogey_on_your_tail + +co_peppy_drop_altitude: + type: NAUDIO:V1:SAMPLE + offset: 0x4FD0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_peppy_drop_altitude + +co_peppy_incoming_enemy_from_the_rear: + type: NAUDIO:V1:SAMPLE + offset: 0x4FB0 + parent: 0x4520 + sampleBankId: 2 + symbol: co_peppy_incoming_enemy_from_the_rear + +co_peppy_quit_screwin_around_do_something: + type: NAUDIO:V1:SAMPLE + offset: 0x4E90 + parent: 0x4520 + sampleBankId: 2 + symbol: co_peppy_quit_screwin_around_do_something + +co_peppy_slippy_watch_out: + type: NAUDIO:V1:SAMPLE + offset: 0x4930 + parent: 0x4520 + sampleBankId: 2 + symbol: co_peppy_slippy_watch_out + +co_peppy_this_is_peppy_all_systems_go: + type: NAUDIO:V1:SAMPLE + offset: 0x4850 + parent: 0x4520 + sampleBankId: 2 + symbol: co_peppy_this_is_peppy_all_systems_go + +co_peppy_use_the_boost_to_chase: + type: NAUDIO:V1:SAMPLE + offset: 0x13C10 + parent: 0x134A0 + sampleBankId: 2 + symbol: co_peppy_use_the_boost_to_chase + +co_peppy_youre_becoming_more_like_your_father: + type: NAUDIO:V1:SAMPLE + offset: 0x5070 + parent: 0x4520 + sampleBankId: 2 + symbol: co_peppy_youre_becoming_more_like_your_father + +co_slippy_dead_ahead: + type: NAUDIO:V1:SAMPLE + offset: 0x4C50 + parent: 0x4520 + sampleBankId: 2 + symbol: co_slippy_dead_ahead + +co_slippy_enemy_robot: + type: NAUDIO:V1:SAMPLE + offset: 0x4C30 + parent: 0x4520 + sampleBankId: 2 + symbol: co_slippy_enemy_robot + +co_slippy_help_me: + type: NAUDIO:V1:SAMPLE + offset: 0x4990 + parent: 0x4520 + sampleBankId: 2 + symbol: co_slippy_help_me + +co_slippy_i_thought_they_had_me: + type: NAUDIO:V1:SAMPLE + offset: 0x5170 + parent: 0x4520 + sampleBankId: 2 + symbol: co_slippy_i_thought_they_had_me + +co_slippy_i_was_worried_for_a_moment: + type: NAUDIO:V1:SAMPLE + offset: 0x5030 + parent: 0x4520 + sampleBankId: 2 + symbol: co_slippy_i_was_worried_for_a_moment + +co_slippy_im_okay: + type: NAUDIO:V1:SAMPLE + offset: 0x4890 + parent: 0x4520 + sampleBankId: 2 + symbol: co_slippy_im_okay + +co_slippy_slippy_here: + type: NAUDIO:V1:SAMPLE + offset: 0x4870 + parent: 0x4520 + sampleBankId: 2 + symbol: co_slippy_slippy_here + +co_slippy_thanks_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x5130 + parent: 0x4520 + sampleBankId: 2 + symbol: co_slippy_thanks_fox + +co_slippy_woah: + type: NAUDIO:V1:SAMPLE + offset: 0x4970 + parent: 0x4520 + sampleBankId: 2 + symbol: co_slippy_woah + +co_slippy_you_did_it: + type: NAUDIO:V1:SAMPLE + offset: 0x5010 + parent: 0x4520 + sampleBankId: 2 + symbol: co_slippy_you_did_it + +cr_fox_its_time_for_us_to_go_now: + type: NAUDIO:V1:SAMPLE + offset: 0x15DD0 + parent: 0x15A20 + sampleBankId: 2 + symbol: cr_fox_its_time_for_us_to_go_now + +cr_fox_oh_no_sir: + type: NAUDIO:V1:SAMPLE + offset: 0x15D50 + parent: 0x15A20 + sampleBankId: 2 + symbol: cr_fox_oh_no_sir + +cr_fox_we_prefer_doing_things_our_own_way: + type: NAUDIO:V1:SAMPLE + offset: 0x15D70 + parent: 0x15A20 + sampleBankId: 2 + symbol: cr_fox_we_prefer_doing_things_our_own_way + +cr_pepper_honoured_to_have_you_as: + type: NAUDIO:V1:SAMPLE + offset: 0x15D10 + parent: 0x15A20 + sampleBankId: 2 + symbol: cr_pepper_honoured_to_have_you_as + +cr_pepper_i_would_be: + type: NAUDIO:V1:SAMPLE + offset: 0x15CF0 + parent: 0x15A20 + sampleBankId: 2 + symbol: cr_pepper_i_would_be + +cr_pepper_part_of_the_cornerian_army: + type: NAUDIO:V1:SAMPLE + offset: 0x15D30 + parent: 0x15A20 + sampleBankId: 2 + symbol: cr_pepper_part_of_the_cornerian_army + +cr_pepper_star_fox_we_are_in_your_debt: + type: NAUDIO:V1:SAMPLE + offset: 0x15C20 + parent: 0x15A20 + sampleBankId: 2 + symbol: cr_pepper_star_fox_we_are_in_your_debt + +cr_pepper_this_is_one_steep_bill_but_its_worth_it: + type: NAUDIO:V1:SAMPLE + offset: 0x24E0 + parent: 0x0 + sampleBankId: 0 + symbol: cr_pepper_this_is_one_steep_bill_but_its_worth_it + +cr_pepper_what: + type: NAUDIO:V1:SAMPLE + offset: 0x2550 + parent: 0x0 + sampleBankId: 0 + symbol: cr_pepper_what + +cr_rob_great_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x15D90 + parent: 0x15A20 + sampleBankId: 2 + symbol: cr_rob_great_fox + +cr_rob_is_ready_to_go: + type: NAUDIO:V1:SAMPLE + offset: 0x15DB0 + parent: 0x15A20 + sampleBankId: 2 + symbol: cr_rob_is_ready_to_go + +fo_andrew_andross: + type: NAUDIO:V1:SAMPLE + offset: 0xB9D0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_andrew_andross + +fo_andrew_andross_enemy_is_my_enemy: + type: NAUDIO:V1:SAMPLE + offset: 0xB8B0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_andrew_andross_enemy_is_my_enemy + +fo_andrew_bow_before_the_great: + type: NAUDIO:V1:SAMPLE + offset: 0xB9B0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_andrew_bow_before_the_great + +fo_andrew_im_not_afraid_of_you: + type: NAUDIO:V1:SAMPLE + offset: 0xBB10 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_andrew_im_not_afraid_of_you + +fo_andrew_score_one_for_andross: + type: NAUDIO:V1:SAMPLE + offset: 0xBF10 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_andrew_score_one_for_andross + +fo_andrew_stick_to_the_pond_froggy: + type: NAUDIO:V1:SAMPLE + offset: 0xBA70 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_andrew_stick_to_the_pond_froggy + +fo_andrew_uncle_andross: + type: NAUDIO:V1:SAMPLE + offset: 0xBBB0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_andrew_uncle_andross + +fo_falco_so_thats_star_wolf: + type: NAUDIO:V1:SAMPLE + offset: 0xBDD0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_falco_so_thats_star_wolf + +fo_falco_that_was_a_close_call_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xBE50 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_falco_that_was_a_close_call_fox + +fo_fox_and_take_it_to_em: + type: NAUDIO:V1:SAMPLE + offset: 0xB3B0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_fox_and_take_it_to_em + +fo_fox_can_anyone_take_care_of_it: + type: NAUDIO:V1:SAMPLE + offset: 0xBC30 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_fox_can_anyone_take_care_of_it + +fo_fox_emergency_maneuvers: + type: NAUDIO:V1:SAMPLE + offset: 0xBD50 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_fox_emergency_maneuvers + +fo_fox_geez: + type: NAUDIO:V1:SAMPLE + offset: 0xBC10 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_fox_geez + +fo_fox_get_out_of_there: + type: NAUDIO:V1:SAMPLE + offset: 0xBD70 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_fox_get_out_of_there + +fo_fox_ill_take_care_of_the_bomb_now: + type: NAUDIO:V1:SAMPLE + offset: 0xBD30 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_fox_ill_take_care_of_the_bomb_now + +fo_fox_just_what_i_need_to_see: + type: NAUDIO:V1:SAMPLE + offset: 0xB8D0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_fox_just_what_i_need_to_see + +fo_fox_lets_take_care_of_these_guys_first: + type: NAUDIO:V1:SAMPLE + offset: 0xBC50 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_fox_lets_take_care_of_these_guys_first + +fo_fox_split_up: + type: NAUDIO:V1:SAMPLE + offset: 0xB300 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_fox_split_up + +fo_fox_star_wolf: + type: NAUDIO:V1:SAMPLE + offset: 0xB8F0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_fox_star_wolf + +fo_leon_andross_has_ordered_us_to_take_you_down: + type: NAUDIO:V1:SAMPLE + offset: 0xB850 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_leon_andross_has_ordered_us_to_take_you_down + +fo_leon_annoying_bird: + type: NAUDIO:V1:SAMPLE + offset: 0xBA10 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_leon_annoying_bird + +fo_leon_close_but_no_cigar_hahaha: + type: NAUDIO:V1:SAMPLE + offset: 0xBE90 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_leon_close_but_no_cigar_hahaha + +fo_leon_i_am_the_great_leon: + type: NAUDIO:V1:SAMPLE + offset: 0xBA30 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_leon_i_am_the_great_leon + +fo_leon_shoot_me_down_if_you_can: + type: NAUDIO:V1:SAMPLE + offset: 0xBAB0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_leon_shoot_me_down_if_you_can + +fo_leon_this_cant_be_happening: + type: NAUDIO:V1:SAMPLE + offset: 0xBB70 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_leon_this_cant_be_happening + +fo_leon_youre_not_as_tough_as_i_thought: + type: NAUDIO:V1:SAMPLE + offset: 0xB970 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_leon_youre_not_as_tough_as_i_thought + +fo_peppy_fox_take_it_easy: + type: NAUDIO:V1:SAMPLE + offset: 0xBE30 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_peppy_fox_take_it_easy + +fo_peppy_im_not_too_crazy_about_those_guys: + type: NAUDIO:V1:SAMPLE + offset: 0xBDB0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_peppy_im_not_too_crazy_about_those_guys + +fo_pigma_come_on_little_man: + type: NAUDIO:V1:SAMPLE + offset: 0xBAD0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_pigma_come_on_little_man + +fo_pigma_hehehe_were_gettin_paid_a_lot_of_cash_for_this: + type: NAUDIO:V1:SAMPLE + offset: 0xB870 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_pigma_hehehe_were_gettin_paid_a_lot_of_cash_for_this + +fo_pigma_ill_do_you_fast_peppy_old_pal: + type: NAUDIO:V1:SAMPLE + offset: 0xBA50 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_pigma_ill_do_you_fast_peppy_old_pal + +fo_pigma_ive_got_two_words_for_you: + type: NAUDIO:V1:SAMPLE + offset: 0xBEB0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_pigma_ive_got_two_words_for_you + +fo_pigma_lo: + type: NAUDIO:V1:SAMPLE + offset: 0xBED0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_pigma_lo + +fo_pigma_my_beautiful_reward_ahahaharrrgh: + type: NAUDIO:V1:SAMPLE + offset: 0xBB90 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_pigma_my_beautiful_reward_ahahaharrrgh + +fo_pigma_peppy_long_time_no_see: + type: NAUDIO:V1:SAMPLE + offset: 0xB890 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_pigma_peppy_long_time_no_see + +fo_pigma_ser: + type: NAUDIO:V1:SAMPLE + offset: 0xBEF0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_pigma_ser + +fo_pigma_shoot_me: + type: NAUDIO:V1:SAMPLE + offset: 0xBAF0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_pigma_shoot_me + +fo_pigma_that_rewards_as_good_as_mine: + type: NAUDIO:V1:SAMPLE + offset: 0xB990 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_pigma_that_rewards_as_good_as_mine + +fo_rob_15_seconds_to_explosion: + type: NAUDIO:V1:SAMPLE + offset: 0xBCD0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_rob_15_seconds_to_explosion + +fo_rob_30_seconds_to_explosion: + type: NAUDIO:V1:SAMPLE + offset: 0xBCB0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_rob_30_seconds_to_explosion + +fo_rob_a_bomb_has_been_planted_at_the_base: + type: NAUDIO:V1:SAMPLE + offset: 0xBBF0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_rob_a_bomb_has_been_planted_at_the_base + +fo_rob_bomb_explotiong: + type: NAUDIO:V1:SAMPLE + offset: 0xBCF0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_rob_bomb_explotiong + +fo_rob_danger: + type: NAUDIO:V1:SAMPLE + offset: 0xBC70 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_rob_danger + +fo_rob_keep_clear: + type: NAUDIO:V1:SAMPLE + offset: 0xBD10 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_rob_keep_clear + +fo_rob_one_minute_to_explosion: + type: NAUDIO:V1:SAMPLE + offset: 0xBC90 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_rob_one_minute_to_explosion + +fo_slippy_hey_we_made_it: + type: NAUDIO:V1:SAMPLE + offset: 0xBE10 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_slippy_hey_we_made_it + +fo_slippy_they_almost_got_us: + type: NAUDIO:V1:SAMPLE + offset: 0xBD90 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_slippy_they_almost_got_us + +fo_slippy_why_are_ships_coming_out_of_the_base: + type: NAUDIO:V1:SAMPLE + offset: 0xB3D0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_slippy_why_are_ships_coming_out_of_the_base + +fo_wolf_cant_let_you_do_that_star_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xB810 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_wolf_cant_let_you_do_that_star_fox + +fo_wolf_cant_lose: + type: NAUDIO:V1:SAMPLE + offset: 0xBB50 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_wolf_cant_lose + +fo_wolf_i: + type: NAUDIO:V1:SAMPLE + offset: 0xBB30 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_wolf_i + +fo_wolf_looks_like_we_win_today_star_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xBE70 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_wolf_looks_like_we_win_today_star_fox + +fo_wolf_what_the_heck: + type: NAUDIO:V1:SAMPLE + offset: 0xBBD0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_wolf_what_the_heck + +fo_wolf_youll_be_seing_your_dad_soon_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xB910 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_wolf_youll_be_seing_your_dad_soon_fox + +fo_wolf_youre_going_down: + type: NAUDIO:V1:SAMPLE + offset: 0xB950 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_wolf_youre_going_down + +fo_wolf_youre_in_my_sights: + type: NAUDIO:V1:SAMPLE + offset: 0xB930 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_wolf_youre_in_my_sights + +fo_wolf_youre_not_so_tough: + type: NAUDIO:V1:SAMPLE + offset: 0xB9F0 + parent: 0xB100 + sampleBankId: 2 + symbol: fo_wolf_youre_not_so_tough + +gen_andross_ahhh_the_son_of_james_mccloud: + type: NAUDIO:V1:SAMPLE + offset: 0x13F30 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_andross_ahhh_the_son_of_james_mccloud + +gen_andross_ha_ha_ha_you_can_never_defeat_me: + type: NAUDIO:V1:SAMPLE + offset: 0x13F90 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_andross_ha_ha_ha_you_can_never_defeat_me + +gen_andross_ill_make_those_fools_pay: + type: NAUDIO:V1:SAMPLE + offset: 0x13F50 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_andross_ill_make_those_fools_pay + +gen_andross_im_looking_forward_to_this: + type: NAUDIO:V1:SAMPLE + offset: 0x13F10 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_andross_im_looking_forward_to_this + +gen_andross_those: + type: NAUDIO:V1:SAMPLE + offset: 0x13CD0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_andross_those + +gen_andross_those_tin_cans_are_no_match_for_me: + type: NAUDIO:V1:SAMPLE + offset: 0x13F70 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_andross_those_tin_cans_are_no_match_for_me + +gen_andross_tin_cans_are_no_match_for_me: + type: NAUDIO:V1:SAMPLE + offset: 0x13CF0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_andross_tin_cans_are_no_match_for_me + +gen_bill_heres_something_for_ya_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x11D90 + parent: 0x115E0 + sampleBankId: 2 + symbol: gen_bill_heres_something_for_ya_fox + +gen_bill_hey: + type: NAUDIO:V1:SAMPLE + offset: 0x139B0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_bill_hey + +gen_bill_see_if_i_help_you_again: + type: NAUDIO:V1:SAMPLE + offset: 0x139D0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_bill_see_if_i_help_you_again + +gen_bill_take_it_easy_fox_dont_let_us_down: + type: NAUDIO:V1:SAMPLE + offset: 0x7A10 + parent: 0x7460 + sampleBankId: 2 + symbol: gen_bill_take_it_easy_fox_dont_let_us_down + +gen_falco_ah: + type: NAUDIO:V1:SAMPLE + offset: 0x13810 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_ah + +gen_falco_all_right: + type: NAUDIO:V1:SAMPLE + offset: 0x9ED0 + parent: 0x96A0 + sampleBankId: 2 + symbol: gen_falco_all_right + +gen_falco_clean_up_this_mess: + type: NAUDIO:V1:SAMPLE + offset: 0x14330 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_clean_up_this_mess + +gen_falco_come_on: + type: NAUDIO:V1:SAMPLE + offset: 0x14230 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_come_on + +gen_falco_company: + type: NAUDIO:V1:SAMPLE + offset: 0xD7D0 + parent: 0xD440 + sampleBankId: 2 + symbol: gen_falco_company + +gen_falco_crud: + type: NAUDIO:V1:SAMPLE + offset: 0x144B0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_crud + +gen_falco_dang: + type: NAUDIO:V1:SAMPLE + offset: 0xB510 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_falco_dang + +gen_falco_dead_meat: + type: NAUDIO:V1:SAMPLE + offset: 0xB6F0 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_falco_dead_meat + +gen_falco_does_it_look_okay_to_you: + type: NAUDIO:V1:SAMPLE + offset: 0x14390 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_does_it_look_okay_to_you + +gen_falco_dont_worry_about_me_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x14030 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_dont_worry_about_me_fox + +gen_falco_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xF050 + parent: 0xEBA0 + sampleBankId: 2 + symbol: gen_falco_fox + +gen_falco_fox_hes_right_behind_you: + type: NAUDIO:V1:SAMPLE + offset: 0x4D50 + parent: 0x4520 + sampleBankId: 2 + symbol: gen_falco_fox_hes_right_behind_you + +gen_falco_fox_how_swell: + type: NAUDIO:V1:SAMPLE + offset: 0xB5F0 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_falco_fox_how_swell + +gen_falco_gee_ive_been_saved_by: + type: NAUDIO:V1:SAMPLE + offset: 0xB5D0 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_falco_gee_ive_been_saved_by + +gen_falco_geez_laweeze_what: + type: NAUDIO:V1:SAMPLE + offset: 0xA8B0 + parent: 0xA4E0 + sampleBankId: 2 + symbol: gen_falco_geez_laweeze_what + +gen_falco_geez_quit_movin_around: + type: NAUDIO:V1:SAMPLE + offset: 0xE3D0 + parent: 0xDE40 + sampleBankId: 2 + symbol: gen_falco_geez_quit_movin_around + +gen_falco_get_outta_my_way: + type: NAUDIO:V1:SAMPLE + offset: 0x13B50 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_get_outta_my_way + +gen_falco_go_find_your_own_target: + type: NAUDIO:V1:SAMPLE + offset: 0x13A90 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_go_find_your_own_target + +gen_falco_here_they_come: + type: NAUDIO:V1:SAMPLE + offset: 0x11AD0 + parent: 0x115E0 + sampleBankId: 2 + symbol: gen_falco_here_they_come + +gen_falco_hes_right_behind_me: + type: NAUDIO:V1:SAMPLE + offset: 0xB410 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_falco_hes_right_behind_me + +gen_falco_hey_einstein_im_on_your_side: + type: NAUDIO:V1:SAMPLE + offset: 0x13930 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_hey_einstein_im_on_your_side + +gen_falco_hold_together: + type: NAUDIO:V1:SAMPLE + offset: 0x14430 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_hold_together + +gen_falco_i_cant_shake_this_guy: + type: NAUDIO:V1:SAMPLE + offset: 0xB470 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_falco_i_cant_shake_this_guy + +gen_falco_i_got_the_last_one: + type: NAUDIO:V1:SAMPLE + offset: 0xBF70 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_falco_i_got_the_last_one + +gen_falco_i_guess_i_should_be_thankful: + type: NAUDIO:V1:SAMPLE + offset: 0x5190 + parent: 0x4520 + sampleBankId: 2 + symbol: gen_falco_i_guess_i_should_be_thankful + +gen_falco_i_guess_youre_good_for_somethin: + type: NAUDIO:V1:SAMPLE + offset: 0x13D50 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_i_guess_youre_good_for_somethin + +gen_falco_im_going_down: + type: NAUDIO:V1:SAMPLE + offset: 0x15FD0 + parent: 0x15A20 + sampleBankId: 2 + symbol: gen_falco_im_going_down + +gen_falco_im_going_left: + type: NAUDIO:V1:SAMPLE + offset: 0x15F70 + parent: 0x15A20 + sampleBankId: 2 + symbol: gen_falco_im_going_left + +gen_falco_im_going_right: + type: NAUDIO:V1:SAMPLE + offset: 0x15F30 + parent: 0x15A20 + sampleBankId: 2 + symbol: gen_falco_im_going_right + +gen_falco_im_going_up: + type: NAUDIO:V1:SAMPLE + offset: 0x15FB0 + parent: 0x15A20 + sampleBankId: 2 + symbol: gen_falco_im_going_up + +gen_falco_im_hit: + type: NAUDIO:V1:SAMPLE + offset: 0xB530 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_falco_im_hit + +gen_falco_is_that: + type: NAUDIO:V1:SAMPLE + offset: 0xA8D0 + parent: 0xA4E0 + sampleBankId: 2 + symbol: gen_falco_is_that + +gen_falco_its_working: + type: NAUDIO:V1:SAMPLE + offset: 0x9CF0 + parent: 0x96A0 + sampleBankId: 2 + symbol: gen_falco_its_working + +gen_falco_lets: + type: NAUDIO:V1:SAMPLE + offset: 0x14310 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_lets + +gen_falco_lets_kick_some_tail: + type: NAUDIO:V1:SAMPLE + offset: 0x14270 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_lets_kick_some_tail + +gen_falco_looks_like_weve_got: + type: NAUDIO:V1:SAMPLE + offset: 0xD7B0 + parent: 0xD440 + sampleBankId: 2 + symbol: gen_falco_looks_like_weve_got + +gen_falco_move_it: + type: NAUDIO:V1:SAMPLE + offset: 0x4D30 + parent: 0x4520 + sampleBankId: 2 + symbol: gen_falco_move_it + +gen_falco_nooo: + type: NAUDIO:V1:SAMPLE + offset: 0x139F0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_nooo + +gen_falco_oh_man_im_gonna_have_to_back_off: + type: NAUDIO:V1:SAMPLE + offset: 0x13B70 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_oh_man_im_gonna_have_to_back_off + +gen_falco_pal: + type: NAUDIO:V1:SAMPLE + offset: 0xB710 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_falco_pal + +gen_falco_scratch_one_bogey: + type: NAUDIO:V1:SAMPLE + offset: 0xB790 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_falco_scratch_one_bogey + +gen_falco_see_my_ship: + type: NAUDIO:V1:SAMPLE + offset: 0x14370 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_see_my_ship + +gen_falco_shoot: + type: NAUDIO:V1:SAMPLE + offset: 0xB3F0 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_falco_shoot + +gen_falco_shoot_ive_taken_damage: + type: NAUDIO:V1:SAMPLE + offset: 0x138D0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_shoot_ive_taken_damage + +gen_falco_thats_it: + type: NAUDIO:V1:SAMPLE + offset: 0xF030 + parent: 0xEBA0 + sampleBankId: 2 + symbol: gen_falco_thats_it + +gen_falco_these_guys_dont_quit: + type: NAUDIO:V1:SAMPLE + offset: 0x8BB0 + parent: 0x8660 + sampleBankId: 2 + symbol: gen_falco_these_guys_dont_quit + +gen_falco_time_for_a_little_payback: + type: NAUDIO:V1:SAMPLE + offset: 0xB670 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_falco_time_for_a_little_payback + +gen_falco_watch_out_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x145B0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_watch_out_fox + +gen_falco_yeah: + type: NAUDIO:V1:SAMPLE + offset: 0x9CD0 + parent: 0x96A0 + sampleBankId: 2 + symbol: gen_falco_yeah + +gen_falco_you_are_so_lucky: + type: NAUDIO:V1:SAMPLE + offset: 0x13850 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_you_are_so_lucky + +gen_falco_you_worry_about_your_own_hide: + type: NAUDIO:V1:SAMPLE + offset: 0x13890 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_you_worry_about_your_own_hide + +gen_falco_youre: + type: NAUDIO:V1:SAMPLE + offset: 0xB6D0 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_falco_youre + +gen_falco_youre_gettin_better_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x13830 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_youre_gettin_better_fox + +gen_falco_youre_not_leavin_yet: + type: NAUDIO:V1:SAMPLE + offset: 0x14490 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_falco_youre_not_leavin_yet + +gen_fox_all_aircraft_report: + type: NAUDIO:V1:SAMPLE + offset: 0x136A0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_fox_all_aircraft_report + +gen_fox_all_range_mode: + type: NAUDIO:V1:SAMPLE + offset: 0x13AD0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_fox_all_range_mode + +gen_fox_death_scream: + type: NAUDIO:V1:SAMPLE + offset: 0x14630 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_fox_death_scream + +gen_fox_theres_one_more_to_go: + type: NAUDIO:V1:SAMPLE + offset: 0x12CF0 + parent: 0x12400 + sampleBankId: 2 + symbol: gen_fox_theres_one_more_to_go + +gen_fox_were_gonna_break_through_that_fleet: + type: NAUDIO:V1:SAMPLE + offset: 0x9AB0 + parent: 0x96A0 + sampleBankId: 2 + symbol: gen_fox_were_gonna_break_through_that_fleet + +gen_katt_beautiful_i_could_kiss_you_for_that: + type: NAUDIO:V1:SAMPLE + offset: 0xFD90 + parent: 0xF7C0 + sampleBankId: 2 + symbol: gen_katt_beautiful_i_could_kiss_you_for_that + +gen_katt_is_that_any_way_to_greet_a_girl: + type: NAUDIO:V1:SAMPLE + offset: 0x8A90 + parent: 0x8660 + sampleBankId: 2 + symbol: gen_katt_is_that_any_way_to_greet_a_girl + +gen_katt_katt: + type: NAUDIO:V1:SAMPLE + offset: 0xFD70 + parent: 0xF7C0 + sampleBankId: 2 + symbol: gen_katt_katt + +gen_katt_make_way_for: + type: NAUDIO:V1:SAMPLE + offset: 0xFD50 + parent: 0xF7C0 + sampleBankId: 2 + symbol: gen_katt_make_way_for + +gen_katt_you_tryin_to_damage_my_pretty_face: + type: NAUDIO:V1:SAMPLE + offset: 0x13990 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_katt_you_tryin_to_damage_my_pretty_face + +gen_leon_ill_take_care_of_you: + type: NAUDIO:V1:SAMPLE + offset: 0x12A30 + parent: 0x12400 + sampleBankId: 2 + symbol: gen_leon_ill_take_care_of_you + +gen_leon_not_yet: + type: NAUDIO:V1:SAMPLE + offset: 0x12AF0 + parent: 0x12400 + sampleBankId: 2 + symbol: gen_leon_not_yet + +gen_leon_the_partys_just_begun: + type: NAUDIO:V1:SAMPLE + offset: 0x12B10 + parent: 0x12400 + sampleBankId: 2 + symbol: gen_leon_the_partys_just_begun + +gen_peppy_brace_yourselves: + type: NAUDIO:V1:SAMPLE + offset: 0xCCF0 + parent: 0xCA20 + sampleBankId: 2 + symbol: gen_peppy_brace_yourselves + +gen_peppy_come_on_fox_you_can_do_it: + type: NAUDIO:V1:SAMPLE + offset: 0x141F0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_come_on_fox_you_can_do_it + +gen_peppy_dang_im_hit: + type: NAUDIO:V1:SAMPLE + offset: 0x138F0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_dang_im_hit + +gen_peppy_do: + type: NAUDIO:V1:SAMPLE + offset: 0x144F0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_do + +gen_peppy_do_a_barrel_roll: + type: NAUDIO:V1:SAMPLE + offset: 0x4A30 + parent: 0x4520 + sampleBankId: 2 + symbol: gen_peppy_do_a_barrel_roll + +gen_peppy_dont_go_dyin_on_me_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x14290 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_dont_go_dyin_on_me_fox + +gen_peppy_dont_mess_up_that_arwing: + type: NAUDIO:V1:SAMPLE + offset: 0x5E10 + parent: 0x5A80 + sampleBankId: 2 + symbol: gen_peppy_dont_mess_up_that_arwing + +gen_peppy_everybody_stay_alert: + type: NAUDIO:V1:SAMPLE + offset: 0x9A30 + parent: 0x96A0 + sampleBankId: 2 + symbol: gen_peppy_everybody_stay_alert + +gen_peppy_everything_okay: + type: NAUDIO:V1:SAMPLE + offset: 0x14450 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_everything_okay + +gen_peppy_everythings_a_okay: + type: NAUDIO:V1:SAMPLE + offset: 0x13770 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_everythings_a_okay + +gen_peppy_ggone_it: + type: NAUDIO:V1:SAMPLE + offset: 0x14510 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_ggone_it + +gen_peppy_good_goin_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x10B50 + parent: 0x106C0 + sampleBankId: 2 + symbol: gen_peppy_good_goin_fox + +gen_peppy_got_me: + type: NAUDIO:V1:SAMPLE + offset: 0xB5B0 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_peppy_got_me + +gen_peppy_hes_quick_be_careful: + type: NAUDIO:V1:SAMPLE + offset: 0xE370 + parent: 0xDE40 + sampleBankId: 2 + symbol: gen_peppy_hes_quick_be_careful + +gen_peppy_i_got_the_last_one: + type: NAUDIO:V1:SAMPLE + offset: 0xBF50 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_peppy_i_got_the_last_one + +gen_peppy_i_saw_my_life_flash_before_my_eyes: + type: NAUDIO:V1:SAMPLE + offset: 0x137F0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_i_saw_my_life_flash_before_my_eyes + +gen_peppy_i_see_your_father_in_you_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x14050 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_i_see_your_father_in_you_fox + +gen_peppy_i_wont_let_you_get_away_from_me: + type: NAUDIO:V1:SAMPLE + offset: 0xB6B0 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_peppy_i_wont_let_you_get_away_from_me + +gen_peppy_im_going_down: + type: NAUDIO:V1:SAMPLE + offset: 0x15E50 + parent: 0x15A20 + sampleBankId: 2 + symbol: gen_peppy_im_going_down + +gen_peppy_im_going_left: + type: NAUDIO:V1:SAMPLE + offset: 0x15E10 + parent: 0x15A20 + sampleBankId: 2 + symbol: gen_peppy_im_going_left + +gen_peppy_im_going_right: + type: NAUDIO:V1:SAMPLE + offset: 0x15DF0 + parent: 0x15A20 + sampleBankId: 2 + symbol: gen_peppy_im_going_right + +gen_peppy_im_going_up: + type: NAUDIO:V1:SAMPLE + offset: 0x15E30 + parent: 0x15A20 + sampleBankId: 2 + symbol: gen_peppy_im_going_up + +gen_peppy_ive_got_a_bad_feeling_about_this_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xA9B0 + parent: 0xA4E0 + sampleBankId: 2 + symbol: gen_peppy_ive_got_a_bad_feeling_about_this_fox + +gen_peppy_ive_taken_a_few_hits_but_im_okay: + type: NAUDIO:V1:SAMPLE + offset: 0x137B0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_ive_taken_a_few_hits_but_im_okay + +gen_peppy_just_shoot_it_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x5DF0 + parent: 0x5A80 + sampleBankId: 2 + symbol: gen_peppy_just_shoot_it_fox + +gen_peppy_knock_it_off_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x13950 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_knock_it_off_fox + +gen_peppy_lock_on_the_enemy: + type: NAUDIO:V1:SAMPLE + offset: 0x14090 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_lock_on_the_enemy + +gen_peppy_never_give_up: + type: NAUDIO:V1:SAMPLE + offset: 0x143B0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_never_give_up + +gen_peppy_nooo: + type: NAUDIO:V1:SAMPLE + offset: 0x13A10 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_nooo + +gen_peppy_shoot_theyve: + type: NAUDIO:V1:SAMPLE + offset: 0xB590 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_peppy_shoot_theyve + +gen_peppy_slippy_get_back_here: + type: NAUDIO:V1:SAMPLE + offset: 0x13E10 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_slippy_get_back_here + +gen_peppy_sorry_guys_ive_gotta_sit_this_one_out: + type: NAUDIO:V1:SAMPLE + offset: 0x13B90 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_sorry_guys_ive_gotta_sit_this_one_out + +gen_peppy_take_care_of_the_guy_behind_me_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xB450 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_peppy_take_care_of_the_guy_behind_me_fox + +gen_peppy_thanks_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x78D0 + parent: 0x7460 + sampleBankId: 2 + symbol: gen_peppy_thanks_fox + +gen_peppy_the_enemys_coming_from_behind: + type: NAUDIO:V1:SAMPLE + offset: 0x5E70 + parent: 0x5A80 + sampleBankId: 2 + symbol: gen_peppy_the_enemys_coming_from_behind + +gen_peppy_theres_one_down: + type: NAUDIO:V1:SAMPLE + offset: 0xB7F0 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_peppy_theres_one_down + +gen_peppy_theyre_on_me_im_gettin_careless: + type: NAUDIO:V1:SAMPLE + offset: 0x9C50 + parent: 0x96A0 + sampleBankId: 2 + symbol: gen_peppy_theyre_on_me_im_gettin_careless + +gen_peppy_to_barrel_roll_press_z_or_r_twice: + type: NAUDIO:V1:SAMPLE + offset: 0x14170 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_to_barrel_roll_press_z_or_r_twice + +gen_peppy_trust_your_instincts: + type: NAUDIO:V1:SAMPLE + offset: 0x143D0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_trust_your_instincts + +gen_peppy_try_a_sommersault: + type: NAUDIO:V1:SAMPLE + offset: 0x13C30 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_try_a_sommersault + +gen_peppy_try_a_u_turn: + type: NAUDIO:V1:SAMPLE + offset: 0x13C50 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_try_a_u_turn + +gen_peppy_try_hovering: + type: NAUDIO:V1:SAMPLE + offset: 0x6A70 + parent: 0x6680 + sampleBankId: 2 + symbol: gen_peppy_try_hovering + +gen_peppy_use_bombs_wisely: + type: NAUDIO:V1:SAMPLE + offset: 0x13C70 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_use_bombs_wisely + +gen_peppy_use_the_boost_to_get_thru: + type: NAUDIO:V1:SAMPLE + offset: 0x13C90 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_use_the_boost_to_get_thru + +gen_peppy_use_the_brake: + type: NAUDIO:V1:SAMPLE + offset: 0x4A70 + parent: 0x4520 + sampleBankId: 2 + symbol: gen_peppy_use_the_brake + +gen_peppy_watch_out_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x14610 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_watch_out_fox + +gen_peppy_watch_the_radar_carefully_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xE3F0 + parent: 0xDE40 + sampleBankId: 2 + symbol: gen_peppy_watch_the_radar_carefully_fox + +gen_peppy_watch_where_yer_flyin: + type: NAUDIO:V1:SAMPLE + offset: 0x13B30 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_watch_where_yer_flyin + +gen_peppy_whats_taking_you_so_long_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xB4F0 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_peppy_whats_taking_you_so_long_fox + +gen_peppy_whats_the_big_idea_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x13A70 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_whats_the_big_idea_fox + +gen_peppy_you_can_also_lock_on_to_enemies_this_way: + type: NAUDIO:V1:SAMPLE + offset: 0x14590 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_you_can_also_lock_on_to_enemies_this_way + +gen_peppy_your_father_helped_me_like_that_too: + type: NAUDIO:V1:SAMPLE + offset: 0xB650 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_peppy_your_father_helped_me_like_that_too + +gen_peppy_your_skills_have_improved_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x13D30 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_peppy_your_skills_have_improved_fox + +gen_peppy_youre_mine: + type: NAUDIO:V1:SAMPLE + offset: 0xB770 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_peppy_youre_mine + +gen_peppy_youve_got_an_enemy_on_your_tail: + type: NAUDIO:V1:SAMPLE + offset: 0x4A50 + parent: 0x4520 + sampleBankId: 2 + symbol: gen_peppy_youve_got_an_enemy_on_your_tail + +gen_pigma_im_gonna_bust_you_up_real_good: + type: NAUDIO:V1:SAMPLE + offset: 0x12A50 + parent: 0x12400 + sampleBankId: 2 + symbol: gen_pigma_im_gonna_bust_you_up_real_good + +gen_rob_falcos_ship_is_in_the_docking_bay: + type: NAUDIO:V1:SAMPLE + offset: 0x14850 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_rob_falcos_ship_is_in_the_docking_bay + +gen_rob_falcos_ship_is_under_maintenance: + type: NAUDIO:V1:SAMPLE + offset: 0x147F0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_rob_falcos_ship_is_under_maintenance + +gen_rob_good_luck_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x13FB0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_rob_good_luck_fox + +gen_rob_is_in_the_docking_bay: + type: NAUDIO:V1:SAMPLE + offset: 0x148D0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_rob_is_in_the_docking_bay + +gen_rob_location_confirmed: + type: NAUDIO:V1:SAMPLE + offset: 0x13BD0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_rob_location_confirmed + +gen_rob_maintenance_complete_on_falcos_ship: + type: NAUDIO:V1:SAMPLE + offset: 0x148F0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_rob_maintenance_complete_on_falcos_ship + +gen_rob_on_falcos_ship: + type: NAUDIO:V1:SAMPLE + offset: 0x14930 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_rob_on_falcos_ship + +gen_rob_on_peppys_ship: + type: NAUDIO:V1:SAMPLE + offset: 0x14970 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_rob_on_peppys_ship + +gen_rob_on_slippys_ship: + type: NAUDIO:V1:SAMPLE + offset: 0x149B0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_rob_on_slippys_ship + +gen_rob_peppys_ship_is_in_for_repairs: + type: NAUDIO:V1:SAMPLE + offset: 0x14810 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_rob_peppys_ship_is_in_for_repairs + +gen_rob_peppys_ship_is_in_the_docking_bay: + type: NAUDIO:V1:SAMPLE + offset: 0x14870 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_rob_peppys_ship_is_in_the_docking_bay + +gen_rob_repairs_complete: + type: NAUDIO:V1:SAMPLE + offset: 0x14910 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_rob_repairs_complete + +gen_rob_sending_supplies: + type: NAUDIO:V1:SAMPLE + offset: 0x13BF0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_rob_sending_supplies + +gen_rob_ship: + type: NAUDIO:V1:SAMPLE + offset: 0x148B0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_rob_ship + +gen_rob_slippys: + type: NAUDIO:V1:SAMPLE + offset: 0x14890 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_rob_slippys + +gen_rob_slippys_ship_is_in_for_repairs: + type: NAUDIO:V1:SAMPLE + offset: 0x14830 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_rob_slippys_ship_is_in_for_repairs + +gen_slippy_a: + type: NAUDIO:V1:SAMPLE + offset: 0x14550 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_slippy_a + +gen_slippy_ahhh: + type: NAUDIO:V1:SAMPLE + offset: 0xB550 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_slippy_ahhh + +gen_slippy_are_you_okay: + type: NAUDIO:V1:SAMPLE + offset: 0x14210 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_slippy_are_you_okay + +gen_slippy_data_analysis_complete: + type: NAUDIO:V1:SAMPLE + offset: 0x6BB0 + parent: 0x6680 + sampleBankId: 2 + symbol: gen_slippy_data_analysis_complete + +gen_slippy_did_it: + type: NAUDIO:V1:SAMPLE + offset: 0xF230 + parent: 0xEBA0 + sampleBankId: 2 + symbol: gen_slippy_did_it + +gen_slippy_enemy_shield_analyzed: + type: NAUDIO:V1:SAMPLE + offset: 0x4CD0 + parent: 0x4520 + sampleBankId: 2 + symbol: gen_slippy_enemy_shield_analyzed + +gen_slippy_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x13B10 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_slippy_fox + +gen_slippy_fox_get_this_guy_off_me: + type: NAUDIO:V1:SAMPLE + offset: 0xB430 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_slippy_fox_get_this_guy_off_me + +gen_slippy_got_one: + type: NAUDIO:V1:SAMPLE + offset: 0xB7D0 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_slippy_got_one + +gen_slippy_got_you_now: + type: NAUDIO:V1:SAMPLE + offset: 0xB750 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_slippy_got_you_now + +gen_slippy_here_it_comes: + type: NAUDIO:V1:SAMPLE + offset: 0x6BD0 + parent: 0x6680 + sampleBankId: 2 + symbol: gen_slippy_here_it_comes + +gen_slippy_hey_he_was_mine: + type: NAUDIO:V1:SAMPLE + offset: 0x13A50 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_slippy_hey_he_was_mine + +gen_slippy_hey_whats_the_big_idea: + type: NAUDIO:V1:SAMPLE + offset: 0x13970 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_slippy_hey_whats_the_big_idea + +gen_slippy_hold: + type: NAUDIO:V1:SAMPLE + offset: 0x14530 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_slippy_hold + +gen_slippy_hows_the_arwing_doing_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x14070 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_slippy_hows_the_arwing_doing_fox + +gen_slippy_i_got_the_last_one: + type: NAUDIO:V1:SAMPLE + offset: 0xBF30 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_slippy_i_got_the_last_one + +gen_slippy_i_thought_i_was_a_goner: + type: NAUDIO:V1:SAMPLE + offset: 0x137D0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_slippy_i_thought_i_was_a_goner + +gen_slippy_im_fine_im_fine: + type: NAUDIO:V1:SAMPLE + offset: 0x13750 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_slippy_im_fine_im_fine + +gen_slippy_im_going_down: + type: NAUDIO:V1:SAMPLE + offset: 0x15F10 + parent: 0x15A20 + sampleBankId: 2 + symbol: gen_slippy_im_going_down + +gen_slippy_im_going_left: + type: NAUDIO:V1:SAMPLE + offset: 0x15E90 + parent: 0x15A20 + sampleBankId: 2 + symbol: gen_slippy_im_going_left + +gen_slippy_im_going_right: + type: NAUDIO:V1:SAMPLE + offset: 0x15E70 + parent: 0x15A20 + sampleBankId: 2 + symbol: gen_slippy_im_going_right + +gen_slippy_im_going_up: + type: NAUDIO:V1:SAMPLE + offset: 0x15ED0 + parent: 0x15A20 + sampleBankId: 2 + symbol: gen_slippy_im_going_up + +gen_slippy_im_having_some_trouble_here: + type: NAUDIO:V1:SAMPLE + offset: 0x13790 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_slippy_im_having_some_trouble_here + +gen_slippy_im_hit: + type: NAUDIO:V1:SAMPLE + offset: 0xB570 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_slippy_im_hit + +gen_slippy_im_monkey_food_if_i_dont_leave: + type: NAUDIO:V1:SAMPLE + offset: 0x13BB0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_slippy_im_monkey_food_if_i_dont_leave + +gen_slippy_ive: + type: NAUDIO:V1:SAMPLE + offset: 0xB730 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_slippy_ive + +gen_slippy_look_out_behind_you: + type: NAUDIO:V1:SAMPLE + offset: 0x14350 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_slippy_look_out_behind_you + +gen_slippy_nooo: + type: NAUDIO:V1:SAMPLE + offset: 0x13A30 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_slippy_nooo + +gen_slippy_oh_no: + type: NAUDIO:V1:SAMPLE + offset: 0x144D0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_slippy_oh_no + +gen_slippy_slippys_hit: + type: NAUDIO:V1:SAMPLE + offset: 0x13910 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_slippy_slippys_hit + +gen_slippy_that_was_too_close: + type: NAUDIO:V1:SAMPLE + offset: 0xB630 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_slippy_that_was_too_close + +gen_slippy_there_ya_go: + type: NAUDIO:V1:SAMPLE + offset: 0x5050 + parent: 0x4520 + sampleBankId: 2 + symbol: gen_slippy_there_ya_go + +gen_slippy_this_is_really_starting_to: + type: NAUDIO:V1:SAMPLE + offset: 0xB490 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_slippy_this_is_really_starting_to + +gen_slippy_tick_me_off: + type: NAUDIO:V1:SAMPLE + offset: 0xB4B0 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_slippy_tick_me_off + +gen_slippy_to_charge_your_laser: + type: NAUDIO:V1:SAMPLE + offset: 0x14570 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_slippy_to_charge_your_laser + +gen_slippy_watch_out: + type: NAUDIO:V1:SAMPLE + offset: 0x145D0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_slippy_watch_out + +gen_slippy_what_do_you_think_youre_doing: + type: NAUDIO:V1:SAMPLE + offset: 0x13AF0 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_slippy_what_do_you_think_youre_doing + +gen_slippy_whew: + type: NAUDIO:V1:SAMPLE + offset: 0xB610 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_slippy_whew + +gen_slippy_whew_youre_alright: + type: NAUDIO:V1:SAMPLE + offset: 0x14470 + parent: 0x134A0 + sampleBankId: 2 + symbol: gen_slippy_whew_youre_alright + +gen_slippy_yeah_yeah: + type: NAUDIO:V1:SAMPLE + offset: 0x9D10 + parent: 0x96A0 + sampleBankId: 2 + symbol: gen_slippy_yeah_yeah + +gen_slippy_yippee: + type: NAUDIO:V1:SAMPLE + offset: 0xF1F0 + parent: 0xEBA0 + sampleBankId: 2 + symbol: gen_slippy_yippee + +gen_slippy_you: + type: NAUDIO:V1:SAMPLE + offset: 0xF210 + parent: 0xEBA0 + sampleBankId: 2 + symbol: gen_slippy_you + +gen_slippy_youre_not_gettin_away_that_easy: + type: NAUDIO:V1:SAMPLE + offset: 0xB690 + parent: 0xB100 + sampleBankId: 2 + symbol: gen_slippy_youre_not_gettin_away_that_easy + +gen_wolf_is_that_all_youve_got: + type: NAUDIO:V1:SAMPLE + offset: 0x12A10 + parent: 0x12400 + sampleBankId: 2 + symbol: gen_wolf_is_that_all_youve_got + +gen_wolf_what: + type: NAUDIO:V1:SAMPLE + offset: 0x129F0 + parent: 0x12400 + sampleBankId: 2 + symbol: gen_wolf_what + +ka_bill_all_units_report: + type: NAUDIO:V1:SAMPLE + offset: 0x11A50 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_all_units_report + +ka_bill_bulldog_unit: + type: NAUDIO:V1:SAMPLE + offset: 0x11A10 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_bulldog_unit + +ka_bill_care_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x11CD0 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_care_fox + +ka_bill_cover_the_base: + type: NAUDIO:V1:SAMPLE + offset: 0x119F0 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_cover_the_base + +ka_bill_dont_let_anything_through: + type: NAUDIO:V1:SAMPLE + offset: 0x11A30 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_dont_let_anything_through + +ka_bill_enemy_mothership_approaching: + type: NAUDIO:V1:SAMPLE + offset: 0x11A90 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_enemy_mothership_approaching + +ka_bill_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x11C10 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_fox + +ka_bill_fox_thats_one_of_ours: + type: NAUDIO:V1:SAMPLE + offset: 0x119B0 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_fox_thats_one_of_ours + +ka_bill_fox_you_made_it: + type: NAUDIO:V1:SAMPLE + offset: 0x118B0 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_fox_you_made_it + +ka_bill_get_outta_here_now: + type: NAUDIO:V1:SAMPLE + offset: 0x11C30 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_get_outta_here_now + +ka_bill_go_for_the_four_hatches_on_the_underside: + type: NAUDIO:V1:SAMPLE + offset: 0x11AF0 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_go_for_the_four_hatches_on_the_underside + +ka_bill_hang_on_guys: + type: NAUDIO:V1:SAMPLE + offset: 0x117E0 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_hang_on_guys + +ka_bill_help_is_on_the_way: + type: NAUDIO:V1:SAMPLE + offset: 0x11890 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_help_is_on_the_way + +ka_bill_hurry: + type: NAUDIO:V1:SAMPLE + offset: 0x11BD0 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_hurry + +ka_bill_hurry_up_and_take_out_that_core: + type: NAUDIO:V1:SAMPLE + offset: 0x11B90 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_hurry_up_and_take_out_that_core + +ka_bill_husky_unit: + type: NAUDIO:V1:SAMPLE + offset: 0x119D0 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_husky_unit + +ka_bill_im_glad_were_on_the_same_team_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x11D10 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_im_glad_were_on_the_same_team_fox + +ka_bill_just_like_old_times_eh_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x11D50 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_just_like_old_times_eh_fox + +ka_bill_stand_by_to_attack: + type: NAUDIO:V1:SAMPLE + offset: 0x11B70 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_stand_by_to_attack + +ka_bill_stick_around_for_a_while: + type: NAUDIO:V1:SAMPLE + offset: 0x11D70 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_stick_around_for_a_while + +ka_bill_take: + type: NAUDIO:V1:SAMPLE + offset: 0x11CB0 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_take + +ka_bill_the_core_has_appeared: + type: NAUDIO:V1:SAMPLE + offset: 0x11B50 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_the_core_has_appeared + +ka_bill_the_hatches_are_open: + type: NAUDIO:V1:SAMPLE + offset: 0x11B10 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_the_hatches_are_open + +ka_bill_theres_not_much_time_left: + type: NAUDIO:V1:SAMPLE + offset: 0x11BB0 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_theres_not_much_time_left + +ka_bill_theres_some_sort_of_energy_reaction: + type: NAUDIO:V1:SAMPLE + offset: 0x11B30 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_theres_some_sort_of_energy_reaction + +ka_bill_try_shooting_the_bad_guys_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x11990 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_try_shooting_the_bad_guys_fox + +ka_bill_we_can_catch_up_later_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x11930 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_we_can_catch_up_later_fox + +ka_bill_yeehaw_you_did_it: + type: NAUDIO:V1:SAMPLE + offset: 0x11BF0 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_yeehaw_you_did_it + +ka_bill_youve_become_quite_a_pilot: + type: NAUDIO:V1:SAMPLE + offset: 0x11AB0 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_bill_youve_become_quite_a_pilot + +ka_falco_man_theres_just_no_end_to_these_guys: + type: NAUDIO:V1:SAMPLE + offset: 0x11A70 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_falco_man_theres_just_no_end_to_these_guys + +ka_fox_all_aircraft_break_away: + type: NAUDIO:V1:SAMPLE + offset: 0x11C50 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_fox_all_aircraft_break_away + +ka_fox_bill: + type: NAUDIO:V1:SAMPLE + offset: 0x118D0 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_fox_bill + +ka_fox_dang: + type: NAUDIO:V1:SAMPLE + offset: 0x11C70 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_fox_dang + +ka_fox_i_cant_believe_it: + type: NAUDIO:V1:SAMPLE + offset: 0x11910 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_fox_i_cant_believe_it + +ka_fox_is_that_you: + type: NAUDIO:V1:SAMPLE + offset: 0x118F0 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_fox_is_that_you + +ka_fox_you_owe_me_one: + type: NAUDIO:V1:SAMPLE + offset: 0x11D30 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_fox_you_owe_me_one + +ka_fox_you_too_bill: + type: NAUDIO:V1:SAMPLE + offset: 0x11CF0 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_fox_you_too_bill + +ka_peppy_dont_get_so_down_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x11C90 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_peppy_dont_get_so_down_fox + +ka_peppy_enemy_down: + type: NAUDIO:V1:SAMPLE + offset: 0x11DB0 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_peppy_enemy_down + +ka_peppy_wait_that_was_one_of_ours: + type: NAUDIO:V1:SAMPLE + offset: 0x11DD0 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_peppy_wait_that_was_one_of_ours + +ka_slippy_from_the_bad: + type: NAUDIO:V1:SAMPLE + offset: 0x11970 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_slippy_from_the_bad + +ka_slippy_hard_to_tell_the_good_guys: + type: NAUDIO:V1:SAMPLE + offset: 0x11950 + parent: 0x115E0 + sampleBankId: 2 + symbol: ka_slippy_hard_to_tell_the_good_guys + +ma_falco_full_up_here: + type: NAUDIO:V1:SAMPLE + offset: 0x109B0 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_falco_full_up_here + +ma_falco_hey_ive_got_my_hands: + type: NAUDIO:V1:SAMPLE + offset: 0x10990 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_falco_hey_ive_got_my_hands + +ma_falco_i_see_the_fuel_bunker_on_the_right_side: + type: NAUDIO:V1:SAMPLE + offset: 0x109F0 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_falco_i_see_the_fuel_bunker_on_the_right_side + +ma_falco_im_here_to_rescue_you: + type: NAUDIO:V1:SAMPLE + offset: 0x13CB0 + parent: 0x134A0 + sampleBankId: 2 + symbol: ma_falco_im_here_to_rescue_you + +ma_falco_katt: + type: NAUDIO:V1:SAMPLE + offset: 0x10AB0 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_falco_katt + +ma_falco_not_you_again: + type: NAUDIO:V1:SAMPLE + offset: 0x10AD0 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_falco_not_you_again + +ma_falco_now_its_our_turn_to_kick_some_tail: + type: NAUDIO:V1:SAMPLE + offset: 0x10C10 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_falco_now_its_our_turn_to_kick_some_tail + +ma_fox_i_spot_the_train: + type: NAUDIO:V1:SAMPLE + offset: 0x108C0 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_fox_i_spot_the_train + +ma_fox_im_taking_it_out: + type: NAUDIO:V1:SAMPLE + offset: 0x10970 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_fox_im_taking_it_out + +ma_katt_boys: + type: NAUDIO:V1:SAMPLE + offset: 0x10A70 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_katt_boys + +ma_katt_im_crushed: + type: NAUDIO:V1:SAMPLE + offset: 0x10A90 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_katt_im_crushed + +ma_katt_im_outta_here: + type: NAUDIO:V1:SAMPLE + offset: 0x10C50 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_katt_im_outta_here + +ma_katt_ive_got_the_left: + type: NAUDIO:V1:SAMPLE + offset: 0x10AF0 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_katt_ive_got_the_left + +ma_katt_see_you_again: + type: NAUDIO:V1:SAMPLE + offset: 0x10BD0 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_katt_see_you_again + +ma_katt_startin_without_me: + type: NAUDIO:V1:SAMPLE + offset: 0x10A50 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_katt_startin_without_me + +ma_katt_take_care_falco: + type: NAUDIO:V1:SAMPLE + offset: 0x10C70 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_katt_take_care_falco + +ma_katt_you_take_the_right_hon: + type: NAUDIO:V1:SAMPLE + offset: 0x10B10 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_katt_you_take_the_right_hon + +ma_katt_youre_pretty_good_tiger: + type: NAUDIO:V1:SAMPLE + offset: 0x10B90 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_katt_youre_pretty_good_tiger + +ma_mechbeth_come_a_little_closer: + type: NAUDIO:V1:SAMPLE + offset: 0x10D10 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_come_a_little_closer + +ma_mechbeth_dang: + type: NAUDIO:V1:SAMPLE + offset: 0x10CB0 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_dang + +ma_mechbeth_detatch_the_rear_vehicle: + type: NAUDIO:V1:SAMPLE + offset: 0x10CD0 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_detatch_the_rear_vehicle + +ma_mechbeth_get_away: + type: NAUDIO:V1:SAMPLE + offset: 0x10E10 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_get_away + +ma_mechbeth_heh_heh_heh_whats_wrong: + type: NAUDIO:V1:SAMPLE + offset: 0x10E30 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_heh_heh_heh_whats_wrong + +ma_mechbeth_here_come_the_little_hyenas_now: + type: NAUDIO:V1:SAMPLE + offset: 0x10C90 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_here_come_the_little_hyenas_now + +ma_mechbeth_here_ya_go: + type: NAUDIO:V1:SAMPLE + offset: 0x10D30 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_here_ya_go + +ma_mechbeth_hit_the_brakes: + type: NAUDIO:V1:SAMPLE + offset: 0x10E90 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_hit_the_brakes + +ma_mechbeth_i_cant: + type: NAUDIO:V1:SAMPLE + offset: 0x10EB0 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_i_cant + +ma_mechbeth_i_didnt_expect_to_have_to_use_this: + type: NAUDIO:V1:SAMPLE + offset: 0x10D90 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_i_didnt_expect_to_have_to_use_this + +ma_mechbeth_ill_lure_these_guys_to_the_front: + type: NAUDIO:V1:SAMPLE + offset: 0x10D70 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_ill_lure_these_guys_to_the_front + +ma_mechbeth_no: + type: NAUDIO:V1:SAMPLE + offset: 0x10DF0 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_no + +ma_mechbeth_no_2: + type: NAUDIO:V1:SAMPLE + offset: 0x10E70 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_no_2 + +ma_mechbeth_step_on_the_gas: + type: NAUDIO:V1:SAMPLE + offset: 0x10EF0 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_step_on_the_gas + +ma_mechbeth_stop_it: + type: NAUDIO:V1:SAMPLE + offset: 0x10ED0 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_stop_it + +ma_mechbeth_take_this: + type: NAUDIO:V1:SAMPLE + offset: 0x10F70 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_take_this + +ma_mechbeth_theyre_not_takin_me_seriously: + type: NAUDIO:V1:SAMPLE + offset: 0x10D50 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_theyre_not_takin_me_seriously + +ma_mechbeth_time_to_end_this: + type: NAUDIO:V1:SAMPLE + offset: 0x10F50 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_time_to_end_this + +ma_mechbeth_try_this: + type: NAUDIO:V1:SAMPLE + offset: 0x10E50 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_try_this + +ma_mechbeth_whats_wrong: + type: NAUDIO:V1:SAMPLE + offset: 0x10CF0 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_whats_wrong + +ma_mechbeth_whoooa: + type: NAUDIO:V1:SAMPLE + offset: 0x10DD0 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_whoooa + +ma_mechbeth_youre_too_slow: + type: NAUDIO:V1:SAMPLE + offset: 0x10F30 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_youre_too_slow + +ma_mechbeth_youre_very_lucky: + type: NAUDIO:V1:SAMPLE + offset: 0x10DB0 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_mechbeth_youre_very_lucky + +ma_peppy_change_the_switch_ahead: + type: NAUDIO:V1:SAMPLE + offset: 0x10A10 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_peppy_change_the_switch_ahead + +ma_peppy_dont_let_em_get_to_the_supply_depot: + type: NAUDIO:V1:SAMPLE + offset: 0x109D0 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_peppy_dont_let_em_get_to_the_supply_depot + +ma_peppy_im_sure_we_hurt_em_this_time: + type: NAUDIO:V1:SAMPLE + offset: 0x10BF0 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_peppy_im_sure_we_hurt_em_this_time + +ma_peppy_okay_now_shoot_the_switcher: + type: NAUDIO:V1:SAMPLE + offset: 0x10B30 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_peppy_okay_now_shoot_the_switcher + +ma_peppy_shoot_the_8_switches_to_open_the_lock: + type: NAUDIO:V1:SAMPLE + offset: 0x10A30 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_peppy_shoot_the_8_switches_to_open_the_lock + +ma_peppy_well_at_least_we_can_take_this_boss_out: + type: NAUDIO:V1:SAMPLE + offset: 0x10B70 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_peppy_well_at_least_we_can_take_this_boss_out + +ma_slippy_hows_the_landmaster_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x10F10 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_slippy_hows_the_landmaster_fox + +ma_slippy_i_can_see_the_look_on_their_stupid_faces: + type: NAUDIO:V1:SAMPLE + offset: 0x10C30 + parent: 0x106C0 + sampleBankId: 2 + symbol: ma_slippy_i_can_see_the_look_on_their_stupid_faces + +map_fox_affirmative_general: + type: NAUDIO:V1:SAMPLE + offset: 0x3670 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_fox_affirmative_general + +map_fox_andross_wont_have_his_way_with_me: + type: NAUDIO:V1:SAMPLE + offset: 0x3390 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_fox_andross_wont_have_his_way_with_me + +map_fox_deploy_the_blue_marine: + type: NAUDIO:V1:SAMPLE + offset: 0x36F0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_fox_deploy_the_blue_marine + +map_fox_dont_worry_sir: + type: NAUDIO:V1:SAMPLE + offset: 0x3790 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_fox_dont_worry_sir + +map_fox_i_cant_leave_slippy_hangin: + type: NAUDIO:V1:SAMPLE + offset: 0x3450 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_fox_i_cant_leave_slippy_hangin + +map_fox_i_wont_let_you_down_sir: + type: NAUDIO:V1:SAMPLE + offset: 0x33F0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_fox_i_wont_let_you_down_sir + +map_fox_ill_be_careful: + type: NAUDIO:V1:SAMPLE + offset: 0x3890 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_fox_ill_be_careful + +map_fox_ill_check_it_out: + type: NAUDIO:V1:SAMPLE + offset: 0x3490 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_fox_ill_check_it_out + +map_fox_ill_do_my_best: + type: NAUDIO:V1:SAMPLE + offset: 0x3370 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_fox_ill_do_my_best + +map_fox_im_on_it: + type: NAUDIO:V1:SAMPLE + offset: 0x3530 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_fox_im_on_it + +map_fox_im_on_my_way: + type: NAUDIO:V1:SAMPLE + offset: 0x3810 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_fox_im_on_my_way + +map_fox_itll_be_a_piece_of_cake_general: + type: NAUDIO:V1:SAMPLE + offset: 0x3610 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_fox_itll_be_a_piece_of_cake_general + +map_fox_roger_general: + type: NAUDIO:V1:SAMPLE + offset: 0x34D0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_fox_roger_general + +map_fox_will_do_general: + type: NAUDIO:V1:SAMPLE + offset: 0x35B0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_fox_will_do_general + +map_fox_yes_sir: + type: NAUDIO:V1:SAMPLE + offset: 0x36D0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_fox_yes_sir + +map_narrator_a_few_years_have_passed: + type: NAUDIO:V1:SAMPLE + offset: 0x3270 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_narrator_a_few_years_have_passed + +map_narrator_and_free_the_lylat_system: + type: NAUDIO:V1:SAMPLE + offset: 0x32D0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_narrator_and_free_the_lylat_system + +map_narrator_and_returned_home_to_tell_james_son_fox_about_his_fathers_fate: + type: NAUDIO:V1:SAMPLE + offset: 0x3250 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_narrator_and_returned_home_to_tell_james_son_fox_about_his_fathers_fate + +map_narrator_andross_has_again_invaded_the_lylat_system: + type: NAUDIO:V1:SAMPLE + offset: 0x3290 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_narrator_andross_has_again_invaded_the_lylat_system + +map_narrator_corneria_fourth_planet_of_the_lylat_system_the_evil_andross_turned_this_once_thriving_system: + type: NAUDIO:V1:SAMPLE + offset: 0x3100 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_narrator_corneria_fourth_planet_of_the_lylat_system_the_evil_andross_turned_this_once_thriving_system + +map_narrator_five_years_later_general_pepper_noticed_strange_activity_coming_from_venom_james_mccloud_pigma_dengar_and_peppy_hare_of_the_star_fox_team_were_sent_to_investigate: + type: NAUDIO:V1:SAMPLE + offset: 0x31F0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_narrator_five_years_later_general_pepper_noticed_strange_activity_coming_from_venom_james_mccloud_pigma_dengar_and_peppy_hare_of_the_star_fox_team_were_sent_to_investigate + +map_narrator_general_pepper_has_turned_to_a_new_star_fox_team_headed_by_fox_mccloud_to_save_corneria: + type: NAUDIO:V1:SAMPLE + offset: 0x32B0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_narrator_general_pepper_has_turned_to_a_new_star_fox_team_headed_by_fox_mccloud_to_save_corneria + +map_narrator_general_pepper_of_the_cornerian_army_was_successful_in_exiling_this_maniacle_scientist_to_the_barren_deserted_planet_venom: + type: NAUDIO:V1:SAMPLE + offset: 0x31D0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_narrator_general_pepper_of_the_cornerian_army_was_successful_in_exiling_this_maniacle_scientist_to_the_barren_deserted_planet_venom + +map_narrator_into_a_wasteland_of_near_extinction: + type: NAUDIO:V1:SAMPLE + offset: 0x31B0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_narrator_into_a_wasteland_of_near_extinction + +map_narrator_once_again: + type: NAUDIO:V1:SAMPLE + offset: 0x32F0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_narrator_once_again + +map_narrator_peppy_barely_escaped_venom: + type: NAUDIO:V1:SAMPLE + offset: 0x3230 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_narrator_peppy_barely_escaped_venom + +map_narrator_upon_their_arrival_pigma_betrayed_the_team_and_james_and_peppy_were_captured_by_andross: + type: NAUDIO:V1:SAMPLE + offset: 0x3210 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_narrator_upon_their_arrival_pigma_betrayed_the_team_and_james_and_peppy_were_captured_by_andross + +map_pepper_be_careful: + type: NAUDIO:V1:SAMPLE + offset: 0x3770 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_be_careful + +map_pepper_be_careful_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x3510 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_be_careful_fox + +map_pepper_be_reasonable_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x3870 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_be_reasonable_fox + +map_pepper_come_back_in_one_piece_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x3590 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_come_back_in_one_piece_fox + +map_pepper_dont_go_burning_that_arwing: + type: NAUDIO:V1:SAMPLE + offset: 0x3850 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_dont_go_burning_that_arwing + +map_pepper_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x37B0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_fox + +map_pepper_great_idea_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x35F0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_great_idea_fox + +map_pepper_help_us_out_here: + type: NAUDIO:V1:SAMPLE + offset: 0x37F0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_help_us_out_here + +map_pepper_i_want_you_to_take_out_the_enemy_bio_weapon: + type: NAUDIO:V1:SAMPLE + offset: 0x36B0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_i_want_you_to_take_out_the_enemy_bio_weapon + +map_pepper_if_you_destroy_the_satellite_we_can_go_straight_for_venom: + type: NAUDIO:V1:SAMPLE + offset: 0x34F0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_if_you_destroy_the_satellite_we_can_go_straight_for_venom + +map_pepper_impressive_star_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x33B0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_impressive_star_fox + +map_pepper_its_about: + type: NAUDIO:V1:SAMPLE + offset: 0x3310 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_its_about + +map_pepper_its_almost_over: + type: NAUDIO:V1:SAMPLE + offset: 0x3550 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_its_almost_over + +map_pepper_its_too_dangerous_there: + type: NAUDIO:V1:SAMPLE + offset: 0x3430 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_its_too_dangerous_there + +map_pepper_katina_is_battling_the_enemy: + type: NAUDIO:V1:SAMPLE + offset: 0x3630 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_katina_is_battling_the_enemy + +map_pepper_now_watch_out_for_enemies_in_the_asteroid_field: + type: NAUDIO:V1:SAMPLE + offset: 0x33D0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_now_watch_out_for_enemies_in_the_asteroid_field + +map_pepper_recover_our_base_from_the_enemy_army: + type: NAUDIO:V1:SAMPLE + offset: 0x34B0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_recover_our_base_from_the_enemy_army + +map_pepper_reports_indicate_that_andross_is_working_on_some_secret_weapon: + type: NAUDIO:V1:SAMPLE + offset: 0x3470 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_reports_indicate_that_andross_is_working_on_some_secret_weapon + +map_pepper_so_youre_going_to_attack_the_enemy_base: + type: NAUDIO:V1:SAMPLE + offset: 0x35D0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_so_youre_going_to_attack_the_enemy_base + +map_pepper_star_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x3690 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_star_fox + +map_pepper_that_areas_an_oven: + type: NAUDIO:V1:SAMPLE + offset: 0x3830 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_that_areas_an_oven + +map_pepper_the_enemy_army_is_gunning_for_you: + type: NAUDIO:V1:SAMPLE + offset: 0x3750 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_the_enemy_army_is_gunning_for_you + +map_pepper_theres_an_enemy_base_there: + type: NAUDIO:V1:SAMPLE + offset: 0x3710 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_theres_an_enemy_base_there + +map_pepper_time_you_showed_up_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x3330 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_time_you_showed_up_fox + +map_pepper_were_in_your_debt: + type: NAUDIO:V1:SAMPLE + offset: 0x3570 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_were_in_your_debt + +map_pepper_were_under_attack: + type: NAUDIO:V1:SAMPLE + offset: 0x37D0 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_were_under_attack + +map_pepper_what_are_you_doing: + type: NAUDIO:V1:SAMPLE + offset: 0x3410 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_what_are_you_doing + +map_pepper_will_you_help_em_out: + type: NAUDIO:V1:SAMPLE + offset: 0x3650 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_will_you_help_em_out + +map_pepper_youre_the_only_hope_for_our_world: + type: NAUDIO:V1:SAMPLE + offset: 0x3350 + parent: 0x2F00 + sampleBankId: 1 + symbol: map_pepper_youre_the_only_hope_for_our_world + +me_falco_are_you_gonna_listen_to_that_monkey: + type: NAUDIO:V1:SAMPLE + offset: 0x6010 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_falco_are_you_gonna_listen_to_that_monkey + +me_falco_i_guess_its_your_turn_to_be_thankful: + type: NAUDIO:V1:SAMPLE + offset: 0x5E90 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_falco_i_guess_its_your_turn_to_be_thankful + +me_fox_but_im_in_a_hurry: + type: NAUDIO:V1:SAMPLE + offset: 0x60D0 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_fox_but_im_in_a_hurry + +me_fox_sorry_to_jet: + type: NAUDIO:V1:SAMPLE + offset: 0x60B0 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_fox_sorry_to_jet + +me_fox_were_heading_into_the_asteroids: + type: NAUDIO:V1:SAMPLE + offset: 0x5D50 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_fox_were_heading_into_the_asteroids + +me_meteo_crusher_defeat: + type: NAUDIO:V1:SAMPLE + offset: 0x5FF0 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_meteo_crusher_defeat + +me_meteo_crusher_does_not_work: + type: NAUDIO:V1:SAMPLE + offset: 0x6090 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_meteo_crusher_does_not_work + +me_meteo_crusher_hah_youre_not_as: + type: NAUDIO:V1:SAMPLE + offset: 0x6030 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_meteo_crusher_hah_youre_not_as + +me_meteo_crusher_how_about: + type: NAUDIO:V1:SAMPLE + offset: 0x5F70 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_meteo_crusher_how_about + +me_meteo_crusher_i_admit: + type: NAUDIO:V1:SAMPLE + offset: 0x5FD0 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_meteo_crusher_i_admit + +me_meteo_crusher_i_cannot_allow_you_to_go_any_further: + type: NAUDIO:V1:SAMPLE + offset: 0x5EF0 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_meteo_crusher_i_cannot_allow_you_to_go_any_further + +me_meteo_crusher_i_cant_believe_i_lost_to_this: + type: NAUDIO:V1:SAMPLE + offset: 0x60F0 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_meteo_crusher_i_cant_believe_i_lost_to_this + +me_meteo_crusher_if_this: + type: NAUDIO:V1:SAMPLE + offset: 0x6070 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_meteo_crusher_if_this + +me_meteo_crusher_im_no_match_for_you: + type: NAUDIO:V1:SAMPLE + offset: 0x5FB0 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_meteo_crusher_im_no_match_for_you + +me_meteo_crusher_ive_underestimated_you: + type: NAUDIO:V1:SAMPLE + offset: 0x5F50 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_meteo_crusher_ive_underestimated_you + +me_meteo_crusher_lets_see_what_youve_got: + type: NAUDIO:V1:SAMPLE + offset: 0x5F10 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_meteo_crusher_lets_see_what_youve_got + +me_meteo_crusher_scum: + type: NAUDIO:V1:SAMPLE + offset: 0x6110 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_meteo_crusher_scum + +me_meteo_crusher_stupid_as_you_look: + type: NAUDIO:V1:SAMPLE + offset: 0x6050 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_meteo_crusher_stupid_as_you_look + +me_meteo_crusher_this: + type: NAUDIO:V1:SAMPLE + offset: 0x5F90 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_meteo_crusher_this + +me_meteo_crusher_youre_more_cunning_than_i_thought: + type: NAUDIO:V1:SAMPLE + offset: 0x6130 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_meteo_crusher_youre_more_cunning_than_i_thought + +me_peppy_be_careful_its_a_trap: + type: NAUDIO:V1:SAMPLE + offset: 0x5DD0 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_peppy_be_careful_its_a_trap + +me_peppy_incoming_message_from_rob64: + type: NAUDIO:V1:SAMPLE + offset: 0x13E90 + parent: 0x134A0 + sampleBankId: 2 + symbol: me_peppy_incoming_message_from_rob64 + +me_peppy_its_quiet: + type: NAUDIO:V1:SAMPLE + offset: 0x5D90 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_peppy_its_quiet + +me_peppy_quit_dinkin_around_slip: + type: NAUDIO:V1:SAMPLE + offset: 0x5D30 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_peppy_quit_dinkin_around_slip + +me_peppy_that_shields_absorbing_the_laser: + type: NAUDIO:V1:SAMPLE + offset: 0x5F30 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_peppy_that_shields_absorbing_the_laser + +me_peppy_too_quiet: + type: NAUDIO:V1:SAMPLE + offset: 0x5DB0 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_peppy_too_quiet + +me_slippy_can_you_make_it: + type: NAUDIO:V1:SAMPLE + offset: 0x5E50 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_slippy_can_you_make_it + +me_slippy_here_comes_a_big_one: + type: NAUDIO:V1:SAMPLE + offset: 0x5D70 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_slippy_here_comes_a_big_one + +me_slippy_take_that: + type: NAUDIO:V1:SAMPLE + offset: 0x5ED0 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_slippy_take_that + +me_slippy_things_are_starting_to_heat_up: + type: NAUDIO:V1:SAMPLE + offset: 0x5C80 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_slippy_things_are_starting_to_heat_up + +me_slippy_woah: + type: NAUDIO:V1:SAMPLE + offset: 0x5E30 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_slippy_woah + +me_slippy_you_want_a_piece_of_me: + type: NAUDIO:V1:SAMPLE + offset: 0x5EB0 + parent: 0x5A80 + sampleBankId: 2 + symbol: me_slippy_you_want_a_piece_of_me + +ms_: + type: NAUDIO:V1:SAMPLE + offset: 0x16D40 + parent: 0x16400 + sampleBankId: 3 + symbol: ms_ + +ms_bass_drum: + type: NAUDIO:V1:SAMPLE + offset: 0x16A00 + parent: 0x16400 + sampleBankId: 3 + symbol: ms_bass_drum + +ms_bass_drum_2: + type: NAUDIO:V1:SAMPLE + offset: 0x17BE0 + parent: 0x177A0 + sampleBankId: 3 + symbol: ms_bass_drum_2 + +ms_bass_drum_3: + type: NAUDIO:V1:SAMPLE + offset: 0x17DA0 + parent: 0x177A0 + sampleBankId: 3 + symbol: ms_bass_drum_3 + +ms_cymbal: + type: NAUDIO:V1:SAMPLE + offset: 0x16990 + parent: 0x16400 + sampleBankId: 3 + symbol: ms_cymbal + +ms_cymbal_2: + type: NAUDIO:V1:SAMPLE + offset: 0x17D30 + parent: 0x177A0 + sampleBankId: 3 + symbol: ms_cymbal_2 + +ms_cymbal_3: + type: NAUDIO:V1:SAMPLE + offset: 0x18DD0 + parent: 0x18960 + sampleBankId: 3 + symbol: ms_cymbal_3 + +ms_cymbal_4: + type: NAUDIO:V1:SAMPLE + offset: 0x197A0 + parent: 0x192A0 + sampleBankId: 3 + symbol: ms_cymbal_4 + +ms_cymbal_5: + type: NAUDIO:V1:SAMPLE + offset: 0x1A0F0 + parent: 0x19C80 + sampleBankId: 3 + symbol: ms_cymbal_5 + +ms_cymbal_6: + type: NAUDIO:V1:SAMPLE + offset: 0x1AAA0 + parent: 0x1A5A0 + sampleBankId: 3 + symbol: ms_cymbal_6 + +ms_digital_drum: + type: NAUDIO:V1:SAMPLE + offset: 0x16E20 + parent: 0x16400 + sampleBankId: 3 + symbol: ms_digital_drum + +ms_digital_organ: + type: NAUDIO:V1:SAMPLE + offset: 0x19D40 + parent: 0x19C80 + sampleBankId: 3 + symbol: ms_digital_organ + +ms_digital_organ_2: + type: NAUDIO:V1:SAMPLE + offset: 0x1B040 + parent: 0x1AF80 + sampleBankId: 3 + symbol: ms_digital_organ_2 + +ms_digital_tom: + type: NAUDIO:V1:SAMPLE + offset: 0x1BCF0 + parent: 0x1B960 + sampleBankId: 3 + symbol: ms_digital_tom + +ms_digital_tom_drum: + type: NAUDIO:V1:SAMPLE + offset: 0x18BD0 + parent: 0x18960 + sampleBankId: 3 + symbol: ms_digital_tom_drum + +ms_digital_tom_drum_2: + type: NAUDIO:V1:SAMPLE + offset: 0x195A0 + parent: 0x192A0 + sampleBankId: 3 + symbol: ms_digital_tom_drum_2 + +ms_digital_tom_drum_3: + type: NAUDIO:V1:SAMPLE + offset: 0x1B280 + parent: 0x1AF80 + sampleBankId: 3 + symbol: ms_digital_tom_drum_3 + +ms_discordant_string_hit: + type: NAUDIO:V1:SAMPLE + offset: 0x1D9C0 + parent: 0x1D750 + sampleBankId: 3 + symbol: ms_discordant_string_hit + +ms_electric_organ: + type: NAUDIO:V1:SAMPLE + offset: 0x17E30 + parent: 0x177A0 + sampleBankId: 3 + symbol: ms_electric_organ + +ms_gregorian_vocals: + type: NAUDIO:V1:SAMPLE + offset: 0x18050 + parent: 0x177A0 + sampleBankId: 3 + symbol: ms_gregorian_vocals + +ms_gregorian_vocals_2: + type: NAUDIO:V1:SAMPLE + offset: 0x180E0 + parent: 0x177A0 + sampleBankId: 3 + symbol: ms_gregorian_vocals_2 + +ms_hammer_hit: + type: NAUDIO:V1:SAMPLE + offset: 0x16C40 + parent: 0x16400 + sampleBankId: 3 + symbol: ms_hammer_hit + +ms_hammer_hit_2: + type: NAUDIO:V1:SAMPLE + offset: 0x16C0 + parent: 0x0 + sampleBankId: 0 + symbol: ms_hammer_hit_2 + +ms_horn: + type: NAUDIO:V1:SAMPLE + offset: 0x16690 + parent: 0x16400 + sampleBankId: 3 + symbol: ms_horn + +ms_horn_2: + type: NAUDIO:V1:SAMPLE + offset: 0x17910 + parent: 0x177A0 + sampleBankId: 3 + symbol: ms_horn_2 + +ms_horn_3: + type: NAUDIO:V1:SAMPLE + offset: 0x19360 + parent: 0x192A0 + sampleBankId: 3 + symbol: ms_horn_3 + +ms_horn_4: + type: NAUDIO:V1:SAMPLE + offset: 0x1A660 + parent: 0x1A5A0 + sampleBankId: 3 + symbol: ms_horn_4 + +ms_low_flute: + type: NAUDIO:V1:SAMPLE + offset: 0x176C0 + parent: 0x17620 + sampleBankId: 3 + symbol: ms_low_flute + +ms_oboe: + type: NAUDIO:V1:SAMPLE + offset: 0x17880 + parent: 0x177A0 + sampleBankId: 3 + symbol: ms_oboe + +ms_pan_flute: + type: NAUDIO:V1:SAMPLE + offset: 0x164E0 + parent: 0x16400 + sampleBankId: 3 + symbol: ms_pan_flute + +ms_plucked_strings: + type: NAUDIO:V1:SAMPLE + offset: 0x17FE0 + parent: 0x177A0 + sampleBankId: 3 + symbol: ms_plucked_strings + +ms_reverse_strings: + type: NAUDIO:V1:SAMPLE + offset: 0x1C5E0 + parent: 0x1C370 + sampleBankId: 3 + symbol: ms_reverse_strings + +ms_sawtooth_hit: + type: NAUDIO:V1:SAMPLE + offset: 0x19510 + parent: 0x192A0 + sampleBankId: 3 + symbol: ms_sawtooth_hit + +ms_sawtooth_hit_2: + type: NAUDIO:V1:SAMPLE + offset: 0x19EF0 + parent: 0x19C80 + sampleBankId: 3 + symbol: ms_sawtooth_hit_2 + +ms_sawtooth_hit_3: + type: NAUDIO:V1:SAMPLE + offset: 0x1A8A0 + parent: 0x1A5A0 + sampleBankId: 3 + symbol: ms_sawtooth_hit_3 + +ms_sawtooth_hit_4: + type: NAUDIO:V1:SAMPLE + offset: 0x1B1F0 + parent: 0x1AF80 + sampleBankId: 3 + symbol: ms_sawtooth_hit_4 + +ms_sawtooth_synth: + type: NAUDIO:V1:SAMPLE + offset: 0x16A90 + parent: 0x16400 + sampleBankId: 3 + symbol: ms_sawtooth_synth + +ms_sawtooth_synth_2: + type: NAUDIO:V1:SAMPLE + offset: 0x18B40 + parent: 0x18960 + sampleBankId: 3 + symbol: ms_sawtooth_synth_2 + +ms_sine_wave: + type: NAUDIO:V1:SAMPLE + offset: 0x16CB0 + parent: 0x16400 + sampleBankId: 3 + symbol: ms_sine_wave + +ms_sine_wave_2: + type: NAUDIO:V1:SAMPLE + offset: 0x177F0 + parent: 0x177A0 + sampleBankId: 3 + symbol: ms_sine_wave_2 + +ms_sine_wave_3: + type: NAUDIO:V1:SAMPLE + offset: 0x18170 + parent: 0x177A0 + sampleBankId: 3 + symbol: ms_sine_wave_3 + +ms_snare_drum: + type: NAUDIO:V1:SAMPLE + offset: 0x168B0 + parent: 0x16400 + sampleBankId: 3 + symbol: ms_snare_drum + +ms_snare_drum_2: + type: NAUDIO:V1:SAMPLE + offset: 0x16920 + parent: 0x16400 + sampleBankId: 3 + symbol: ms_snare_drum_2 + +ms_snare_drum_3: + type: NAUDIO:V1:SAMPLE + offset: 0x17C50 + parent: 0x177A0 + sampleBankId: 3 + symbol: ms_snare_drum_3 + +ms_snare_drum_4: + type: NAUDIO:V1:SAMPLE + offset: 0x17CC0 + parent: 0x177A0 + sampleBankId: 3 + symbol: ms_snare_drum_4 + +ms_snare_drum_5: + type: NAUDIO:V1:SAMPLE + offset: 0x18D60 + parent: 0x18960 + sampleBankId: 3 + symbol: ms_snare_drum_5 + +ms_snare_drum_6: + type: NAUDIO:V1:SAMPLE + offset: 0x1AA30 + parent: 0x1A5A0 + sampleBankId: 3 + symbol: ms_snare_drum_6 + +ms_snare_drum_roll: + type: NAUDIO:V1:SAMPLE + offset: 0x18C60 + parent: 0x18960 + sampleBankId: 3 + symbol: ms_snare_drum_roll + +ms_snare_drum_roll_2: + type: NAUDIO:V1:SAMPLE + offset: 0x19630 + parent: 0x192A0 + sampleBankId: 3 + symbol: ms_snare_drum_roll_2 + +ms_snare_drum_roll_3: + type: NAUDIO:V1:SAMPLE + offset: 0x19F80 + parent: 0x19C80 + sampleBankId: 3 + symbol: ms_snare_drum_roll_3 + +ms_snare_drum_roll_4: + type: NAUDIO:V1:SAMPLE + offset: 0x1A930 + parent: 0x1A5A0 + sampleBankId: 3 + symbol: ms_snare_drum_roll_4 + +ms_snare_drum_roll_5: + type: NAUDIO:V1:SAMPLE + offset: 0x1B310 + parent: 0x1AF80 + sampleBankId: 3 + symbol: ms_snare_drum_roll_5 + +ms_strings: + type: NAUDIO:V1:SAMPLE + offset: 0x16B20 + parent: 0x16400 + sampleBankId: 3 + symbol: ms_strings + +ms_strings_10: + type: NAUDIO:V1:SAMPLE + offset: 0x19E60 + parent: 0x19C80 + sampleBankId: 3 + symbol: ms_strings_10 + +ms_strings_11: + type: NAUDIO:V1:SAMPLE + offset: 0x1A780 + parent: 0x1A5A0 + sampleBankId: 3 + symbol: ms_strings_11 + +ms_strings_12: + type: NAUDIO:V1:SAMPLE + offset: 0x1A810 + parent: 0x1A5A0 + sampleBankId: 3 + symbol: ms_strings_12 + +ms_strings_13: + type: NAUDIO:V1:SAMPLE + offset: 0x1B0D0 + parent: 0x1AF80 + sampleBankId: 3 + symbol: ms_strings_13 + +ms_strings_14: + type: NAUDIO:V1:SAMPLE + offset: 0x1B160 + parent: 0x1AF80 + sampleBankId: 3 + symbol: ms_strings_14 + +ms_strings_2: + type: NAUDIO:V1:SAMPLE + offset: 0x16BB0 + parent: 0x16400 + sampleBankId: 3 + symbol: ms_strings_2 + +ms_strings_3: + type: NAUDIO:V1:SAMPLE + offset: 0x17EC0 + parent: 0x177A0 + sampleBankId: 3 + symbol: ms_strings_3 + +ms_strings_4: + type: NAUDIO:V1:SAMPLE + offset: 0x17F50 + parent: 0x177A0 + sampleBankId: 3 + symbol: ms_strings_4 + +ms_strings_5: + type: NAUDIO:V1:SAMPLE + offset: 0x18A20 + parent: 0x18960 + sampleBankId: 3 + symbol: ms_strings_5 + +ms_strings_6: + type: NAUDIO:V1:SAMPLE + offset: 0x18AB0 + parent: 0x18960 + sampleBankId: 3 + symbol: ms_strings_6 + +ms_strings_7: + type: NAUDIO:V1:SAMPLE + offset: 0x193F0 + parent: 0x192A0 + sampleBankId: 3 + symbol: ms_strings_7 + +ms_strings_8: + type: NAUDIO:V1:SAMPLE + offset: 0x19480 + parent: 0x192A0 + sampleBankId: 3 + symbol: ms_strings_8 + +ms_strings_9: + type: NAUDIO:V1:SAMPLE + offset: 0x19DD0 + parent: 0x19C80 + sampleBankId: 3 + symbol: ms_strings_9 + +ms_timpani: + type: NAUDIO:V1:SAMPLE + offset: 0x16840 + parent: 0x16400 + sampleBankId: 3 + symbol: ms_timpani + +ms_timpani_3: + type: NAUDIO:V1:SAMPLE + offset: 0x18CF0 + parent: 0x18960 + sampleBankId: 3 + symbol: ms_timpani_3 + +ms_timpani_4: + type: NAUDIO:V1:SAMPLE + offset: 0x196C0 + parent: 0x192A0 + sampleBankId: 3 + symbol: ms_timpani_4 + +ms_timpani_5: + type: NAUDIO:V1:SAMPLE + offset: 0x1A010 + parent: 0x19C80 + sampleBankId: 3 + symbol: ms_timpani_5 + +ms_timpani_6: + type: NAUDIO:V1:SAMPLE + offset: 0x1A9C0 + parent: 0x1A5A0 + sampleBankId: 3 + symbol: ms_timpani_6 + +ms_triangle: + type: NAUDIO:V1:SAMPLE + offset: 0x167B0 + parent: 0x16400 + sampleBankId: 3 + symbol: ms_triangle + +ms_triangle_2: + type: NAUDIO:V1:SAMPLE + offset: 0x17B50 + parent: 0x177A0 + sampleBankId: 3 + symbol: ms_triangle_2 + +ms_triangle_wave: + type: NAUDIO:V1:SAMPLE + offset: 0x1C550 + parent: 0x1C370 + sampleBankId: 3 + symbol: ms_triangle_wave + +ms_trumpet: + type: NAUDIO:V1:SAMPLE + offset: 0x16570 + parent: 0x16400 + sampleBankId: 3 + symbol: ms_trumpet + +ms_trumpet_10: + type: NAUDIO:V1:SAMPLE + offset: 0x1A5D0 + parent: 0x1A5A0 + sampleBankId: 3 + symbol: ms_trumpet_10 + +ms_trumpet_11: + type: NAUDIO:V1:SAMPLE + offset: 0x1AFB0 + parent: 0x1AF80 + sampleBankId: 3 + symbol: ms_trumpet_11 + +ms_trumpet_2: + type: NAUDIO:V1:SAMPLE + offset: 0x16600 + parent: 0x16400 + sampleBankId: 3 + symbol: ms_trumpet_2 + +ms_trumpet_3: + type: NAUDIO:V1:SAMPLE + offset: 0x16720 + parent: 0x16400 + sampleBankId: 3 + symbol: ms_trumpet_3 + +ms_trumpet_4: + type: NAUDIO:V1:SAMPLE + offset: 0x179A0 + parent: 0x177A0 + sampleBankId: 3 + symbol: ms_trumpet_4 + +ms_trumpet_5: + type: NAUDIO:V1:SAMPLE + offset: 0x17A30 + parent: 0x177A0 + sampleBankId: 3 + symbol: ms_trumpet_5 + +ms_trumpet_6: + type: NAUDIO:V1:SAMPLE + offset: 0x17AC0 + parent: 0x177A0 + sampleBankId: 3 + symbol: ms_trumpet_6 + +ms_trumpet_7: + type: NAUDIO:V1:SAMPLE + offset: 0x18990 + parent: 0x18960 + sampleBankId: 3 + symbol: ms_trumpet_7 + +ms_trumpet_8: + type: NAUDIO:V1:SAMPLE + offset: 0x192D0 + parent: 0x192A0 + sampleBankId: 3 + symbol: ms_trumpet_8 + +ms_trumpet_9: + type: NAUDIO:V1:SAMPLE + offset: 0x19CB0 + parent: 0x19C80 + sampleBankId: 3 + symbol: ms_trumpet_9 + +op_pepper_and_is_trying_to_take_over_corneria: + type: NAUDIO:V1:SAMPLE + offset: 0x41D0 + parent: 0x3EE0 + sampleBankId: 2 + symbol: op_pepper_and_is_trying_to_take_over_corneria + +op_pepper_andross_has_declared_war: + type: NAUDIO:V1:SAMPLE + offset: 0x4190 + parent: 0x3EE0 + sampleBankId: 2 + symbol: op_pepper_andross_has_declared_war + +op_pepper_hes_invaded_the_lylat_system: + type: NAUDIO:V1:SAMPLE + offset: 0x41B0 + parent: 0x3EE0 + sampleBankId: 2 + symbol: op_pepper_hes_invaded_the_lylat_system + +op_pepper_hurry_star_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x4210 + parent: 0x3EE0 + sampleBankId: 2 + symbol: op_pepper_hurry_star_fox + +op_pepper_our_army_alone_cant_do_the_job: + type: NAUDIO:V1:SAMPLE + offset: 0x41F0 + parent: 0x3EE0 + sampleBankId: 2 + symbol: op_pepper_our_army_alone_cant_do_the_job + +op_pepper_we_need_your_help_star_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x40E0 + parent: 0x3EE0 + sampleBankId: 2 + symbol: op_pepper_we_need_your_help_star_fox + +op_rob_message_from_general_pepper: + type: NAUDIO:V1:SAMPLE + offset: 0x4230 + parent: 0x3EE0 + sampleBankId: 2 + symbol: op_rob_message_from_general_pepper + +op_rob_priority_one: + type: NAUDIO:V1:SAMPLE + offset: 0x4250 + parent: 0x3EE0 + sampleBankId: 2 + symbol: op_rob_priority_one + +se_: + type: NAUDIO:V1:SAMPLE + offset: 0x1A70 + parent: 0x0 + sampleBankId: 0 + symbol: se_ + +se_air_whoosh: + type: NAUDIO:V1:SAMPLE + offset: 0x1C90 + parent: 0x0 + sampleBankId: 0 + symbol: se_air_whoosh + +se_andross_grunt_1: + type: NAUDIO:V1:SAMPLE + offset: 0x2140 + parent: 0x0 + sampleBankId: 0 + symbol: se_andross_grunt_1 + +se_andross_grunt_2: + type: NAUDIO:V1:SAMPLE + offset: 0x2290 + parent: 0x0 + sampleBankId: 0 + symbol: se_andross_grunt_2 + +se_andross_laugh: + type: NAUDIO:V1:SAMPLE + offset: 0x2300 + parent: 0x0 + sampleBankId: 0 + symbol: se_andross_laugh + +se_andross_pain_grunt: + type: NAUDIO:V1:SAMPLE + offset: 0x21B0 + parent: 0x0 + sampleBankId: 0 + symbol: se_andross_pain_grunt + +se_andross_pain_grunt_2: + type: NAUDIO:V1:SAMPLE + offset: 0x2220 + parent: 0x0 + sampleBankId: 0 + symbol: se_andross_pain_grunt_2 + +se_andross_pain_grunt_3: + type: NAUDIO:V1:SAMPLE + offset: 0x2370 + parent: 0x0 + sampleBankId: 0 + symbol: se_andross_pain_grunt_3 + +se_andross_pain_scream: + type: NAUDIO:V1:SAMPLE + offset: 0x23E0 + parent: 0x0 + sampleBankId: 0 + symbol: se_andross_pain_scream + +se_animal_squeal: + type: NAUDIO:V1:SAMPLE + offset: 0x12C0 + parent: 0x0 + sampleBankId: 0 + symbol: se_animal_squeal + +se_bio_weapon_roar: + type: NAUDIO:V1:SAMPLE + offset: 0xDC0 + parent: 0x0 + sampleBankId: 0 + symbol: se_bio_weapon_roar + +se_bioweapon_roar: + type: NAUDIO:V1:SAMPLE + offset: 0x11E0 + parent: 0x0 + sampleBankId: 0 + symbol: se_bioweapon_roar + +se_bubbling: + type: NAUDIO:V1:SAMPLE + offset: 0x1530 + parent: 0x0 + sampleBankId: 0 + symbol: se_bubbling + +se_bubbling_water: + type: NAUDIO:V1:SAMPLE + offset: 0x2020 + parent: 0x0 + sampleBankId: 0 + symbol: se_bubbling_water + +se_digital_noise: + type: NAUDIO:V1:SAMPLE + offset: 0x20B0 + parent: 0x0 + sampleBankId: 0 + symbol: se_digital_noise + +se_ding: + type: NAUDIO:V1:SAMPLE + offset: 0x1F00 + parent: 0x0 + sampleBankId: 0 + symbol: se_ding + +se_doppler_jet: + type: NAUDIO:V1:SAMPLE + offset: 0x15C0 + parent: 0x0 + sampleBankId: 0 + symbol: se_doppler_jet + +se_electric_noise: + type: NAUDIO:V1:SAMPLE + offset: 0x17E0 + parent: 0x0 + sampleBankId: 0 + symbol: se_electric_noise + +se_electrical_burst: + type: NAUDIO:V1:SAMPLE + offset: 0x270 + parent: 0x0 + sampleBankId: 0 + symbol: se_electrical_burst + +se_electrical_pulse: + type: NAUDIO:V1:SAMPLE + offset: 0x1F90 + parent: 0x0 + sampleBankId: 0 + symbol: se_electrical_pulse + +se_enemy_engine: + type: NAUDIO:V1:SAMPLE + offset: 0xFC0 + parent: 0x0 + sampleBankId: 0 + symbol: se_enemy_engine + +se_enemy_laser: + type: NAUDIO:V1:SAMPLE + offset: 0x7B0 + parent: 0x0 + sampleBankId: 0 + symbol: se_enemy_laser + +se_enemy_laser_fire: + type: NAUDIO:V1:SAMPLE + offset: 0x1870 + parent: 0x0 + sampleBankId: 0 + symbol: se_enemy_laser_fire + +se_energy_pulse: + type: NAUDIO:V1:SAMPLE + offset: 0x13C0 + parent: 0x0 + sampleBankId: 0 + symbol: se_energy_pulse + +se_explosion: + type: NAUDIO:V1:SAMPLE + offset: 0xCA0 + parent: 0x0 + sampleBankId: 0 + symbol: se_explosion + +se_explosion_1: + type: NAUDIO:V1:SAMPLE + offset: 0x2E0 + parent: 0x0 + sampleBankId: 0 + symbol: se_explosion_1 + +se_explosion_low: + type: NAUDIO:V1:SAMPLE + offset: 0x920 + parent: 0x0 + sampleBankId: 0 + symbol: se_explosion_low + +se_explosion_low_boom: + type: NAUDIO:V1:SAMPLE + offset: 0xA00 + parent: 0x0 + sampleBankId: 0 + symbol: se_explosion_low_boom + +se_explosion_sharp: + type: NAUDIO:V1:SAMPLE + offset: 0x1450 + parent: 0x0 + sampleBankId: 0 + symbol: se_explosion_sharp + +se_feedback: + type: NAUDIO:V1:SAMPLE + offset: 0x16450 + parent: 0x16400 + sampleBankId: 3 + symbol: se_feedback + +se_good_luck: + type: NAUDIO:V1:SAMPLE + offset: 0x1D90 + parent: 0x0 + sampleBankId: 0 + symbol: se_good_luck + +se_gorgon_warp: + type: NAUDIO:V1:SAMPLE + offset: 0x18E0 + parent: 0x0 + sampleBankId: 0 + symbol: se_gorgon_warp + +se_heavy_impact: + type: NAUDIO:V1:SAMPLE + offset: 0x1970 + parent: 0x0 + sampleBankId: 0 + symbol: se_heavy_impact + +se_hovering_ship: + type: NAUDIO:V1:SAMPLE + offset: 0x1D00 + parent: 0x0 + sampleBankId: 0 + symbol: se_hovering_ship + +se_hum: + type: NAUDIO:V1:SAMPLE + offset: 0x1330 + parent: 0x0 + sampleBankId: 0 + symbol: se_hum + +se_hum_harsh: + type: NAUDIO:V1:SAMPLE + offset: 0x1050 + parent: 0x0 + sampleBankId: 0 + symbol: se_hum_harsh + +se_hyper_laser: + type: NAUDIO:V1:SAMPLE + offset: 0xBC0 + parent: 0x0 + sampleBankId: 0 + symbol: se_hyper_laser + +se_jet_engine: + type: NAUDIO:V1:SAMPLE + offset: 0x1B70 + parent: 0x0 + sampleBankId: 0 + symbol: se_jet_engine + +se_jet_engine_high_pitch: + type: NAUDIO:V1:SAMPLE + offset: 0x350 + parent: 0x0 + sampleBankId: 0 + symbol: se_jet_engine_high_pitch + +se_jet_engine_high_pitched: + type: NAUDIO:V1:SAMPLE + offset: 0x890 + parent: 0x0 + sampleBankId: 0 + symbol: se_jet_engine_high_pitched + +se_landmaster_treads: + type: NAUDIO:V1:SAMPLE + offset: 0x3E0 + parent: 0x0 + sampleBankId: 0 + symbol: se_landmaster_treads + +se_laser: + type: NAUDIO:V1:SAMPLE + offset: 0x1250 + parent: 0x0 + sampleBankId: 0 + symbol: se_laser + +se_laser_2: + type: NAUDIO:V1:SAMPLE + offset: 0x200 + parent: 0x0 + sampleBankId: 0 + symbol: se_laser_2 + +se_laser_blast: + type: NAUDIO:V1:SAMPLE + offset: 0xE30 + parent: 0x0 + sampleBankId: 0 + symbol: se_laser_blast + +se_laser_blast_high_pitch: + type: NAUDIO:V1:SAMPLE + offset: 0x990 + parent: 0x0 + sampleBankId: 0 + symbol: se_laser_blast_high_pitch + +se_laser_reflect: + type: NAUDIO:V1:SAMPLE + offset: 0x620 + parent: 0x0 + sampleBankId: 0 + symbol: se_laser_reflect + +se_laser_wave: + type: NAUDIO:V1:SAMPLE + offset: 0xEA0 + parent: 0x0 + sampleBankId: 0 + symbol: se_laser_wave + +se_mechanical_reposition: + type: NAUDIO:V1:SAMPLE + offset: 0x2450 + parent: 0x0 + sampleBankId: 0 + symbol: se_mechanical_reposition + +se_metal_chain: + type: NAUDIO:V1:SAMPLE + offset: 0x1E70 + parent: 0x0 + sampleBankId: 0 + symbol: se_metal_chain + +se_metal_clang: + type: NAUDIO:V1:SAMPLE + offset: 0x10E0 + parent: 0x0 + sampleBankId: 0 + symbol: se_metal_clang + +se_metal_scraping: + type: NAUDIO:V1:SAMPLE + offset: 0x1AE0 + parent: 0x0 + sampleBankId: 0 + symbol: se_metal_scraping + +se_metallic_thud: + type: NAUDIO:V1:SAMPLE + offset: 0x14C0 + parent: 0x0 + sampleBankId: 0 + symbol: se_metallic_thud + +se_missile_launch: + type: NAUDIO:V1:SAMPLE + offset: 0x500 + parent: 0x0 + sampleBankId: 0 + symbol: se_missile_launch + +se_radio_close: + type: NAUDIO:V1:SAMPLE + offset: 0x1150 + parent: 0x0 + sampleBankId: 0 + symbol: se_radio_close + +se_radio_open: + type: NAUDIO:V1:SAMPLE + offset: 0x38B0 + parent: 0x2F00 + sampleBankId: 1 + symbol: se_radio_open + +se_sand_noise: + type: NAUDIO:V1:SAMPLE + offset: 0x690 + parent: 0x0 + sampleBankId: 0 + symbol: se_sand_noise + +se_train_rolling: + type: NAUDIO:V1:SAMPLE + offset: 0x19E0 + parent: 0x0 + sampleBankId: 0 + symbol: se_train_rolling + +se_twin_laser: + type: NAUDIO:V1:SAMPLE + offset: 0xA70 + parent: 0x0 + sampleBankId: 0 + symbol: se_twin_laser + +se_unknown_1: + type: NAUDIO:V1:SAMPLE + offset: 0x720 + parent: 0x0 + sampleBankId: 0 + symbol: se_unknown_1 + +se_unknown_2: + type: NAUDIO:V1:SAMPLE + offset: 0xF30 + parent: 0x0 + sampleBankId: 0 + symbol: se_unknown_2 + +se_water_splash: + type: NAUDIO:V1:SAMPLE + offset: 0x1E00 + parent: 0x0 + sampleBankId: 0 + symbol: se_water_splash + +se_wind: + type: NAUDIO:V1:SAMPLE + offset: 0x1C00 + parent: 0x0 + sampleBankId: 0 + symbol: se_wind + +se_wind_noise: + type: NAUDIO:V1:SAMPLE + offset: 0x590 + parent: 0x0 + sampleBankId: 0 + symbol: se_wind_noise + +se_wing_movement: + type: NAUDIO:V1:SAMPLE + offset: 0x470 + parent: 0x0 + sampleBankId: 0 + symbol: se_wing_movement + +silent: + type: NAUDIO:V1:SAMPLE + offset: 0x10170 + parent: 0xF7C0 + sampleBankId: 2 + symbol: silent + +so_bill_dont_get_too_excited: + type: NAUDIO:V1:SAMPLE + offset: 0xCDF0 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_bill_dont_get_too_excited + +so_bill_here_we_go: + type: NAUDIO:V1:SAMPLE + offset: 0xCE10 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_bill_here_we_go + +so_bill_looks_like_you_could_use_some_help_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xCDB0 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_bill_looks_like_you_could_use_some_help_fox + +so_bill_watch_yourself_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xCE30 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_bill_watch_yourself_fox + +so_falco_andross_is_an_insane: + type: NAUDIO:V1:SAMPLE + offset: 0xCE90 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_falco_andross_is_an_insane + +so_falco_burned: + type: NAUDIO:V1:SAMPLE + offset: 0xCF70 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_falco_burned + +so_falco_fool: + type: NAUDIO:V1:SAMPLE + offset: 0xCEB0 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_falco_fool + +so_falco_good_riddance: + type: NAUDIO:V1:SAMPLE + offset: 0xCF30 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_falco_good_riddance + +so_falco_i_aint_your_buddy_go_away: + type: NAUDIO:V1:SAMPLE + offset: 0xCF10 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_falco_i_aint_your_buddy_go_away + +so_falco_i_almost_got: + type: NAUDIO:V1:SAMPLE + offset: 0xCF50 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_falco_i_almost_got + +so_falco_the_arwing_might_not_make_it: + type: NAUDIO:V1:SAMPLE + offset: 0xCCD0 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_falco_the_arwing_might_not_make_it + +so_fox_bill: + type: NAUDIO:V1:SAMPLE + offset: 0xCDD0 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_fox_bill + +so_fox_keep_an_eye_on_your_shield_gauge: + type: NAUDIO:V1:SAMPLE + offset: 0xCC20 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_fox_keep_an_eye_on_your_shield_gauge + +so_peppy_aim_for_the_arm: + type: NAUDIO:V1:SAMPLE + offset: 0xCEF0 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_peppy_aim_for_the_arm + +so_peppy_dont_fly_too_low_your_ship_cant_take_it: + type: NAUDIO:V1:SAMPLE + offset: 0xCFD0 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_peppy_dont_fly_too_low_your_ship_cant_take_it + +so_peppy_maybe_its_an_arm: + type: NAUDIO:V1:SAMPLE + offset: 0xCED0 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_peppy_maybe_its_an_arm + +so_peppy_shoot_the_rocks: + type: NAUDIO:V1:SAMPLE + offset: 0xCD10 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_peppy_shoot_the_rocks + +so_peppy_theyre_attacking_in_groups: + type: NAUDIO:V1:SAMPLE + offset: 0xCE50 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_peppy_theyre_attacking_in_groups + +so_peppy_this_is_the_enemy_bio_weapon: + type: NAUDIO:V1:SAMPLE + offset: 0xCE70 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_peppy_this_is_the_enemy_bio_weapon + +so_slippy_i_cant_take_it_anymore: + type: NAUDIO:V1:SAMPLE + offset: 0xCFB0 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_slippy_i_cant_take_it_anymore + +so_slippy_its_now_at_8000: + type: NAUDIO:V1:SAMPLE + offset: 0xCD70 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_slippy_its_now_at_8000 + +so_slippy_its_too_hot: + type: NAUDIO:V1:SAMPLE + offset: 0xCF90 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_slippy_its_too_hot + +so_slippy_oh_no: + type: NAUDIO:V1:SAMPLE + offset: 0xCD90 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_slippy_oh_no + +so_slippy_temperature_is_6000_and_climbing: + type: NAUDIO:V1:SAMPLE + offset: 0xCD50 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_slippy_temperature_is_6000_and_climbing + +so_slippy_this_baby_can_take_temperatures_of_up_to_9000_degrees: + type: NAUDIO:V1:SAMPLE + offset: 0xCD30 + parent: 0xCA20 + sampleBankId: 2 + symbol: so_slippy_this_baby_can_take_temperatures_of_up_to_9000_degrees + +sx_bill_back_me_up: + type: NAUDIO:V1:SAMPLE + offset: 0x7970 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_bill_back_me_up + +sx_bill_im_gonna_open_the_gate: + type: NAUDIO:V1:SAMPLE + offset: 0x7950 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_bill_im_gonna_open_the_gate + +sx_bill_im_here_to_help: + type: NAUDIO:V1:SAMPLE + offset: 0x79F0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_bill_im_here_to_help + +sx_bill_of_course: + type: NAUDIO:V1:SAMPLE + offset: 0x79D0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_bill_of_course + +sx_falco_destroy_what: + type: NAUDIO:V1:SAMPLE + offset: 0x7BF0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_destroy_what + +sx_falco_enemy_group_behind_us: + type: NAUDIO:V1:SAMPLE + offset: 0x7750 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_enemy_group_behind_us + +sx_falco_fast: + type: NAUDIO:V1:SAMPLE + offset: 0x7790 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_fast + +sx_falco_fox_look_behind_you: + type: NAUDIO:V1:SAMPLE + offset: 0x7BB0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_fox_look_behind_you + +sx_falco_fun: + type: NAUDIO:V1:SAMPLE + offset: 0x7730 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_fun + +sx_falco_hes_crazy: + type: NAUDIO:V1:SAMPLE + offset: 0x7C10 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_hes_crazy + +sx_falco_hurry_up_or_youre_toast: + type: NAUDIO:V1:SAMPLE + offset: 0x7A90 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_hurry_up_or_youre_toast + +sx_falco_i_cant_wait_to_thsee_this_secret_weapon: + type: NAUDIO:V1:SAMPLE + offset: 0x78F0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_i_cant_wait_to_thsee_this_secret_weapon + +sx_falco_i_found_the_gate: + type: NAUDIO:V1:SAMPLE + offset: 0x7910 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_i_found_the_gate + +sx_falco_is_that: + type: NAUDIO:V1:SAMPLE + offset: 0x7870 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_is_that + +sx_falco_its_all_gone: + type: NAUDIO:V1:SAMPLE + offset: 0x7810 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_its_all_gone + +sx_falco_just_one_more: + type: NAUDIO:V1:SAMPLE + offset: 0x7EB0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_just_one_more + +sx_falco_lets_have_a_little: + type: NAUDIO:V1:SAMPLE + offset: 0x7710 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_lets_have_a_little + +sx_falco_looks_like_a_warp: + type: NAUDIO:V1:SAMPLE + offset: 0x7930 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_looks_like_a_warp + +sx_falco_man_theyre: + type: NAUDIO:V1:SAMPLE + offset: 0x7770 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_man_theyre + +sx_falco_slippy_can_be_such_a_headache: + type: NAUDIO:V1:SAMPLE + offset: 0x7E10 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_slippy_can_be_such_a_headache + +sx_falco_some: + type: NAUDIO:V1:SAMPLE + offset: 0x7A30 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_some + +sx_falco_somebody_beat_us_here: + type: NAUDIO:V1:SAMPLE + offset: 0x77F0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_somebody_beat_us_here + +sx_falco_the_heck: + type: NAUDIO:V1:SAMPLE + offset: 0x7850 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_the_heck + +sx_falco_thins_not_right_here: + type: NAUDIO:V1:SAMPLE + offset: 0x7A50 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_thins_not_right_here + +sx_falco_what: + type: NAUDIO:V1:SAMPLE + offset: 0x7830 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_what + +sx_falco_what_the_heck: + type: NAUDIO:V1:SAMPLE + offset: 0x7B90 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_what_the_heck + +sx_falco_who_took_this_base_out: + type: NAUDIO:V1:SAMPLE + offset: 0x7A70 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_who_took_this_base_out + +sx_falco_yeah: + type: NAUDIO:V1:SAMPLE + offset: 0x7E70 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_falco_yeah + +sx_fox_bill: + type: NAUDIO:V1:SAMPLE + offset: 0x7990 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_fox_bill + +sx_fox_can_you_confirm_slippys_location: + type: NAUDIO:V1:SAMPLE + offset: 0x7DD0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_fox_can_you_confirm_slippys_location + +sx_fox_huh: + type: NAUDIO:V1:SAMPLE + offset: 0x126D0 + parent: 0x12400 + sampleBankId: 2 + symbol: sx_fox_huh + +sx_fox_is_everything_okay: + type: NAUDIO:V1:SAMPLE + offset: 0x7EF0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_fox_is_everything_okay + +sx_fox_lets_take_out_that_weapon_boys: + type: NAUDIO:V1:SAMPLE + offset: 0x7660 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_fox_lets_take_out_that_weapon_boys + +sx_fox_rob: + type: NAUDIO:V1:SAMPLE + offset: 0x7DB0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_fox_rob + +sx_fox_slippy: + type: NAUDIO:V1:SAMPLE + offset: 0x7ED0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_fox_slippy + +sx_fox_so_this_is_the_secret_weapon: + type: NAUDIO:V1:SAMPLE + offset: 0x7BD0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_fox_so_this_is_the_secret_weapon + +sx_fox_what: + type: NAUDIO:V1:SAMPLE + offset: 0x126F0 + parent: 0x12400 + sampleBankId: 2 + symbol: sx_fox_what + +sx_fox_whats_he_saying: + type: NAUDIO:V1:SAMPLE + offset: 0x7CF0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_fox_whats_he_saying + +sx_fox_youre_okay: + type: NAUDIO:V1:SAMPLE + offset: 0x79B0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_fox_youre_okay + +sx_peppy_ears_are_still_ringing: + type: NAUDIO:V1:SAMPLE + offset: 0x78B0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_peppy_ears_are_still_ringing + +sx_peppy_i_got_tagged_my: + type: NAUDIO:V1:SAMPLE + offset: 0x7890 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_peppy_i_got_tagged_my + +sx_peppy_ill_attack_from_the_outside: + type: NAUDIO:V1:SAMPLE + offset: 0x7AB0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_peppy_ill_attack_from_the_outside + +sx_peppy_im_going_ahead_back_me_up_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x7B50 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_peppy_im_going_ahead_back_me_up_fox + +sx_peppy_looks_like_hes_on_titania: + type: NAUDIO:V1:SAMPLE + offset: 0x7DF0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_peppy_looks_like_hes_on_titania + +sx_peppy_theyre_everywhere: + type: NAUDIO:V1:SAMPLE + offset: 0x7B10 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_peppy_theyre_everywhere + +sx_peppy_were_getting_close_to_the_base: + type: NAUDIO:V1:SAMPLE + offset: 0x77D0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_peppy_were_getting_close_to_the_base + +sx_peppy_where_is_the_secret_weapon: + type: NAUDIO:V1:SAMPLE + offset: 0x7B30 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_peppy_where_is_the_secret_weapon + +sx_rob_coming_from_titania: + type: NAUDIO:V1:SAMPLE + offset: 0x7E50 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_rob_coming_from_titania + +sx_rob_distress_signal: + type: NAUDIO:V1:SAMPLE + offset: 0x7E30 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_rob_distress_signal + +sx_slippy_dead_ahead: + type: NAUDIO:V1:SAMPLE + offset: 0x7AF0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_slippy_dead_ahead + +sx_slippy_dont_forget_me: + type: NAUDIO:V1:SAMPLE + offset: 0x13D10 + parent: 0x134A0 + sampleBankId: 2 + symbol: sx_slippy_dont_forget_me + +sx_slippy_interceptor_system: + type: NAUDIO:V1:SAMPLE + offset: 0x7AD0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_slippy_interceptor_system + +sx_slippy_let_me_handle_this: + type: NAUDIO:V1:SAMPLE + offset: 0x7C30 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_slippy_let_me_handle_this + +sx_slippy_yeah_yeah_no_problem: + type: NAUDIO:V1:SAMPLE + offset: 0x7F10 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_slippy_yeah_yeah_no_problem + +sx_spyborg_destroy: + type: NAUDIO:V1:SAMPLE + offset: 0x7C50 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_spyborg_destroy + +sx_spyborg_i_must_be_complete: + type: NAUDIO:V1:SAMPLE + offset: 0x7D90 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_spyborg_i_must_be_complete + +sx_spyborg_i_will_terminate_all_enemies: + type: NAUDIO:V1:SAMPLE + offset: 0x7C90 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_spyborg_i_will_terminate_all_enemies + +sx_spyborg_is_clear: + type: NAUDIO:V1:SAMPLE + offset: 0x7D50 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_spyborg_is_clear + +sx_spyborg_the: + type: NAUDIO:V1:SAMPLE + offset: 0x7D10 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_spyborg_the + +sx_spyborg_view: + type: NAUDIO:V1:SAMPLE + offset: 0x7D30 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_spyborg_view + +sx_spyborg_where_is_the_creator: + type: NAUDIO:V1:SAMPLE + offset: 0x7CD0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_spyborg_where_is_the_creator + +sx_spyborg_where_is_the_enemy: + type: NAUDIO:V1:SAMPLE + offset: 0x7D70 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_spyborg_where_is_the_enemy + +sx_spyborg_you_are_an_enemy: + type: NAUDIO:V1:SAMPLE + offset: 0x7CB0 + parent: 0x7460 + sampleBankId: 2 + symbol: sx_spyborg_you_are_an_enemy + +sy_falco_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xE190 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_falco_fox + +sy_falco_is_that_the_best_you_can_do: + type: NAUDIO:V1:SAMPLE + offset: 0xE1F0 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_falco_is_that_the_best_you_can_do + +sy_falco_ive_got_everything_above: + type: NAUDIO:V1:SAMPLE + offset: 0xE270 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_falco_ive_got_everything_above + +sy_falco_somebodys_gonna_pay_for_all_this: + type: NAUDIO:V1:SAMPLE + offset: 0xE0F0 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_falco_somebodys_gonna_pay_for_all_this + +sy_falco_take_em_down_with_one_shot: + type: NAUDIO:V1:SAMPLE + offset: 0xE350 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_falco_take_em_down_with_one_shot + +sy_falco_youre_supposed_to_shoot_em_all: + type: NAUDIO:V1:SAMPLE + offset: 0xE1B0 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_falco_youre_supposed_to_shoot_em_all + +sy_fox_lets_back_up_the_squadron: + type: NAUDIO:V1:SAMPLE + offset: 0xE040 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_fox_lets_back_up_the_squadron + +sy_fox_report_in: + type: NAUDIO:V1:SAMPLE + offset: 0xE5D0 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_fox_report_in + +sy_fox_were_headin_for_aquas: + type: NAUDIO:V1:SAMPLE + offset: 0xE5B0 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_fox_were_headin_for_aquas + +sy_peppy_dont_let_any_of_them_through: + type: NAUDIO:V1:SAMPLE + offset: 0xE110 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_peppy_dont_let_any_of_them_through + +sy_peppy_good_job_keep_up_the_good_work: + type: NAUDIO:V1:SAMPLE + offset: 0xE470 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_peppy_good_job_keep_up_the_good_work + +sy_peppy_good_job_keep_up_the_pace: + type: NAUDIO:V1:SAMPLE + offset: 0xE1D0 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_peppy_good_job_keep_up_the_pace + +sy_peppy_hold_em_theyre_trying_to_get_through: + type: NAUDIO:V1:SAMPLE + offset: 0xE170 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_peppy_hold_em_theyre_trying_to_get_through + +sy_peppy_ill_take_care_of_everything_below: + type: NAUDIO:V1:SAMPLE + offset: 0xE250 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_peppy_ill_take_care_of_everything_below + +sy_peppy_surprise_attack_coming_from_above: + type: NAUDIO:V1:SAMPLE + offset: 0xE230 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_peppy_surprise_attack_coming_from_above + +sy_peppy_youre_becoming_a_better_pilot: + type: NAUDIO:V1:SAMPLE + offset: 0xE210 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_peppy_youre_becoming_a_better_pilot + +sy_shogun_cocky_little_freaks: + type: NAUDIO:V1:SAMPLE + offset: 0xE570 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_shogun_cocky_little_freaks + +sy_shogun_death_scream: + type: NAUDIO:V1:SAMPLE + offset: 0xE590 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_shogun_death_scream + +sy_shogun_dont_party_just_yet: + type: NAUDIO:V1:SAMPLE + offset: 0xE490 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_shogun_dont_party_just_yet + +sy_shogun_ill_take_you_guys_out_from_the_ship: + type: NAUDIO:V1:SAMPLE + offset: 0xE550 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_shogun_ill_take_you_guys_out_from_the_ship + +sy_shogun_im_coming_for_ya: + type: NAUDIO:V1:SAMPLE + offset: 0xE530 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_shogun_im_coming_for_ya + +sy_shogun_is_that_it: + type: NAUDIO:V1:SAMPLE + offset: 0xE510 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_shogun_is_that_it + +sy_shogun_its_time_to_try_our_new_weapon: + type: NAUDIO:V1:SAMPLE + offset: 0xE4D0 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_shogun_its_time_to_try_our_new_weapon + +sy_shogun_whats_wrong: + type: NAUDIO:V1:SAMPLE + offset: 0xE4F0 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_shogun_whats_wrong + +sy_slippy_a_hah: + type: NAUDIO:V1:SAMPLE + offset: 0xE290 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_slippy_a_hah + +sy_slippy_escaping: + type: NAUDIO:V1:SAMPLE + offset: 0xE2D0 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_slippy_escaping + +sy_slippy_hey: + type: NAUDIO:V1:SAMPLE + offset: 0xE310 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_slippy_hey + +sy_slippy_i_dont_see_anything: + type: NAUDIO:V1:SAMPLE + offset: 0xE150 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_slippy_i_dont_see_anything + +sy_slippy_i_dont_think_so: + type: NAUDIO:V1:SAMPLE + offset: 0xE2F0 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_slippy_i_dont_think_so + +sy_slippy_leave_me_alone: + type: NAUDIO:V1:SAMPLE + offset: 0xE330 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_slippy_leave_me_alone + +sy_slippy_looks_different: + type: NAUDIO:V1:SAMPLE + offset: 0xE3B0 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_slippy_looks_different + +sy_slippy_somethings_up_ahead: + type: NAUDIO:V1:SAMPLE + offset: 0xE390 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_slippy_somethings_up_ahead + +sy_slippy_somethings_wrong: + type: NAUDIO:V1:SAMPLE + offset: 0xE130 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_slippy_somethings_wrong + +sy_slippy_these_guys_are: + type: NAUDIO:V1:SAMPLE + offset: 0xE410 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_slippy_these_guys_are + +sy_slippy_thought_you_could_hide_from_me_eh: + type: NAUDIO:V1:SAMPLE + offset: 0xE2B0 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_slippy_thought_you_could_hide_from_me_eh + +sy_slippy_tough: + type: NAUDIO:V1:SAMPLE + offset: 0xE430 + parent: 0xDE40 + sampleBankId: 2 + symbol: sy_slippy_tough + +sz_falco_cant_you_go_bother_someone_else: + type: NAUDIO:V1:SAMPLE + offset: 0xFCF0 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_falco_cant_you_go_bother_someone_else + +sz_falco_dang_now_theyve: + type: NAUDIO:V1:SAMPLE + offset: 0xFF30 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_falco_dang_now_theyve + +sz_falco_done_it: + type: NAUDIO:V1:SAMPLE + offset: 0xFF50 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_falco_done_it + +sz_falco_im_heading_for_the_missile_now: + type: NAUDIO:V1:SAMPLE + offset: 0xFAB0 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_falco_im_heading_for_the_missile_now + +sz_falco_katt: + type: NAUDIO:V1:SAMPLE + offset: 0xFCD0 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_falco_katt + +sz_falco_nice_welcome: + type: NAUDIO:V1:SAMPLE + offset: 0xFA90 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_falco_nice_welcome + +sz_falco_one_missile_down: + type: NAUDIO:V1:SAMPLE + offset: 0xFE50 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_falco_one_missile_down + +sz_falco_that_was_a_close_call: + type: NAUDIO:V1:SAMPLE + offset: 0xFFF0 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_falco_that_was_a_close_call + +sz_fox_here_it_comes: + type: NAUDIO:V1:SAMPLE + offset: 0xFB50 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_fox_here_it_comes + +sz_fox_is_everything_okay: + type: NAUDIO:V1:SAMPLE + offset: 0xFEF0 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_fox_is_everything_okay + +sz_fox_rob: + type: NAUDIO:V1:SAMPLE + offset: 0xFED0 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_fox_rob + +sz_fox_well_gladly_take_this_one: + type: NAUDIO:V1:SAMPLE + offset: 0xFA70 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_fox_well_gladly_take_this_one + +sz_katt_are_you_gonna_hog_all_the_fun: + type: NAUDIO:V1:SAMPLE + offset: 0xFCB0 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_katt_are_you_gonna_hog_all_the_fun + +sz_katt_falco: + type: NAUDIO:V1:SAMPLE + offset: 0xFDD0 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_katt_falco + +sz_katt_good_luck_little_man: + type: NAUDIO:V1:SAMPLE + offset: 0xFE10 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_katt_good_luck_little_man + +sz_katt_i_took_care_of_a_missile_for_you: + type: NAUDIO:V1:SAMPLE + offset: 0xFEB0 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_katt_i_took_care_of_a_missile_for_you + +sz_katt_let_me_help_you_out: + type: NAUDIO:V1:SAMPLE + offset: 0xFD10 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_katt_let_me_help_you_out + +sz_katt_too_bad_little_man: + type: NAUDIO:V1:SAMPLE + offset: 0xFE30 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_katt_too_bad_little_man + +sz_katt_you_owe_me: + type: NAUDIO:V1:SAMPLE + offset: 0xFDB0 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_katt_you_owe_me + +sz_katt_youre_on_your_own: + type: NAUDIO:V1:SAMPLE + offset: 0xFDF0 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_katt_youre_on_your_own + +sz_peppy_im_goin_for_the_missile: + type: NAUDIO:V1:SAMPLE + offset: 0xFAD0 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_peppy_im_goin_for_the_missile + +sz_peppy_it_could_be_difficult_to_attack_venom: + type: NAUDIO:V1:SAMPLE + offset: 0xFF70 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_peppy_it_could_be_difficult_to_attack_venom + +sz_peppy_one_missile_destroyed: + type: NAUDIO:V1:SAMPLE + offset: 0xFE70 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_peppy_one_missile_destroyed + +sz_peppy_weve_got_the_bad_guys_on_the_run: + type: NAUDIO:V1:SAMPLE + offset: 0x10010 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_peppy_weve_got_the_bad_guys_on_the_run + +sz_rob_20: + type: NAUDIO:V1:SAMPLE + offset: 0xFC10 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_rob_20 + +sz_rob_50: + type: NAUDIO:V1:SAMPLE + offset: 0xFBB0 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_rob_50 + +sz_rob_damage_to_rear_left_section_of_the_ship: + type: NAUDIO:V1:SAMPLE + offset: 0xFF10 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_rob_damage_to_rear_left_section_of_the_ship + +sz_rob_distance: + type: NAUDIO:V1:SAMPLE + offset: 0xFB90 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_rob_distance + +sz_rob_distance_10: + type: NAUDIO:V1:SAMPLE + offset: 0xFC30 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_rob_distance_10 + +sz_rob_enemy_approaching_from_the_left: + type: NAUDIO:V1:SAMPLE + offset: 0xF9C0 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_rob_enemy_approaching_from_the_left + +sz_rob_great_fox_is_okay: + type: NAUDIO:V1:SAMPLE + offset: 0xFFD0 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_rob_great_fox_is_okay + +sz_rob_missile_approaching: + type: NAUDIO:V1:SAMPLE + offset: 0xFB70 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_rob_missile_approaching + +sz_rob_missile_one_is_heading_for_great_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xFB30 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_rob_missile_one_is_heading_for_great_fox + +sz_rob_missiles_four_five_and_six_approaching: + type: NAUDIO:V1:SAMPLE + offset: 0xFC90 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_rob_missiles_four_five_and_six_approaching + +sz_rob_missiles_two_and_three_approaching: + type: NAUDIO:V1:SAMPLE + offset: 0xFC70 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_rob_missiles_two_and_three_approaching + +sz_rob_six_missiles_coming_from_the_left: + type: NAUDIO:V1:SAMPLE + offset: 0xFB10 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_rob_six_missiles_coming_from_the_left + +sz_rob_unable_to_evade: + type: NAUDIO:V1:SAMPLE + offset: 0xFC50 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_rob_unable_to_evade + +sz_slippy_dog: + type: NAUDIO:V1:SAMPLE + offset: 0xFF90 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_slippy_dog + +sz_slippy_dont_worry: + type: NAUDIO:V1:SAMPLE + offset: 0x10030 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_slippy_dont_worry + +sz_slippy_gone_it: + type: NAUDIO:V1:SAMPLE + offset: 0xFFB0 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_slippy_gone_it + +sz_slippy_im_heading_for_the_missile_now: + type: NAUDIO:V1:SAMPLE + offset: 0xFAF0 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_slippy_im_heading_for_the_missile_now + +sz_slippy_scratch_one_missile: + type: NAUDIO:V1:SAMPLE + offset: 0xFE90 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_slippy_scratch_one_missile + +sz_slippy_slippys_here: + type: NAUDIO:V1:SAMPLE + offset: 0x10050 + parent: 0xF7C0 + sampleBankId: 2 + symbol: sz_slippy_slippys_here + +ti_falco_a_magnetic_storm: + type: NAUDIO:V1:SAMPLE + offset: 0x6970 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_falco_a_magnetic_storm + +ti_falco_down_slippy_just_hold_on: + type: NAUDIO:V1:SAMPLE + offset: 0x6C70 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_falco_down_slippy_just_hold_on + +ti_falco_enemy_fighters_coming_at_ya_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x6A90 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_falco_enemy_fighters_coming_at_ya_fox + +ti_falco_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x6A30 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_falco_fox + +ti_falco_he_can_sure_be_a_pain_in_the_neck: + type: NAUDIO:V1:SAMPLE + offset: 0x69D0 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_falco_he_can_sure_be_a_pain_in_the_neck + +ti_falco_i_think_you_look_better_in_a_tank: + type: NAUDIO:V1:SAMPLE + offset: 0x69B0 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_falco_i_think_you_look_better_in_a_tank + +ti_falco_ill_be_there_soon: + type: NAUDIO:V1:SAMPLE + offset: 0x6B70 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_falco_ill_be_there_soon + +ti_falco_ill_pass: + type: NAUDIO:V1:SAMPLE + offset: 0x6A10 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_falco_ill_pass + +ti_falco_let_me_get_a_piece_of_that_action_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x6C10 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_falco_let_me_get_a_piece_of_that_action_fox + +ti_falco_pipe: + type: NAUDIO:V1:SAMPLE + offset: 0x6C50 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_falco_pipe + +ti_falco_slippy_what_are_ya_doin_hurry_up: + type: NAUDIO:V1:SAMPLE + offset: 0x6C90 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_falco_slippy_what_are_ya_doin_hurry_up + +ti_falco_well_search_here: + type: NAUDIO:V1:SAMPLE + offset: 0x6990 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_falco_well_search_here + +ti_falco_were_always_savin_your_hide_slip: + type: NAUDIO:V1:SAMPLE + offset: 0x6D10 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_falco_were_always_savin_your_hide_slip + +ti_falco_you_sure_you_can_handle_it_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x6CD0 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_falco_you_sure_you_can_handle_it_fox + +ti_fox_deploy_the_landmaster: + type: NAUDIO:V1:SAMPLE + offset: 0x6E10 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_fox_deploy_the_landmaster + +ti_fox_give_me_slippys_location_rob: + type: NAUDIO:V1:SAMPLE + offset: 0x6880 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_fox_give_me_slippys_location_rob + +ti_fox_is_that_you_slippy: + type: NAUDIO:V1:SAMPLE + offset: 0x6B50 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_fox_is_that_you_slippy + +ti_fox_slippy: + type: NAUDIO:V1:SAMPLE + offset: 0x141D0 + parent: 0x134A0 + sampleBankId: 2 + symbol: ti_fox_slippy + +ti_fox_well_head_to_venom: + type: NAUDIO:V1:SAMPLE + offset: 0x6D70 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_fox_well_head_to_venom + +ti_fox_when_we_get_back: + type: NAUDIO:V1:SAMPLE + offset: 0x6D50 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_fox_when_we_get_back + +ti_fox_why_dont_you_come_down_here_falco: + type: NAUDIO:V1:SAMPLE + offset: 0x69F0 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_fox_why_dont_you_come_down_here_falco + +ti_peppy_are_ya_okay: + type: NAUDIO:V1:SAMPLE + offset: 0x6AB0 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_peppy_are_ya_okay + +ti_peppy_dont_be_dead_slip: + type: NAUDIO:V1:SAMPLE + offset: 0x6AD0 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_peppy_dont_be_dead_slip + +ti_peppy_dont_go_to_fast_falco: + type: NAUDIO:V1:SAMPLE + offset: 0x6A50 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_peppy_dont_go_to_fast_falco + +ti_peppy_go_for_the_chest: + type: NAUDIO:V1:SAMPLE + offset: 0x6B90 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_peppy_go_for_the_chest + +ti_peppy_hold_together_its_just_a_bit_further: + type: NAUDIO:V1:SAMPLE + offset: 0x6B30 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_peppy_hold_together_its_just_a_bit_further + +ti_peppy_im_sure_hes_learned_his_lesson: + type: NAUDIO:V1:SAMPLE + offset: 0x6D30 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_peppy_im_sure_hes_learned_his_lesson + +ti_peppy_incoming: + type: NAUDIO:V1:SAMPLE + offset: 0x6AF0 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_peppy_incoming + +ti_peppy_take_out_his_arms_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x6C30 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_peppy_take_out_his_arms_fox + +ti_peppy_theres_rocky_terrain_dead_ahead: + type: NAUDIO:V1:SAMPLE + offset: 0x6950 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_peppy_theres_rocky_terrain_dead_ahead + +ti_peppy_ya_okay: + type: NAUDIO:V1:SAMPLE + offset: 0x6B10 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_peppy_ya_okay + +ti_rob_life_form_indicated_at_12_o_clock: + type: NAUDIO:V1:SAMPLE + offset: 0x6930 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_rob_life_form_indicated_at_12_o_clock + +ti_slippy_do_something: + type: NAUDIO:V1:SAMPLE + offset: 0x6BF0 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_slippy_do_something + +ti_slippy_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x6DD0 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_slippy_fox + +ti_slippy_i_knew_youd_come_help_me: + type: NAUDIO:V1:SAMPLE + offset: 0x6DF0 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_slippy_i_knew_youd_come_help_me + +ti_slippy_i_made_it: + type: NAUDIO:V1:SAMPLE + offset: 0x6D90 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_slippy_i_made_it + +ti_slippy_i_thought_i_was_a_goner: + type: NAUDIO:V1:SAMPLE + offset: 0x6CF0 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_slippy_i_thought_i_was_a_goner + +ti_slippy_ill_analyze_right_away: + type: NAUDIO:V1:SAMPLE + offset: 0x6DB0 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_slippy_ill_analyze_right_away + +ti_slippy_its_impossible_this_way: + type: NAUDIO:V1:SAMPLE + offset: 0x6CB0 + parent: 0x6680 + sampleBankId: 2 + symbol: ti_slippy_its_impossible_this_way + +tm_rob_64: + type: NAUDIO:V1:SAMPLE + offset: 0x14770 + parent: 0x134A0 + sampleBankId: 2 + symbol: tm_rob_64 + +tm_rob_good: + type: NAUDIO:V1:SAMPLE + offset: 0x14710 + parent: 0x134A0 + sampleBankId: 2 + symbol: tm_rob_good + +tm_rob_great: + type: NAUDIO:V1:SAMPLE + offset: 0x147B0 + parent: 0x134A0 + sampleBankId: 2 + symbol: tm_rob_great + +tm_rob_job: + type: NAUDIO:V1:SAMPLE + offset: 0x14730 + parent: 0x134A0 + sampleBankId: 2 + symbol: tm_rob_job + +tm_rob_keep_up_the_good_work: + type: NAUDIO:V1:SAMPLE + offset: 0x14790 + parent: 0x134A0 + sampleBankId: 2 + symbol: tm_rob_keep_up_the_good_work + +tm_rob_lets_practice: + type: NAUDIO:V1:SAMPLE + offset: 0x146D0 + parent: 0x134A0 + sampleBankId: 2 + symbol: tm_rob_lets_practice + +tm_rob_now_lets_get_back_to_the_game: + type: NAUDIO:V1:SAMPLE + offset: 0x147D0 + parent: 0x134A0 + sampleBankId: 2 + symbol: tm_rob_now_lets_get_back_to_the_game + +tm_rob_the_basics: + type: NAUDIO:V1:SAMPLE + offset: 0x146F0 + parent: 0x134A0 + sampleBankId: 2 + symbol: tm_rob_the_basics + +tm_rob_this_is_rob: + type: NAUDIO:V1:SAMPLE + offset: 0x14750 + parent: 0x134A0 + sampleBankId: 2 + symbol: tm_rob_this_is_rob + +tm_rob_welcome_to_training_mode: + type: NAUDIO:V1:SAMPLE + offset: 0x146B0 + parent: 0x134A0 + sampleBankId: 2 + symbol: tm_rob_welcome_to_training_mode + +unused_andross_hurry_fox_im_waiting_for_you: + type: NAUDIO:V1:SAMPLE + offset: 0x12D50 + parent: 0x12400 + sampleBankId: 2 + symbol: unused_andross_hurry_fox_im_waiting_for_you + +unused_fox_are_you_okay: + type: NAUDIO:V1:SAMPLE + offset: 0x138B0 + parent: 0x134A0 + sampleBankId: 2 + symbol: unused_fox_are_you_okay + +unused_fox_falco: + type: NAUDIO:V1:SAMPLE + offset: 0x13DD0 + parent: 0x134A0 + sampleBankId: 2 + symbol: unused_fox_falco + +unused_fox_peppy: + type: NAUDIO:V1:SAMPLE + offset: 0x13DB0 + parent: 0x134A0 + sampleBankId: 2 + symbol: unused_fox_peppy + +unused_peppy_dont_be_doing_anything_foolish: + type: NAUDIO:V1:SAMPLE + offset: 0x49B0 + parent: 0x4520 + sampleBankId: 2 + symbol: unused_peppy_dont_be_doing_anything_foolish + +unused_peppy_enemy_behind_descend: + type: NAUDIO:V1:SAMPLE + offset: 0xF290 + parent: 0xEBA0 + sampleBankId: 2 + symbol: unused_peppy_enemy_behind_descend + +unused_peppy_for_a_u_turn_press_down_and_c_down: + type: NAUDIO:V1:SAMPLE + offset: 0x14130 + parent: 0x134A0 + sampleBankId: 2 + symbol: unused_peppy_for_a_u_turn_press_down_and_c_down + +unused_peppy_hold_a_to_lock_on_to_the_enemy: + type: NAUDIO:V1:SAMPLE + offset: 0x140B0 + parent: 0x134A0 + sampleBankId: 2 + symbol: unused_peppy_hold_a_to_lock_on_to_the_enemy + +unused_peppy_incoming: + type: NAUDIO:V1:SAMPLE + offset: 0x13EB0 + parent: 0x134A0 + sampleBankId: 2 + symbol: unused_peppy_incoming + +unused_peppy_press_b_to_bomb: + type: NAUDIO:V1:SAMPLE + offset: 0x14150 + parent: 0x134A0 + sampleBankId: 2 + symbol: unused_peppy_press_b_to_bomb + +unused_peppy_press_c_down_to_brake: + type: NAUDIO:V1:SAMPLE + offset: 0x14190 + parent: 0x134A0 + sampleBankId: 2 + symbol: unused_peppy_press_c_down_to_brake + +unused_peppy_press_c_left_to_boost: + type: NAUDIO:V1:SAMPLE + offset: 0x140F0 + parent: 0x134A0 + sampleBankId: 2 + symbol: unused_peppy_press_c_left_to_boost + +unused_peppy_press_down_and_c_left_to_do_a_sommersault: + type: NAUDIO:V1:SAMPLE + offset: 0x14110 + parent: 0x134A0 + sampleBankId: 2 + symbol: unused_peppy_press_down_and_c_left_to_do_a_sommersault + +unused_peppy_to_get_rid_of_the_aim_pause_and_press_r: + type: NAUDIO:V1:SAMPLE + offset: 0x140D0 + parent: 0x134A0 + sampleBankId: 2 + symbol: unused_peppy_to_get_rid_of_the_aim_pause_and_press_r + +unused_peppy_to_hover_press_z_and_r: + type: NAUDIO:V1:SAMPLE + offset: 0x141B0 + parent: 0x134A0 + sampleBankId: 2 + symbol: unused_peppy_to_hover_press_z_and_r + +unused_rob_everything: + type: NAUDIO:V1:SAMPLE + offset: 0x13FF0 + parent: 0x134A0 + sampleBankId: 2 + symbol: unused_rob_everything + +unused_rob_okay: + type: NAUDIO:V1:SAMPLE + offset: 0x14010 + parent: 0x134A0 + sampleBankId: 2 + symbol: unused_rob_okay + +unused_slippy_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x13D90 + parent: 0x134A0 + sampleBankId: 2 + symbol: unused_slippy_fox + +unused_slippy_great: + type: NAUDIO:V1:SAMPLE + offset: 0x13D70 + parent: 0x134A0 + sampleBankId: 2 + symbol: unused_slippy_great + +unused_slippy_ha_ha: + type: NAUDIO:V1:SAMPLE + offset: 0x13E30 + parent: 0x134A0 + sampleBankId: 2 + symbol: unused_slippy_ha_ha + +unused_slippy_im_beaten_up_pretty_bad: + type: NAUDIO:V1:SAMPLE + offset: 0xA890 + parent: 0xA4E0 + sampleBankId: 2 + symbol: unused_slippy_im_beaten_up_pretty_bad + +unused_slippy_somethings_not_right: + type: NAUDIO:V1:SAMPLE + offset: 0x77B0 + parent: 0x7460 + sampleBankId: 2 + symbol: unused_slippy_somethings_not_right + +unused_slippy_stop_me: + type: NAUDIO:V1:SAMPLE + offset: 0x13E70 + parent: 0x134A0 + sampleBankId: 2 + symbol: unused_slippy_stop_me + +unused_slippy_try_and: + type: NAUDIO:V1:SAMPLE + offset: 0x13E50 + parent: 0x134A0 + sampleBankId: 2 + symbol: unused_slippy_try_and + +unused_wolf_i_will_not_be_defeated_by_this_trash: + type: NAUDIO:V1:SAMPLE + offset: 0xBA90 + parent: 0xB100 + sampleBankId: 2 + symbol: unused_wolf_i_will_not_be_defeated_by_this_trash + +ve2_andrew_ahhhhhhhh: + type: NAUDIO:V1:SAMPLE + offset: 0x12C50 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_andrew_ahhhhhhhh + +ve2_andrew_give_it_up: + type: NAUDIO:V1:SAMPLE + offset: 0x12B70 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_andrew_give_it_up + +ve2_andrew_well_make_sure_you_never_reach_andross: + type: NAUDIO:V1:SAMPLE + offset: 0x12770 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_andrew_well_make_sure_you_never_reach_andross + +ve2_andrew_you_cant_win: + type: NAUDIO:V1:SAMPLE + offset: 0x12B90 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_andrew_you_cant_win + +ve2_andrew_youre_not_welcome_here: + type: NAUDIO:V1:SAMPLE + offset: 0x12A90 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_andrew_youre_not_welcome_here + +ve2_andross_i_have_the_brains_to_rule_lylat: + type: NAUDIO:V1:SAMPLE + offset: 0x12810 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_andross_i_have_the_brains_to_rule_lylat + +ve2_andross_if_i_go_down_im_taking_you_with_me: + type: NAUDIO:V1:SAMPLE + offset: 0x12830 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_andross_if_i_go_down_im_taking_you_with_me + +ve2_andross_only: + type: NAUDIO:V1:SAMPLE + offset: 0x127F0 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_andross_only + +ve2_falco_i_see_youve_got_new_ships: + type: NAUDIO:V1:SAMPLE + offset: 0x12C70 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_falco_i_see_youve_got_new_ships + +ve2_falco_thats_our_leader: + type: NAUDIO:V1:SAMPLE + offset: 0x12970 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_falco_thats_our_leader + +ve2_falco_you_guys_dont_give_up: + type: NAUDIO:V1:SAMPLE + offset: 0x127B0 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_falco_you_guys_dont_give_up + +ve2_fox_father: + type: NAUDIO:V1:SAMPLE + offset: 0x12870 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_fox_father + +ve2_fox_nothing: + type: NAUDIO:V1:SAMPLE + offset: 0x129B0 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_fox_nothing + +ve2_fox_nothings_wrong: + type: NAUDIO:V1:SAMPLE + offset: 0x129D0 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_fox_nothings_wrong + +ve2_fox_say_your_prayers_andross: + type: NAUDIO:V1:SAMPLE + offset: 0x12600 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_fox_say_your_prayers_andross + +ve2_fox_so_andross: + type: NAUDIO:V1:SAMPLE + offset: 0x12D10 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_fox_so_andross + +ve2_fox_well_just_see_about_that_star_wolf: + type: NAUDIO:V1:SAMPLE + offset: 0x12790 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_fox_well_just_see_about_that_star_wolf + +ve2_fox_you_show_your_true_form: + type: NAUDIO:V1:SAMPLE + offset: 0x12D30 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_fox_you_show_your_true_form + +ve2_james_dont: + type: NAUDIO:V1:SAMPLE + offset: 0x12D70 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_james_dont + +ve2_james_ever_give_up_my_son: + type: NAUDIO:V1:SAMPLE + offset: 0x12D90 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_james_ever_give_up_my_son + +ve2_james_follow_me_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x12850 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_james_follow_me_fox + +ve2_james_never_give_up: + type: NAUDIO:V1:SAMPLE + offset: 0x128B0 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_james_never_give_up + +ve2_james_this_way_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x12890 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_james_this_way_fox + +ve2_james_trust_your_instincts: + type: NAUDIO:V1:SAMPLE + offset: 0x128D0 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_james_trust_your_instincts + +ve2_james_youve_become_so_strong_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x128F0 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_james_youve_become_so_strong_fox + +ve2_leon_hes: + type: NAUDIO:V1:SAMPLE + offset: 0x12BF0 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_leon_hes + +ve2_leon_lets_see_how_you_handle_our_new_ships: + type: NAUDIO:V1:SAMPLE + offset: 0x12710 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_leon_lets_see_how_you_handle_our_new_ships + +ve2_leon_too_strong: + type: NAUDIO:V1:SAMPLE + offset: 0x12C10 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_leon_too_strong + +ve2_peppy_fox_youre_okay: + type: NAUDIO:V1:SAMPLE + offset: 0x12910 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_peppy_fox_youre_okay + +ve2_peppy_i_cant_break_free: + type: NAUDIO:V1:SAMPLE + offset: 0x12CD0 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_peppy_i_cant_break_free + +ve2_peppy_whats_wrong_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x12990 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_peppy_whats_wrong_fox + +ve2_pigma_fail: + type: NAUDIO:V1:SAMPLE + offset: 0x12750 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_pigma_fail + +ve2_pigma_ive_got_a_better_ship: + type: NAUDIO:V1:SAMPLE + offset: 0x12B50 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_pigma_ive_got_a_better_ship + +ve2_pigma_this_cant_be_happening: + type: NAUDIO:V1:SAMPLE + offset: 0x12C30 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_pigma_this_cant_be_happening + +ve2_pigma_too_bad_dads_not_here_to_see_ya: + type: NAUDIO:V1:SAMPLE + offset: 0x12730 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_pigma_too_bad_dads_not_here_to_see_ya + +ve2_pigma_you_cant_beat_me: + type: NAUDIO:V1:SAMPLE + offset: 0x12B30 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_pigma_you_cant_beat_me + +ve2_slippy_go_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x12950 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_slippy_go_fox + +ve2_slippy_hey: + type: NAUDIO:V1:SAMPLE + offset: 0x12C90 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_slippy_hey + +ve2_slippy_nice_aircraft_guys: + type: NAUDIO:V1:SAMPLE + offset: 0x12CB0 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_slippy_nice_aircraft_guys + +ve2_slippy_way_to: + type: NAUDIO:V1:SAMPLE + offset: 0x12930 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_slippy_way_to + +ve2_wolf_but_im_better: + type: NAUDIO:V1:SAMPLE + offset: 0x12AD0 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_wolf_but_im_better + +ve2_wolf_dont_get_too_cocky_star_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x126B0 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_wolf_dont_get_too_cocky_star_fox + +ve2_wolf_i_dont_believe_it: + type: NAUDIO:V1:SAMPLE + offset: 0x12BD0 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_wolf_i_dont_believe_it + +ve2_wolf_no_way: + type: NAUDIO:V1:SAMPLE + offset: 0x12BB0 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_wolf_no_way + +ve2_wolf_youre_good: + type: NAUDIO:V1:SAMPLE + offset: 0x12AB0 + parent: 0x12400 + sampleBankId: 2 + symbol: ve2_wolf_youre_good + +ve_andross_its_foolish_to_come_against_me: + type: NAUDIO:V1:SAMPLE + offset: 0xAAD0 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_andross_its_foolish_to_come_against_me + +ve_andross_ive_been_waiting_for_you_star_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xAA90 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_andross_ive_been_waiting_for_you_star_fox + +ve_andross_now_you_will_feel_true_pain: + type: NAUDIO:V1:SAMPLE + offset: 0x127D0 + parent: 0x12400 + sampleBankId: 2 + symbol: ve_andross_now_you_will_feel_true_pain + +ve_andross_you_know_that_i_control_the_galaxy: + type: NAUDIO:V1:SAMPLE + offset: 0xAAB0 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_andross_you_know_that_i_control_the_galaxy + +ve_andross_you_will_die_just_like_your_father: + type: NAUDIO:V1:SAMPLE + offset: 0xAAF0 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_andross_you_will_die_just_like_your_father + +ve_falco_dont_get_too_close: + type: NAUDIO:V1:SAMPLE + offset: 0xA950 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_falco_dont_get_too_close + +ve_falco_dont_go_dyin_on_me: + type: NAUDIO:V1:SAMPLE + offset: 0xA830 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_falco_dont_go_dyin_on_me + +ve_falco_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xA970 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_falco_fox + +ve_falco_ill_take_the_left: + type: NAUDIO:V1:SAMPLE + offset: 0xA850 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_falco_ill_take_the_left + +ve_falco_okay_ill_admit_it: + type: NAUDIO:V1:SAMPLE + offset: 0xAB70 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_falco_okay_ill_admit_it + +ve_falco_these_guys_just_keep_coming: + type: NAUDIO:V1:SAMPLE + offset: 0xA810 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_falco_these_guys_just_keep_coming + +ve_falco_time_to_show_the_monkeys_whos_boss: + type: NAUDIO:V1:SAMPLE + offset: 0xA7B0 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_falco_time_to_show_the_monkeys_whos_boss + +ve_falco_you_did_good_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xAB90 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_falco_you_did_good_fox + +ve_fox_dont_relax: + type: NAUDIO:V1:SAMPLE + offset: 0xA6E0 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_fox_dont_relax + +ve_fox_ill_go_it_alone_from_here: + type: NAUDIO:V1:SAMPLE + offset: 0xA9D0 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_fox_ill_go_it_alone_from_here + +ve_fox_its_all_coming_down_to_this: + type: NAUDIO:V1:SAMPLE + offset: 0xA990 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_fox_its_all_coming_down_to_this + +ve_fox_were_not_done_yet: + type: NAUDIO:V1:SAMPLE + offset: 0xA790 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_fox_were_not_done_yet + +ve_peppy_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xA9F0 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_peppy_fox + +ve_peppy_fox_are_you_okay: + type: NAUDIO:V1:SAMPLE + offset: 0xAB10 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_peppy_fox_are_you_okay + +ve_peppy_ive_got_the_right: + type: NAUDIO:V1:SAMPLE + offset: 0xA870 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_peppy_ive_got_the_right + +ve_peppy_stay_alert: + type: NAUDIO:V1:SAMPLE + offset: 0xA930 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_peppy_stay_alert + +ve_peppy_this_brings_back_memories_of_your_dad: + type: NAUDIO:V1:SAMPLE + offset: 0xA7D0 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_peppy_this_brings_back_memories_of_your_dad + +ve_slippy_fox: + type: NAUDIO:V1:SAMPLE + offset: 0xAA30 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_slippy_fox + +ve_slippy_incoming: + type: NAUDIO:V1:SAMPLE + offset: 0x13EF0 + parent: 0x134A0 + sampleBankId: 2 + symbol: ve_slippy_incoming + +ve_slippy_that_temple_gives_me_the_creeps: + type: NAUDIO:V1:SAMPLE + offset: 0xA8F0 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_slippy_that_temple_gives_me_the_creeps + +ve_slippy_whats_going_on_hes_running_away: + type: NAUDIO:V1:SAMPLE + offset: 0xA910 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_slippy_whats_going_on_hes_running_away + +ve_slippy_yes: + type: NAUDIO:V1:SAMPLE + offset: 0xAB30 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_slippy_yes + +ve_slippy_you_did_it: + type: NAUDIO:V1:SAMPLE + offset: 0xAB50 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_slippy_you_did_it + +ve_slippy_youll_be_sorry_punks: + type: NAUDIO:V1:SAMPLE + offset: 0xA7F0 + parent: 0xA4E0 + sampleBankId: 2 + symbol: ve_slippy_youll_be_sorry_punks + +zo_falco_enemy_fighters_spotted: + type: NAUDIO:V1:SAMPLE + offset: 0x8B70 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_falco_enemy_fighters_spotted + +zo_falco_i_cant_believe_they_did_this: + type: NAUDIO:V1:SAMPLE + offset: 0x8970 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_falco_i_cant_believe_they_did_this + +zo_falco_i_hear_ya_slippy: + type: NAUDIO:V1:SAMPLE + offset: 0x8990 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_falco_i_hear_ya_slippy + +zo_falco_katt: + type: NAUDIO:V1:SAMPLE + offset: 0x8A50 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_falco_katt + +zo_falco_lets_take_em_all_out: + type: NAUDIO:V1:SAMPLE + offset: 0x89D0 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_falco_lets_take_em_all_out + +zo_falco_shoot: + type: NAUDIO:V1:SAMPLE + offset: 0x8BD0 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_falco_shoot + +zo_falco_take_em_down: + type: NAUDIO:V1:SAMPLE + offset: 0x8B90 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_falco_take_em_down + +zo_falco_what_are_you_doing_here: + type: NAUDIO:V1:SAMPLE + offset: 0x8A70 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_falco_what_are_you_doing_here + +zo_falco_whered_you_go: + type: NAUDIO:V1:SAMPLE + offset: 0x8F90 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_falco_whered_you_go + +zo_fox_have_we_been_spotted: + type: NAUDIO:V1:SAMPLE + offset: 0x8A10 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_fox_have_we_been_spotted + +zo_fox_lets_sneak_in_low_and_surprise_em: + type: NAUDIO:V1:SAMPLE + offset: 0x8860 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_fox_lets_sneak_in_low_and_surprise_em + +zo_fox_uh_oh: + type: NAUDIO:V1:SAMPLE + offset: 0x89F0 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_fox_uh_oh + +zo_katt_ive_got_somebody_on_my_tail: + type: NAUDIO:V1:SAMPLE + offset: 0x8B30 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_katt_ive_got_somebody_on_my_tail + +zo_katt_mess_with_me_and_youll_get_scratched: + type: NAUDIO:V1:SAMPLE + offset: 0x8B50 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_katt_mess_with_me_and_youll_get_scratched + +zo_katt_take_the_right_light_boy_i_have_the_left: + type: NAUDIO:V1:SAMPLE + offset: 0x8AD0 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_katt_take_the_right_light_boy_i_have_the_left + +zo_katt_were_closing_in_on_them_falco: + type: NAUDIO:V1:SAMPLE + offset: 0x8A30 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_katt_were_closing_in_on_them_falco + +zo_peppy_aim_for_the_rudder_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x8B10 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_peppy_aim_for_the_rudder_fox + +zo_peppy_be_careful_it_might_be_a_trap: + type: NAUDIO:V1:SAMPLE + offset: 0x8C30 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_peppy_be_careful_it_might_be_a_trap + +zo_peppy_destroy_the_crane: + type: NAUDIO:V1:SAMPLE + offset: 0x8F10 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_peppy_destroy_the_crane + +zo_peppy_destroy_the_two_exhaust_pipes: + type: NAUDIO:V1:SAMPLE + offset: 0x8ED0 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_peppy_destroy_the_two_exhaust_pipes + +zo_peppy_enemy_tanker: + type: NAUDIO:V1:SAMPLE + offset: 0x8AF0 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_peppy_enemy_tanker + +zo_peppy_follow_your_fathers_example_fox: + type: NAUDIO:V1:SAMPLE + offset: 0x4A90 + parent: 0x4520 + sampleBankId: 2 + symbol: zo_peppy_follow_your_fathers_example_fox + +zo_peppy_his_armors_tough_use_bombs_wisely: + type: NAUDIO:V1:SAMPLE + offset: 0x8EB0 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_peppy_his_armors_tough_use_bombs_wisely + +zo_peppy_looks_like_were_headin_for_macbeth: + type: NAUDIO:V1:SAMPLE + offset: 0x8F50 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_peppy_looks_like_were_headin_for_macbeth + +zo_peppy_quick: + type: NAUDIO:V1:SAMPLE + offset: 0x8EF0 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_peppy_quick + +zo_peppy_this_is_zoness: + type: NAUDIO:V1:SAMPLE + offset: 0x8910 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_peppy_this_is_zoness + +zo_sarumarine_adjust_10_degrees_right: + type: NAUDIO:V1:SAMPLE + offset: 0x8D30 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_sarumarine_adjust_10_degrees_right + +zo_sarumarine_all_sections_ready: + type: NAUDIO:V1:SAMPLE + offset: 0x8CD0 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_sarumarine_all_sections_ready + +zo_sarumarine_angle_okay: + type: NAUDIO:V1:SAMPLE + offset: 0x8D90 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_sarumarine_angle_okay + +zo_sarumarine_arrr: + type: NAUDIO:V1:SAMPLE + offset: 0x8DD0 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_sarumarine_arrr + +zo_sarumarine_arrrrrrrrggghhhhh: + type: NAUDIO:V1:SAMPLE + offset: 0x8E90 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_sarumarine_arrrrrrrrggghhhhh + +zo_sarumarine_disrespectful_little_whelps: + type: NAUDIO:V1:SAMPLE + offset: 0x8C90 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_sarumarine_disrespectful_little_whelps + +zo_sarumarine_drop_the_crane_now: + type: NAUDIO:V1:SAMPLE + offset: 0x8DF0 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_sarumarine_drop_the_crane_now + +zo_sarumarine_engage: + type: NAUDIO:V1:SAMPLE + offset: 0x8CF0 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_sarumarine_engage + +zo_sarumarine_fire: + type: NAUDIO:V1:SAMPLE + offset: 0x8D50 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_sarumarine_fire + +zo_sarumarine_fire_anyway: + type: NAUDIO:V1:SAMPLE + offset: 0x8E30 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_sarumarine_fire_anyway + +zo_sarumarine_fire_torpedo: + type: NAUDIO:V1:SAMPLE + offset: 0x8DB0 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_sarumarine_fire_torpedo + +zo_sarumarine_i_cant_see_anything: + type: NAUDIO:V1:SAMPLE + offset: 0x8E10 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_sarumarine_i_cant_see_anything + +zo_sarumarine_ill_teach_ye_some_respect: + type: NAUDIO:V1:SAMPLE + offset: 0x8CB0 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_sarumarine_ill_teach_ye_some_respect + +zo_sarumarine_oh_shoot: + type: NAUDIO:V1:SAMPLE + offset: 0x8F30 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_sarumarine_oh_shoot + +zo_sarumarine_prepare_to_surface: + type: NAUDIO:V1:SAMPLE + offset: 0x8D10 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_sarumarine_prepare_to_surface + +zo_sarumarine_pressure: + type: NAUDIO:V1:SAMPLE + offset: 0x8D70 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_sarumarine_pressure + +zo_sarumarine_yahahahahahar: + type: NAUDIO:V1:SAMPLE + offset: 0x8C70 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_sarumarine_yahahahahahar + +zo_slippy_here_i_go: + type: NAUDIO:V1:SAMPLE + offset: 0x8AB0 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_slippy_here_i_go + +zo_slippy_somethings_coming_from_the_sea: + type: NAUDIO:V1:SAMPLE + offset: 0x8C50 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_slippy_somethings_coming_from_the_sea + +zo_slippy_watch_out: + type: NAUDIO:V1:SAMPLE + offset: 0x8C10 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_slippy_watch_out + +zo_slippy_watch_out_for_the_search_light: + type: NAUDIO:V1:SAMPLE + offset: 0x89B0 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_slippy_watch_out_for_the_search_light + +zo_slippy_what_a_dump: + type: NAUDIO:V1:SAMPLE + offset: 0x8930 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_slippy_what_a_dump + +zo_slippy_woah: + type: NAUDIO:V1:SAMPLE + offset: 0x8BF0 + parent: 0x8660 + sampleBankId: 2 + symbol: zo_slippy_woah + diff --git a/cmake/find_and_copy_libtcc1.cmake b/cmake/find_and_copy_libtcc1.cmake new file mode 100644 index 000000000..1cb632858 --- /dev/null +++ b/cmake/find_and_copy_libtcc1.cmake @@ -0,0 +1,32 @@ +# cmake/find_and_copy_libtcc1.cmake +# Called at build time via cmake -P. +# Variables passed in: +# SEARCH_DIR - primary recursive search root (e.g. CMAKE_BINARY_DIR) +# DEST_DIR - destination directory to copy libtcc1.a into +# SYSTEM_FALLBACK_DIRS - (optional) semicolon-separated list of system dirs to +# check if not found under SEARCH_DIR (e.g. /usr/lib) + +file(GLOB_RECURSE LIBTCC1_CANDIDATES "${SEARCH_DIR}/libtcc1.a") + +if(LIBTCC1_CANDIDATES) + list(GET LIBTCC1_CANDIDATES 0 LIBTCC1_PATH) + message(STATUS "Found libtcc1.a at: ${LIBTCC1_PATH}") + file(COPY "${LIBTCC1_PATH}" DESTINATION "${DEST_DIR}") +else() + # Fall back to system-installed locations if provided + set(FOUND_IN_SYSTEM FALSE) + if(DEFINED SYSTEM_FALLBACK_DIRS) + foreach(SYSDIR ${SYSTEM_FALLBACK_DIRS}) + if(EXISTS "${SYSDIR}/libtcc1.a") + message(STATUS "Found libtcc1.a in system path: ${SYSDIR}/libtcc1.a") + file(COPY "${SYSDIR}/libtcc1.a" DESTINATION "${DEST_DIR}") + set(FOUND_IN_SYSTEM TRUE) + break() + endif() + endforeach() + endif() + + if(NOT FOUND_IN_SYSTEM) + message(WARNING "libtcc1.a was not found under '${SEARCH_DIR}' or in any system fallback path. Skipping copy.") + endif() +endif() \ No newline at end of file diff --git a/cmake/lus-cvars.cmake b/cmake/lus-cvars.cmake new file mode 100644 index 000000000..e4c54c4ae --- /dev/null +++ b/cmake/lus-cvars.cmake @@ -0,0 +1,21 @@ +set(CVAR_VSYNC_ENABLED "${CVAR_PREFIX_SETTING}.VsyncEnabled") +set(CVAR_Z_FIGHTING_MODE "${CVAR_PREFIX_SETTING}.ZFightingMode") +set(CVAR_INTERNAL_RESOLUTION "${CVAR_PREFIX_SETTING}.InternalResolution") +set(CVAR_MSAA_VALUE "${CVAR_PREFIX_SETTING}.MSAAValue") +set(CVAR_SDL_WINDOWED_FULLSCREEN "${CVAR_PREFIX_SETTING}.SdlWindowedFullscreen") +set(CVAR_TEXTURE_FILTER "${CVAR_PREFIX_SETTING}.TextureFilter") +set(CVAR_IMGUI_CONTROLLER_NAV "${CVAR_PREFIX_SETTING}.ControlNav") +set(CVAR_CONSOLE_WINDOW_OPEN "${CVAR_PREFIX_WINDOW}.Console") +set(CVAR_CONTROLLER_CONFIGURATION_WINDOW_OPEN "${CVAR_PREFIX_WINDOW}.ControllerConfiguration") +set(CVAR_CONTROLLER_DISCONNECTED_WINDOW_OPEN "${CVAR_PREFIX_WINDOW}.ControllerDisconnected") +set(CVAR_CONTROLLER_REORDERING_WINDOW_OPEN "${CVAR_PREFIX_WINDOW}.ControllerReordering") +set(CVAR_GFX_DEBUGGER_WINDOW_OPEN "${CVAR_PREFIX_WINDOW}.GfxDebugger") +set(CVAR_STATS_WINDOW_OPEN "${CVAR_PREFIX_WINDOW}.Stats") +set(CVAR_ENABLE_MULTI_VIEWPORTS "${CVAR_PREFIX_SETTING}.EnableMultiViewports") +set(CVAR_LOW_RES_MODE "${CVAR_PREFIX_SETTING}.LowResMode") +set(CVAR_SIMULATED_INPUT_LAG "${CVAR_PREFIX_SETTING}.SimulatedInputLag") +set(CVAR_GAME_OVERLAY_FONT "${CVAR_PREFIX_SETTING}.OverlayFont") +set(CVAR_MENU_BAR_OPEN "${CVAR_PREFIX_SETTING}.OpenMenuBar") +set(CVAR_PREFIX_CONTROLLERS "${CVAR_PREFIX_SETTING}.Controllers") +set(CVAR_PREFIX_ADVANCED_RESOLUTION "${CVAR_PREFIX_SETTING}.AdvancedResolution") +include("libultraship/cmake/cvars.cmake") diff --git a/cmake/starship-cvars.cmake b/cmake/starship-cvars.cmake new file mode 100644 index 000000000..485a97265 --- /dev/null +++ b/cmake/starship-cvars.cmake @@ -0,0 +1,26 @@ +set(CVAR_PREFIX_COSMETIC "gCosmetics") +set(CVAR_PREFIX_AUDIO "gAudioEditor") +set(CVAR_PREFIX_CHEAT "gCheats") +set(CVAR_PREFIX_ENHANCEMENT "gEnhancements") +set(CVAR_PREFIX_SETTING "gSettings") +set(CVAR_PREFIX_WINDOW "gOpenWindows") +set(CVAR_PREFIX_TRACKER "gTrackers") +set(CVAR_PREFIX_DEVELOPER_TOOLS "gDeveloperTools") +set(CVAR_PREFIX_GENERAL "gGeneral") +set(CVAR_PREFIX_REMOTE "gRemote") +set(CVAR_PREFIX_GAMEPLAY_STATS "gGameplayStats") +set(CVAR_PREFIX_TIME_DISPLAY "gTimeDisplay") +add_compile_definitions( + CVAR_PREFIX_COSMETIC="${CVAR_PREFIX_COSMETIC}" + CVAR_PREFIX_AUDIO="${CVAR_PREFIX_AUDIO}" + CVAR_PREFIX_CHEAT="${CVAR_PREFIX_CHEAT}" + CVAR_PREFIX_ENHANCEMENT="${CVAR_PREFIX_ENHANCEMENT}" + CVAR_PREFIX_SETTING="${CVAR_PREFIX_SETTING}" + CVAR_PREFIX_WINDOW="${CVAR_PREFIX_WINDOW}" + CVAR_PREFIX_TRACKER="${CVAR_PREFIX_TRACKER}" + CVAR_PREFIX_DEVELOPER_TOOLS="${CVAR_PREFIX_DEVELOPER_TOOLS}" + CVAR_PREFIX_GENERAL="${CVAR_PREFIX_GENERAL}" + CVAR_PREFIX_REMOTE="${CVAR_PREFIX_REMOTE}" + CVAR_PREFIX_GAMEPLAY_STATS="${CVAR_PREFIX_GAMEPLAY_STATS}" + CVAR_PREFIX_TIME_DISPLAY="${CVAR_PREFIX_TIME_DISPLAY}" +) \ No newline at end of file diff --git a/include/audiothread_cmd.h b/include/audiothread_cmd.h index cec7488c0..de70df167 100644 --- a/include/audiothread_cmd.h +++ b/include/audiothread_cmd.h @@ -1,9 +1,11 @@ #ifndef AUDIOTHREAD_CMD_H #define AUDIOTHREAD_CMD_H -void AudioThread_QueueCmdF32(u32 opArgs, f32 val); -void AudioThread_QueueCmdS32(u32 opArgs, u32 val); -void AudioThread_QueueCmdS8(u32 opArgs, s8 val); +#include "macros.h" + +extern_s void AudioThread_QueueCmdF32(u32 opArgs, f32 val); +extern_s void AudioThread_QueueCmdS32(u32 opArgs, u32 val); +extern_s void AudioThread_QueueCmdS8(u32 opArgs, s8 val); /** * Audio thread commands to safely transfer information/requests/data diff --git a/include/buffers.h b/include/buffers.h index d28c40dfd..20f6d9226 100644 --- a/include/buffers.h +++ b/include/buffers.h @@ -3,13 +3,13 @@ #include "gfx.h" -extern u64 gDramStack[]; -extern u8 gOSYieldData[]; -extern FrameBuffer gZBuffer; // z buffer -extern u8 gTaskOutputBuffer[]; -extern u8 gAudioHeap[]; -extern u16 gTextureRenderBuffer[]; -extern u16 gFillBuffer[]; -extern FrameBuffer gFrameBuffers[]; // 8038F800 +extern_s u64 gDramStack[]; +extern_s u8 gOSYieldData[]; +extern_s FrameBuffer gZBuffer; // z buffer +extern_s u8 gTaskOutputBuffer[]; +extern_s u8 gAudioHeap[]; +extern_s u16 gTextureRenderBuffer[]; +extern_s u16 gFillBuffer[]; +extern_s FrameBuffer gFrameBuffers[]; // 8038F800 #endif diff --git a/include/fox_option.h b/include/fox_option.h index 9605a7271..f6defd9b8 100644 --- a/include/fox_option.h +++ b/include/fox_option.h @@ -78,25 +78,25 @@ typedef enum OptionId { /* 401 */ OPTION_MAX } OptionId; -extern u8* gBSSMapPlanetTextures[9]; -extern u8* gAssetMapPlanetTextures[9]; +extern_s u8* gBSSMapPlanetTextures[9]; +extern_s u8* gAssetMapPlanetTextures[9]; -extern s32 gTotalHitsRanking[]; -extern bool gGoToTitle; // engine -extern u8 sLevelStartState; -extern s32 sWipeHeight; -extern s32 sTitleRankMaxRecords; +extern_s s32 gTotalHitsRanking[]; +extern_s bool gGoToTitle; // engine +extern_s u8 sLevelStartState; +extern_s s32 sWipeHeight; +extern_s s32 sTitleRankMaxRecords; // Planet textures -extern u8 gMapVenomCloudTex[96 * 96]; -extern u8 gMapCorneriaTex[96 * 96]; -extern u8 gMapFortunaTex[96 * 96]; -extern u8 gMapAquasTex[96 * 96]; -extern u8 gMapVenomTex[96 * 96]; -extern u8 gMapTitaniaTex[96 * 96]; -extern u8 gMapKatinaTex[96 * 96]; -extern u8 gMapMacbethTex[96 * 96]; -extern u8 gMapZonessTex[96 * 96]; +extern_s u8 gMapVenomCloudTex[96 * 96]; +extern_s u8 gMapCorneriaTex[96 * 96]; +extern_s u8 gMapFortunaTex[96 * 96]; +extern_s u8 gMapAquasTex[96 * 96]; +extern_s u8 gMapVenomTex[96 * 96]; +extern_s u8 gMapTitaniaTex[96 * 96]; +extern_s u8 gMapKatinaTex[96 * 96]; +extern_s u8 gMapMacbethTex[96 * 96]; +extern_s u8 gMapZonessTex[96 * 96]; void Title_UpdateEntry(void); s32 Title_CheckControllers(void); diff --git a/include/fox_record.h b/include/fox_record.h index 6d9cec6e7..be27dc24e 100644 --- a/include/fox_record.h +++ b/include/fox_record.h @@ -14,20 +14,20 @@ typedef struct Record { u16 frame; } Record; -extern Record gCarrierCutsceneRecord[13]; -extern Record gWarpzoneCsRecord[19]; -extern Record gA6GorgonCsRecord[12]; -extern Record gSyRobotCutsceneRecord[3]; -extern Record gAndrossRobotKillCutscene2[20]; -extern Record gAndrossRobotKillCutscene1[25]; -extern Record gMacbethCutsceneRecord[14]; -extern Record gGrangaCutsceneRecord[13]; -extern Record gMeCrusherCutsceneRecord[3]; -extern Record gEndingCsRecord[37]; -extern Record gSolarIntroCsRecord[16]; +extern_s Record gCarrierCutsceneRecord[13]; +extern_s Record gWarpzoneCsRecord[19]; +extern_s Record gA6GorgonCsRecord[12]; +extern_s Record gSyRobotCutsceneRecord[3]; +extern_s Record gAndrossRobotKillCutscene2[20]; +extern_s Record gAndrossRobotKillCutscene1[25]; +extern_s Record gMacbethCutsceneRecord[14]; +extern_s Record gGrangaCutsceneRecord[13]; +extern_s Record gMeCrusherCutsceneRecord[3]; +extern_s Record gEndingCsRecord[37]; +extern_s Record gSolarIntroCsRecord[16]; -extern int gA6GorgonCsFrameCount; -extern int gWarpzoneCsFrameCount; +extern_s int gA6GorgonCsFrameCount; +extern_s int gWarpzoneCsFrameCount; void UpdateVisPerFrameFromRecording(Record* record, s32 maxFrames, int* frameCounter); diff --git a/include/gfx.h b/include/gfx.h index 99eb5252c..f5ab0f805 100644 --- a/include/gfx.h +++ b/include/gfx.h @@ -332,8 +332,8 @@ typedef enum SetupDL { SETUPDL_85_POINT } SetupDL; -extern Gfx gRcpSetupDLs[][9]; // 0x800D31B0 -extern u8 D_80178580[]; -extern void* D_80178710; +extern_s Gfx gRcpSetupDLs[][9]; // 0x800D31B0 +extern_s u8 D_80178580[]; +extern_s void* D_80178710; #endif diff --git a/include/i1.h b/include/i1.h index 0fa47966c..715ecf25b 100644 --- a/include/i1.h +++ b/include/i1.h @@ -7,12 +7,12 @@ #include "sf64player.h" #include "sf64mesg.h" -extern Gfx* D_VE1_8019A008[]; -extern f32 aVe1GolemechHitbox[]; +extern_s Gfx* D_VE1_8019A008[]; +extern_s f32 aVe1GolemechHitbox[]; -extern void Corneria_LevelStart(Player*); -extern void Corneria_LevelComplete1(Player*); -extern void Venom1_LevelStart(Player*); +extern_s void Corneria_LevelStart(Player*); +extern_s void Corneria_LevelComplete1(Player*); +extern_s void Venom1_LevelStart(Player*); void Corneria_CoSmoke_Update(Sprite*); void Corneria_CoGranga_Update(CoGranga*); diff --git a/include/i3.h b/include/i3.h index b455a5775..0219c8c18 100644 --- a/include/i3.h +++ b/include/i3.h @@ -7,7 +7,7 @@ #include "sf64player.h" #include "sf64mesg.h" -extern f32 D_AQ_801C4188; +extern_s f32 D_AQ_801C4188; void Aquas_CsAqFishGroup_Update(Actor*); diff --git a/include/i4.h b/include/i4.h index 6008ace61..af2285ca0 100644 --- a/include/i4.h +++ b/include/i4.h @@ -7,8 +7,8 @@ #include "sf64player.h" #include "sf64mesg.h" -extern s32 D_BO_801A03DC; -extern Matrix D_BO_8019EE80; +extern_s s32 D_BO_801A03DC; +extern_s Matrix D_BO_8019EE80; void Bolse_LevelStart(Player*); void Bolse_LevelComplete(Player*); diff --git a/include/i5.h b/include/i5.h index af06200cc..f1068b965 100644 --- a/include/i5.h +++ b/include/i5.h @@ -8,13 +8,13 @@ #include "sf64mesg.h" -extern Gfx* D_TI_801B7584[]; -extern Gfx* D_TI_801B7608[]; -extern Gfx* D_TI_801B769C[]; -extern f32 aTiGorasHitbox[]; -extern u8 D_MA_801BA1E8; -extern f32 D_MA_801BE250[40]; -extern s16 D_MA_801BE2F0[9]; +extern_s Gfx* D_TI_801B7584[]; +extern_s Gfx* D_TI_801B7608[]; +extern_s Gfx* D_TI_801B769C[]; +extern_s f32 aTiGorasHitbox[]; +extern_s u8 D_MA_801BA1E8; +extern_s f32 D_MA_801BE250[40]; +extern_s s16 D_MA_801BE2F0[9]; void Titania_LevelStart(Player*); void Titania_LevelComplete(Player*); diff --git a/include/i6.h b/include/i6.h index 30d820e2f..829d63361 100644 --- a/include/i6.h +++ b/include/i6.h @@ -7,11 +7,11 @@ #include "sf64player.h" #include "sf64mesg.h" -extern f32 D_Andross_801A7F58; -extern f32 D_Andross_801A7F60; -extern f32 D_Andross_801A7F68; -extern f32 D_Andross_801A7F70; -extern f32 D_Andross_801A7F78; +extern_s f32 D_Andross_801A7F58; +extern_s f32 D_Andross_801A7F60; +extern_s f32 D_Andross_801A7F68; +extern_s f32 D_Andross_801A7F70; +extern_s f32 D_Andross_801A7F78; void Andross_80187530(Actor*); void Andross_80193C4C(Player*); diff --git a/include/macros.h b/include/macros.h index a567fc5cd..3d914d28a 100644 --- a/include/macros.h +++ b/include/macros.h @@ -4,6 +4,21 @@ #include "alignment.h" #include "libc/math.h" #include +#include + +#ifdef _WIN32 +#ifndef __DLL__ +#define extern_s API_EXTERN __declspec(dllexport) +#else +#define extern_s API_EXTERN __declspec(dllimport) +#endif +#else +#define extern_s API_EXTERN +#endif + +#ifdef __cplusplus +#define this thisx +#endif #define SCREEN_WIDTH 320 #define SCREEN_HEIGHT 240 @@ -43,8 +58,8 @@ #define RAD_TO_DEG(radians) (((radians) * 180.0f) / M_PI) #define DEG_TO_RAD(degrees) (((degrees) / 180.0f) * M_PI) -extern f32 SIN_DEG(f32 angle); -extern f32 COS_DEG(f32 angle); +extern_s f32 SIN_DEG(f32 angle); +extern_s f32 COS_DEG(f32 angle); #define USEC_TO_CYCLES(n) (((u64)(n)*(OS_CLOCK_RATE/15625LL))/(1000000LL/15625LL)) #define MSEC_TO_CYCLES(n) (USEC_TO_CYCLES((n) * 1000LL)) @@ -80,4 +95,4 @@ extern f32 COS_DEG(f32 angle); #define ALIGN_ASSET(x) __attribute__((aligned (x))) #endif -#endif // MACROS_H +#endif // MACROS_H \ No newline at end of file diff --git a/include/sf64audio_external.h b/include/sf64audio_external.h index eea7762b0..df069f3f7 100644 --- a/include/sf64audio_external.h +++ b/include/sf64audio_external.h @@ -6,6 +6,10 @@ #include "sfx.h" #include "bgm.h" +#ifdef __cplusplus +extern "C" { +#endif + void Audio_PlayVoice(s32 msgId); void Audio_PlayVoiceWithoutBGM(u32 msgId); void Audio_ClearVoice(void); @@ -18,6 +22,10 @@ void Audio_SetVolume(u8 audioType, u8 volume); void Audio_FadeOutAll(u8 fadeoutTime); void Audio_SetAudioSpec(u8 unused, u16 specParam); +#ifdef __cplusplus +} +#endif + #define AUDIO_SET_SPEC(sfxLayout, spec) Audio_SetAudioSpec(0, ((sfxLayout) << 8) | (spec)) #define AUDIO_SET_SPEC_ALT(sfxLayout, spec) Audio_SetAudioSpec((sfxLayout), ((sfxLayout) << 8) | (spec)) diff --git a/include/sf64audio_provisional.h b/include/sf64audio_provisional.h index 5c27e7335..74bd055b0 100644 --- a/include/sf64audio_provisional.h +++ b/include/sf64audio_provisional.h @@ -237,14 +237,18 @@ typedef struct { /* 0x00 */ u32 medium : 2; // Medium where sample is currently stored /* 0x00 */ u32 unk_bit26 : 1; /* 0x00 */ u32 isRelocated : 1; // Has the sample header been relocated (offsets to pointers) - /* 0x01 */ u32 size : 24; // Size of the sample - /* 0x04 */ u8* sampleAddr; // Raw sample data. Offset from the start of the sample bank or absolute address to + /* 0x04 */ u32 size; // Size of the sample + /* 0x08 */ u8* sampleAddr; // Raw sample data. Offset from the start of the sample bank or absolute address to // either rom or ram - /* 0x08 */ AdpcmLoop* + /* 0x0C */ AdpcmLoop* loop; // Adpcm loop parameters used by the sample. Offset from the start of the sound font / pointer to ram - /* 0x0C */ AdpcmBook* + /* 0x10 */ AdpcmBook* book; // Adpcm book parameters used by the sample. Offset from the start of the sound font / pointer to ram -} Sample; // size = 0x10 + /* 0x14 */ float tuning; + /* 0x18 */ u32 channels; + /* 0x1C */ u32 sampleRate; + /* 0x20 */ u32 numFrames; +} Sample; // size = 0x24 typedef struct { /* 0x00 */ Sample* sample; @@ -1114,143 +1118,142 @@ bool AudioThread_ResetComplete(void); void AudioThread_ResetAudioHeap(s32); void AudioThread_Init(void); -// extern AudioTable gSampleBankTableInit; -// extern AudioTable gSeqTableInit; -// extern AudioTable gSoundFontTableInit; -// extern u8 gSeqFontTableInit[]; - -extern AudioSpec gAudioSpecs[]; -extern s16 gSeqTicksPerBeat; -extern s32 gAudioHeapSize; -extern s32 gInitPoolSize; -extern u32 gPermanentPoolSize; -extern u16 gSequenceMedium; -extern u16 gSoundFontMedium; -extern u16 gSampleBankMedium; - -extern u64 gAudioContextStart[]; -extern SynthesisReverb gSynthReverbs[4]; -extern u8 sAudioContextPad10[0x10]; // 0x10 -extern u16 D_8014C1B0; -extern s8 D_8014C1B2; -extern s8 gNumSynthReverbs; -extern s16 D_8014C1B4; -extern NoteSubEu* gNoteSubsEu; +#ifdef __cplusplus +} +#endif +// extern_s AudioTable gSampleBankTableInit; +// extern_s AudioTable gSeqTableInit; +// extern_s AudioTable gSoundFontTableInit; +// extern_s u8 gSeqFontTableInit[]; + +extern_s AudioSpec gAudioSpecs[]; +extern_s s16 gSeqTicksPerBeat; +extern_s s32 gAudioHeapSize; +extern_s s32 gInitPoolSize; +extern_s u32 gPermanentPoolSize; +extern_s u16 gSequenceMedium; +extern_s u16 gSoundFontMedium; +extern_s u16 gSampleBankMedium; + +extern_s u64 gAudioContextStart[]; +extern_s SynthesisReverb gSynthReverbs[4]; +extern_s u8 sAudioContextPad10[0x10]; // 0x10 +extern_s u16 D_8014C1B0; +extern_s s8 D_8014C1B2; +extern_s s8 gNumSynthReverbs; +extern_s s16 D_8014C1B4; +extern_s NoteSubEu* gNoteSubsEu; // 0x4 -extern AudioAllocPool gSessionPool; -extern AudioAllocPool gInitPool; -extern AudioAllocPool gMiscPool; -extern u8 gAudioContextPad20[0x20]; // 0x20 -extern AudioAllocPool gCachePool; -extern AudioAllocPool gPersistentCommonPool; -extern AudioAllocPool gTemporaryCommonPool; -extern AudioCache gSeqCache; -extern AudioCache gFontCache; -extern AudioCache gSampleBankCache; -extern PermanentCache gPermanentPool; -extern AudioSampleCache gPersistentSampleCache; +extern_s AudioAllocPool gSessionPool; +extern_s AudioAllocPool gInitPool; +extern_s AudioAllocPool gMiscPool; +extern_s u8 gAudioContextPad20[0x20]; // 0x20 +extern_s AudioAllocPool gCachePool; +extern_s AudioAllocPool gPersistentCommonPool; +extern_s AudioAllocPool gTemporaryCommonPool; +extern_s AudioCache gSeqCache; +extern_s AudioCache gFontCache; +extern_s AudioCache gSampleBankCache; +extern_s PermanentCache gPermanentPool; +extern_s AudioSampleCache gPersistentSampleCache; // 0x4 -extern AudioSampleCache gTemporarySampleCache; +extern_s AudioSampleCache gTemporarySampleCache; // 0x4 -extern AudioSessionPoolSplit gSessionPoolSplit; -extern AudioCachePoolSplit gCachePoolSplit; -extern AudioCommonPoolSplit gPersistentCommonPoolSplit; +extern_s AudioSessionPoolSplit gSessionPoolSplit; +extern_s AudioCachePoolSplit gCachePoolSplit; +extern_s AudioCommonPoolSplit gPersistentCommonPoolSplit; // 0x4 -extern AudioCommonPoolSplit gTemporaryCommonPoolSplit; +extern_s AudioCommonPoolSplit gTemporaryCommonPoolSplit; // 0x4 -extern u8 gSampleFontLoadStatus[2048]; -extern u8 gFontLoadStatus[2048]; -extern u8 gSeqLoadStatus[2048]; -extern volatile u8 gAudioResetStep; -extern u8 gAudioSpecId; -extern s32 gResetFadeoutFramesLeft; -extern u8 sAudioContextPad1000[0x1000]; // 0x1000 gap -extern Note* gNotes; +extern_s u8 gSampleFontLoadStatus[2048]; +extern_s u8 gFontLoadStatus[2048]; +extern_s u8 gSeqLoadStatus[2048]; +extern_s volatile u8 gAudioResetStep; +extern_s u8 gAudioSpecId; +extern_s s32 gResetFadeoutFramesLeft; +extern_s u8 sAudioContextPad1000[0x1000]; // 0x1000 gap +extern_s Note* gNotes; // 0x4 -extern SequencePlayer gSeqPlayers[4]; -extern SequenceChannel gSeqChannels[48]; -extern SequenceLayer gSeqLayers[64]; -extern SequenceChannel gSeqChannelNone; -extern AudioListItem gLayerFreeList; -extern NotePool gNoteFreeLists; -extern Sample* gUsedSamples[2048]; -extern AudioPreloadReq gPreloadSampleStack[128]; -extern s32 gNumUsedSamples; -extern s32 gPreloadSampleStackTop; -extern AudioAsyncLoad gAsyncLoads[16]; -extern OSMesgQueue gExternalLoadQueue; -extern OSMesg gExternalLoadMsg[16]; -extern OSMesgQueue gPreloadSampleQueue; -extern OSMesg gPreloadSampleMsg[16]; -extern OSMesgQueue gCurAudioFrameDmaQueue; -extern OSMesg gCurAudioFrameDmaMsg[64]; -extern OSIoMesg gCurAudioFrameDmaIoMsgBuf[64]; -extern OSMesgQueue gSyncDmaQueue; -extern OSMesg gSyncDmaMsg[1]; +extern_s SequencePlayer gSeqPlayers[4]; +extern_s SequenceChannel gSeqChannels[48]; +extern_s SequenceLayer gSeqLayers[64]; +extern_s SequenceChannel gSeqChannelNone; +extern_s AudioListItem gLayerFreeList; +extern_s NotePool gNoteFreeLists; +extern_s Sample* gUsedSamples[2048]; +extern_s AudioPreloadReq gPreloadSampleStack[128]; +extern_s s32 gNumUsedSamples; +extern_s s32 gPreloadSampleStackTop; +extern_s AudioAsyncLoad gAsyncLoads[16]; +extern_s OSMesgQueue gExternalLoadQueue; +extern_s OSMesg gExternalLoadMsg[16]; +extern_s OSMesgQueue gPreloadSampleQueue; +extern_s OSMesg gPreloadSampleMsg[16]; +extern_s OSMesgQueue gCurAudioFrameDmaQueue; +extern_s OSMesg gCurAudioFrameDmaMsg[64]; +extern_s OSIoMesg gCurAudioFrameDmaIoMsgBuf[64]; +extern_s OSMesgQueue gSyncDmaQueue; +extern_s OSMesg gSyncDmaMsg[1]; // 0x4 -extern OSIoMesg gSyncDmaIoMsg; -extern SampleDma gSampleDmas[0x100]; -extern u32 gSampleDmaCount; -extern u32 gSampleDmaListSize1; -extern s32 D_80155A50; +extern_s OSIoMesg gSyncDmaIoMsg; +extern_s SampleDma gSampleDmas[0x100]; +extern_s u32 gSampleDmaCount; +extern_s u32 gSampleDmaListSize1; +extern_s s32 D_80155A50; // 0x4 -extern u8 gSampleDmaReuseQueue1[0x100]; -extern u8 gSampleDmaReuseQueue2[0x100]; -extern u8 gSampleDmaReuseQueue1RdPos; -extern u8 gSampleDmaReuseQueue2RdPos; -extern u8 gSampleDmaReuseQueue1WrPos; -extern u8 gSampleDmaReuseQueue2WrPos; -extern AudioTable* gSequenceTable; -extern AudioTable* gSoundFontTable; -extern AudioTable* gSampleBankTable; -extern u8* gSeqFontTable; -extern s16 gNumSequences; -extern SoundFont* gSoundFontList; +extern_s u8 gSampleDmaReuseQueue1[0x100]; +extern_s u8 gSampleDmaReuseQueue2[0x100]; +extern_s u8 gSampleDmaReuseQueue1RdPos; +extern_s u8 gSampleDmaReuseQueue2RdPos; +extern_s u8 gSampleDmaReuseQueue1WrPos; +extern_s u8 gSampleDmaReuseQueue2WrPos; +extern_s AudioTable* gSequenceTable; +extern_s AudioTable* gSoundFontTable; +extern_s AudioTable* gSampleBankTable; +extern_s u8* gSeqFontTable; +extern_s s16 gNumSequences; +extern_s SoundFont* gSoundFontList; // 0x4 -extern AudioBufferParameters gAudioBufferParams; -extern s32 gSampleDmaBuffSize; -extern s32 gMaxAudioCmds; -extern s32 gNumNotes; -extern s16 gMaxTempo; -extern s8 gAudioSoundMode; -extern volatile s32 gAudioTaskCountQ; -extern s32 gCurAudioFrameDmaCount; -extern s32 gAudioTaskIndexQ; -extern s32 gCurAiBuffIndex; -extern Acmd* gAbiCmdBuffs[2]; -extern Acmd* gCurAbiCmdBuffer; -extern SPTask* gAudioCurTask; -extern SPTask gAudioRspTasks[2]; -extern f32 gMaxTempoTvTypeFactors; -extern s32 gRefreshRate; -extern s16* gAiBuffers[3]; -extern s16 gAiBuffLengths[3]; -extern u32 gAudioRandom; -extern u32 D_80155D88; -extern volatile u32 gAudioResetTimer; - -extern u64 gAudioContextEnd[]; +extern_s AudioBufferParameters gAudioBufferParams; +extern_s s32 gSampleDmaBuffSize; +extern_s s32 gMaxAudioCmds; +extern_s s32 gNumNotes; +extern_s s16 gMaxTempo; +extern_s s8 gAudioSoundMode; +extern_s volatile s32 gAudioTaskCountQ; +extern_s s32 gCurAudioFrameDmaCount; +extern_s s32 gAudioTaskIndexQ; +extern_s s32 gCurAiBuffIndex; +extern_s Acmd* gAbiCmdBuffs[2]; +extern_s Acmd* gCurAbiCmdBuffer; +extern_s SPTask* gAudioCurTask; +extern_s SPTask gAudioRspTasks[2]; +extern_s f32 gMaxTempoTvTypeFactors; +extern_s s32 gRefreshRate; +extern_s s16* gAiBuffers[3]; +extern_s s16 gAiBuffLengths[3]; +extern_s u32 gAudioRandom; +extern_s u32 D_80155D88; +extern_s volatile u32 gAudioResetTimer; + +extern_s u64 gAudioContextEnd[]; // wave_samples -extern s16* gWaveSamples[]; +extern_s s16* gWaveSamples[]; // note_data -extern f32 gBendPitchOneOctaveFrequencies[]; -extern f32 gBendPitchTwoSemitonesFrequencies[]; -extern f32 gPitchFrequencies[]; -extern u8 gDefaultShortNoteVelocityTable[]; -extern u8 gDefaultShortNoteGateTimeTable[]; -extern u16 gHaasEffectDelaySizes[64]; -extern EnvelopePoint gDefaultEnvelope[]; -extern NoteSubEu gZeroNoteSub; -extern NoteSubEu gDefaultNoteSub; -extern s16 gD_800DD200[]; -extern f32 gHeadsetPanVolume[128]; -extern f32 gStereoPanVolume[128]; -extern f32 gDefaultPanVolume[128]; - -#ifdef __cplusplus -} -#endif +extern_s f32 gBendPitchOneOctaveFrequencies[]; +extern_s f32 gBendPitchTwoSemitonesFrequencies[]; +extern_s f32 gPitchFrequencies[]; +extern_s u8 gDefaultShortNoteVelocityTable[]; +extern_s u8 gDefaultShortNoteGateTimeTable[]; +extern_s u16 gHaasEffectDelaySizes[64]; +extern_s EnvelopePoint gDefaultEnvelope[]; +extern_s NoteSubEu gZeroNoteSub; +extern_s NoteSubEu gDefaultNoteSub; +extern_s s16 gD_800DD200[]; +extern_s f32 gHeadsetPanVolume[128]; +extern_s f32 gStereoPanVolume[128]; +extern_s f32 gDefaultPanVolume[128]; #endif diff --git a/include/sf64context.h b/include/sf64context.h index fa990dd02..16fcd894f 100644 --- a/include/sf64context.h +++ b/include/sf64context.h @@ -6,349 +6,349 @@ #include "sf64object.h" #include "sf64player.h" -extern s32 gSceneId; -extern s32 gSceneSetup; -extern s32 gClearPlayerInfo; -extern s32 D_ctx_8017782C; -extern GameState gGameState; -extern s32 gNextGameStateTimer; -extern s32 gVsItemSpawnTimer; -extern OptionState gOptionMenuStatus; -extern s32 gPlayState; -extern s32 D_ctx_80177868; -extern LevelMode gLevelMode; -extern DrawMode gDrawMode; -extern s32 gPlayerNum; -extern s32 gCamCount; -extern s32 gTeamShields[6]; -extern s32 gSavedTeamShields[6]; -extern s32 gPrevPlanetSavedTeamShields[6]; -extern s32 gTeamDamage[6]; -extern u8 gMissionStatus; -extern f32 gGroundHeight; -extern f32 D_ctx_80177950; -extern f32 gPlayerTurnRate; -extern f32 gPlayerTurnStickMod; -extern f32 gCsCamEyeX; -extern f32 gCsCamEyeY; -extern f32 gCsCamEyeZ; -extern f32 gCsCamAtX; -extern f32 gCsCamAtY; -extern f32 gCsCamAtZ; -extern Vec3f gPlayCamEye; -extern Vec3f gPlayCamAt; -extern bool gExpertMode; -extern s32 D_ctx_80177A10[10]; -extern f32 D_ctx_80177A48[10]; -extern s32 gCsFrameCount; -extern u8 gDrawGround; -extern u8 gDrawBackdrop; // Venom Andross is the only level with multiple backdrops -extern u8 gAqDrawMode; -extern s32 gTitleState; -extern s32 gMainController; -extern s32 gMapState; -extern s32 gMissionNumber; -extern s32 gMissionTeamStatus[7]; -extern s32 gMissionHitCount[7]; -extern PlanetId gMissionPlanet[7]; -extern s32 gMissionMedal[7]; -extern s32 gPlanetPathStatus[]; -extern s32 gPrevPlanetTeamShields[6]; -extern s32 D_ctx_80177C58[6]; -extern u8 gOptionSoundMode; -extern s32 gVolumeSettings[3]; -extern u16 gBgmSeqId; -extern u8 gLevelType; -extern s32 gSavedObjectLoadIndex; -extern UNK_TYPE F_80177CA8; -extern f32 gSavedPathProgress; -extern UNK_TYPE F_80177CB8; -extern f32 gWaterLevel; -extern f32 gPathGroundScroll; -extern f32 gLastPathTexScroll; -extern f32 gPathTexScroll; -extern f32 gPathVelZ; -extern f32 gPathProgress; -extern f32 gRadioPortraitScaleY; -extern f32 gRadioTextBoxScaleY; -extern f32 gRadioMsgRadioId; -extern UNK_TYPE F_80177D80; -extern UNK_TYPE F_80177DE8; -extern s32 gGameFrameCount; -extern s32 gObjectLoadIndex; -extern s32 gPrevEventActorIndex; -extern s32 gFormationLeaderIndex; -extern s32 gRingPassCount; -extern Vec3f gFormationInitRot; -extern Vec3f gFormationInitPos; -extern UNK_TYPE F_80178020; -extern s32 gGroundClipMode; -extern LevelId gCurrentLevel; -extern s32 gLevelPhase; -extern s32 gBossActive; -extern bool gKillEventActors; -extern s32 gUseDynaFloor; -extern s32 gRadioState; -extern s32 gCurrentRadioPortrait; -extern s32 gRadioStateTimer; -extern s32 gRadioMouthTimer; -extern s32 D_ctx_801782C0; -extern s32 D_ctx_801782C8; -extern s32 D_ctx_801782D0; -extern s32 gRadioMsgCharIndex; -extern UNK_TYPE F_801782E0; -extern s32 gRadioMsgId; -extern UNK_TYPE F_801782F0; -extern bool gMsgCharIsPrinting; -extern bool gHideRadio; -extern u16* gRadioMsg; -extern ObjectInit* gLevelObjects; -extern s32 gFogRed; -extern s32 gFogGreen; -extern s32 gFogBlue; -extern s32 gFogAlpha; -extern s32 gFillScreenAlpha; -extern s32 gFillScreenRed; -extern s32 gFillScreenGreen; -extern s32 gFillScreenBlue; -extern s32 gFillScreenAlphaTarget; -extern s32 gFillScreenAlphaStep; -extern s32 gLight3R; -extern s32 gLight3G; -extern s32 gLight3B; -extern f32 gLight3Brightness; -extern f32 gLight3x; -extern f32 gLight3y; -extern f32 gLight3z; -extern s32 gFadeoutType; -extern u32 gPlayerGlareAlphas[4]; -extern s32 gPlayerGlareReds[4]; -extern s32 gPlayerGlareGreens[4]; -extern s32 gPlayerGlareBlues[4]; -extern s32 D_ctx_801783C0[4]; -extern f32 gSunViewX; -extern f32 gSunViewY; -extern s32 gFogNear; -extern s32 gFogFar; -extern UNK_TYPE F_801783E0[12]; -extern s32 gStarCount; -extern f32 gStarWarpDistortion; -extern f32 gCOComplete2CamRotY; -extern UNK_TYPE F_8017841C; -extern f32 gStarfieldX; -extern f32 gStarfieldY; -extern f32 gStarfieldRoll; -extern f32 gStarfieldScrollX; -extern f32 gStarfieldScrollY; -extern UNK_TYPE F_80178434; -extern UNK_TYPE F_80178438; -extern UNK_TYPE F_8017843C; -extern f32 gBossDeathCamAtX; -extern f32 gBossDeathCamAtY; -extern f32 gBossDeathCamAtZ; -extern f32 gCsTeamTargetsX[3]; -extern f32 gCsTeamTargetsY[3]; -extern f32 gCsTeamTargetsZ[3]; -extern f32 gCameraShakeY; -extern s32 gCameraShake; -extern s32 D_ctx_80178484; -extern bool gLoadLevelObjects; -extern UNK_TYPE F_8017848C; -extern UNK_TYPE F_80178490; -extern s32 D_ctx_80178494; -extern f32 gShotHitPosZ; -extern f32 gShotHitPosX; -extern f32 gShotHitPosY; -extern s32 gZoDodoraWaypointCount; -extern UNK_TYPE F_801784A8; -extern GroundType gGroundType; -extern UNK_TYPE F_801784B0; -extern UNK_TYPE F_801784B4; -extern f32 gLight1xRot; -extern f32 gLight1yRot; -extern f32 gLight1zRot; -extern f32 gLight1xRotTarget; -extern f32 gLight1yRotTarget; -extern f32 gLight1zRotTarget; -extern f32 gEnvLightxRot; -extern f32 gEnvLightyRot; -extern f32 gEnvLightzRot; -extern s32 gLight1x; -extern s32 gLight1y; -extern s32 gLight1z; -extern f32 gLight1rotStep; -extern f32 gLight2xRot; -extern f32 gLight2yRot; -extern f32 gLight2zRot; -extern f32 gLight2xRotTarget; -extern f32 gLight2yRotTarget; -extern f32 gLight2zRotTarget; -extern s32 gLight2x; -extern s32 gLight2y; -extern s32 gLight2z; -extern f32 gLight2rotStep; -extern UNK_TYPE F_801784514; -extern UNK_TYPE F_801784518; -extern UNK_TYPE F_80178451C; -extern f32 D_ctx_80178520; -extern f32 D_ctx_80178524; -extern f32 D_ctx_80178528; -extern UNK_TYPE F_80178452C; -extern UNK_TYPE F_801784530; -extern UNK_TYPE F_801784534; -extern f32 D_ctx_80178538; -extern f32 D_ctx_8017853C; -extern s32 gLight2colorStep; -extern s32 D_ctx_80178544; -extern s32 gLight1R; -extern s32 gLight1G; -extern s32 gLight1B; -extern s32 gAmbientR; -extern s32 gAmbientG; -extern s32 gAmbientB; -extern UNK_TYPE F_801784560; -extern s32 gLight2R; -extern s32 gLight2G; -extern s32 gLight2B; -extern s32 gLight2RTarget; -extern s32 gLight2GTarget; -extern s32 gLight2BTarget; -extern s32 D_ctx_80161A70; -extern s32 D_ctx_80161A74; -extern s32 D_ctx_80161A78; -extern s32 D_ctx_80161A7C; -extern s32 D_ctx_80161A80; -extern s32 D_ctx_80161A84; -extern s32 gGroundSurface; -extern s32 gSavedGroundSurface; -extern u8 gGoldRingCount[4]; -extern u8 gSavedGoldRingCount[4]; -extern s32 gHitCount; -extern s32 gSavedHitCount; -extern s16 gLifeCount[4]; -extern LaserStrength gLaserStrength[4]; -extern s32 gCullObjects; -extern UNK_TYPE F_80161AC0[16]; -extern Scenery gScenery[50]; -extern Sprite gSprites[40]; -extern Actor gActors[60]; -extern Boss gBosses[4]; -extern Effect gEffects[100]; -extern Item gItems[20]; -extern PlayerShot gPlayerShots[16]; -extern TexturedLine gTexturedLines[100]; -extern RadarMark gRadarMarks[65]; -extern BonusText gBonusText[10]; -extern s32 gMeMoraStatus[2]; -extern f32 gMeMoraXpos[2][100]; -extern f32 gMeMoraYpos[2][100]; -extern f32 gMeMoraZpos[2][100]; -extern f32 gMeMoraXrot[2][100]; -extern f32 gMeMoraYrot[2][100]; -extern f32 gMeMoraZrot[2][100]; -extern u16 gEnemyShotSpeed; -extern u8 gShowLevelClearStatusScreen; -extern s32 gLevelStartStatusScreenTimer; -extern s32 gLevelClearScreenTimer; -extern s32 gBossHealthBar; -extern s32 D_ctx_80177850; -extern s32 D_ctx_80177858[4]; -extern s32 gPlayerForms[4]; -extern s32 gHandicap[4]; -extern VsStage gVersusStage; -extern s32 gVsPointsToWin; -extern s32 gVsMatchType; -extern s32 gVsTimeTrialLimit; -extern bool gVersusMode; -extern u16 gBoostButton[4]; -extern u16 gBrakeButton[4]; -extern u16 gShootButton[4]; -extern u16 gBombButton[4]; -extern f32 D_ctx_80177958[4]; -extern s32 gTeamLowHealthMsgTimer; -extern OSContPad* gInputHold; -extern OSContPad* gInputPress; -extern u8* gControllerRumble; -extern s32 D_ctx_80177990[4]; -extern f32 D_ctx_801779A8[4]; -extern u8 gPauseEnabled; -extern s32 gChargeTimers[4]; -extern f32 gPathVelX; -extern f32 gPathVelY; -extern s32 gUturnDownTimers[4]; -extern s32 gUturnBrakeTimers[4]; -extern s32 gLoopDownTimers[4]; -extern s32 gLoopBoostTimers[4]; -extern f32 gMuzzleFlashScale[4]; -extern f32 gShieldAlpha[4]; -extern s32 gHasShield[4]; -extern s32 gShieldTimer[4]; -extern s32 gVsLockOnTimers[4][4]; -extern u8 gStartAndrossFightTimer; -extern u8 gSoShieldsEmpty; -extern u8 gCoUturnCount; -extern u8 gGreatFoxIntact; -extern u8 gTiStartLandmaster; -extern u16 gControllerRumbleTimers[4]; -extern u16 gPlayerScores[4]; -extern s32 gCircleWipeFrame; -extern s32 gFovYMode; -extern s32 gTraining360MsgTimer; -extern s32 gTraining360MsgIndex; -extern s32 D_ctx_80177C94; -extern s32 D_ctx_80177C9C; -extern s32 D_ctx_80177CA4; -extern s32 D_ctx_80177CAC; -extern s32 D_ctx_80177CB4; -extern s32 D_ctx_80177CBC; -extern s32 D_ctx_80177CC4; -extern s32 gStarWolfTeamAlive[6]; -extern s32 gSavedStarWolfTeamAlive[6]; -extern s32 gRightWingHealth[4]; -extern s32 gLeftWingHealth[4]; -extern s32 gRightWingFlashTimer[4]; -extern s32 gLeftWingFlashTimer[4]; -extern s32 gRightWingDebrisTimer[4]; -extern s32 gLeftWingDebrisTimer[4]; -extern s32 gBombCount[4]; -extern s32 gVsPoints[4]; -extern s32 gVsKills[4][10]; -extern s32 gVsMatchWon; -extern bool gVsMatchStart; -extern bool gChangeTo360; -extern Vec3f gTeamArrowsViewPos[10]; -extern f32 D_ctx_80177F20[65]; -extern f32 D_ctx_80178028[65]; -extern f32 D_ctx_80178130[65]; -// extern u8 D_ctx_80178238[65]; -extern Player* gPlayer; -extern f32* gStarOffsetsX; -extern f32* gStarOffsetsY; -extern u32* gStarFillColors; -extern UNK_TYPE F_801782A0; -extern Scenery360* gScenery360; -extern UNK_TYPE F_801782B0; -extern s32 gDrawSmallRocks; -extern s32 D_ctx_801782BC; -extern PosRot* gZoDodoraPosRots; -extern f32* D_ctx_801782CC; -extern f32* D_ctx_801782D4; -extern f32* D_ctx_801782DC; -extern f32* D_ctx_801782E4; -extern f32* D_ctx_801782EC; -extern UNK_TYPE F_801782F4; -extern s32 gDynaFloorTimer; -extern UNK_TYPE F_80178304; -extern UNK_TYPE F_8017830C; -extern UNK_TYPE F_80178314; -extern UNK_TYPE F_80178318; -extern UNK_TYPE F_8017831C; -extern UNK_TYPE F_80178324; -extern UNK_TYPE F_8017832C; -extern UNK_TYPE F_80178334; -extern UNK_TYPE F_8017833C; -extern UNK_TYPE F_80178344; -extern UNK_TYPE F_8017834C; -extern bool gCamera1Skipped; +extern_s s32 gSceneId; +extern_s s32 gSceneSetup; +extern_s s32 gClearPlayerInfo; +extern_s bool D_ctx_8017782C; +extern_s GameState gGameState; +extern_s s32 gNextGameStateTimer; +extern_s s32 gVsItemSpawnTimer; +extern_s OptionState gOptionMenuStatus; +extern_s s32 gPlayState; +extern_s s32 D_ctx_80177868; +extern_s LevelMode gLevelMode; +extern_s DrawMode gDrawMode; +extern_s s32 gPlayerNum; +extern_s s32 gCamCount; +extern_s s32 gTeamShields[6]; +extern_s s32 gSavedTeamShields[6]; +extern_s s32 gPrevPlanetSavedTeamShields[6]; +extern_s s32 gTeamDamage[6]; +extern_s u8 gMissionStatus; +extern_s f32 gGroundHeight; +extern_s f32 D_ctx_80177950; +extern_s f32 gPlayerTurnRate; +extern_s f32 gPlayerTurnStickMod; +extern_s f32 gCsCamEyeX; +extern_s f32 gCsCamEyeY; +extern_s f32 gCsCamEyeZ; +extern_s f32 gCsCamAtX; +extern_s f32 gCsCamAtY; +extern_s f32 gCsCamAtZ; +extern_s Vec3f gPlayCamEye; +extern_s Vec3f gPlayCamAt; +extern_s bool gExpertMode; +extern_s s32 D_ctx_80177A10[10]; +extern_s f32 D_ctx_80177A48[10]; +extern_s s32 gCsFrameCount; +extern_s u8 gDrawGround; +extern_s u8 gDrawBackdrop; // Venom Andross is the only level with multiple backdrops +extern_s u8 gAqDrawMode; +extern_s s32 gTitleState; +extern_s s32 gMainController; +extern_s s32 gMapState; +extern_s s32 gMissionNumber; +extern_s s32 gMissionTeamStatus[7]; +extern_s s32 gMissionHitCount[7]; +extern_s PlanetId gMissionPlanet[7]; +extern_s s32 gMissionMedal[7]; +extern_s s32 gPlanetPathStatus[]; +extern_s s32 gPrevPlanetTeamShields[6]; +extern_s s32 D_ctx_80177C58[6]; +extern_s u8 gOptionSoundMode; +extern_s s32 gVolumeSettings[3]; +extern_s u16 gBgmSeqId; +extern_s u8 gLevelType; +extern_s s32 gSavedObjectLoadIndex; +extern_s UNK_TYPE F_80177CA8; +extern_s f32 gSavedPathProgress; +extern_s UNK_TYPE F_80177CB8; +extern_s f32 gWaterLevel; +extern_s f32 gPathGroundScroll; +extern_s f32 gLastPathTexScroll; +extern_s f32 gPathTexScroll; +extern_s f32 gPathVelZ; +extern_s f32 gPathProgress; +extern_s f32 gRadioPortraitScaleY; +extern_s f32 gRadioTextBoxScaleY; +extern_s f32 gRadioMsgRadioId; +extern_s UNK_TYPE F_80177D80; +extern_s UNK_TYPE F_80177DE8; +extern_s s32 gGameFrameCount; +extern_s s32 gObjectLoadIndex; +extern_s s32 gPrevEventActorIndex; +extern_s s32 gFormationLeaderIndex; +extern_s s32 gRingPassCount; +extern_s Vec3f gFormationInitRot; +extern_s Vec3f gFormationInitPos; +extern_s UNK_TYPE F_80178020; +extern_s s32 gGroundClipMode; +extern_s LevelId gCurrentLevel; +extern_s s32 gLevelPhase; +extern_s s32 gBossActive; +extern_s bool gKillEventActors; +extern_s s32 gUseDynaFloor; +extern_s s32 gRadioState; +extern_s s32 gCurrentRadioPortrait; +extern_s s32 gRadioStateTimer; +extern_s s32 gRadioMouthTimer; +extern_s s32 D_ctx_801782C0; +extern_s s32 D_ctx_801782C8; +extern_s s32 D_ctx_801782D0; +extern_s s32 gRadioMsgCharIndex; +extern_s UNK_TYPE F_801782E0; +extern_s s32 gRadioMsgId; +extern_s UNK_TYPE F_801782F0; +extern_s bool gMsgCharIsPrinting; +extern_s bool gHideRadio; +extern_s u16* gRadioMsg; +extern_s ObjectInit* gLevelObjects; +extern_s s32 gFogRed; +extern_s s32 gFogGreen; +extern_s s32 gFogBlue; +extern_s s32 gFogAlpha; +extern_s s32 gFillScreenAlpha; +extern_s s32 gFillScreenRed; +extern_s s32 gFillScreenGreen; +extern_s s32 gFillScreenBlue; +extern_s s32 gFillScreenAlphaTarget; +extern_s s32 gFillScreenAlphaStep; +extern_s s32 gLight3R; +extern_s s32 gLight3G; +extern_s s32 gLight3B; +extern_s f32 gLight3Brightness; +extern_s f32 gLight3x; +extern_s f32 gLight3y; +extern_s f32 gLight3z; +extern_s s32 gFadeoutType; +extern_s u32 gPlayerGlareAlphas[4]; +extern_s s32 gPlayerGlareReds[4]; +extern_s s32 gPlayerGlareGreens[4]; +extern_s s32 gPlayerGlareBlues[4]; +extern_s UNK_TYPE D_ctx_801783C0[4]; +extern_s f32 gSunViewX; +extern_s f32 gSunViewY; +extern_s s32 gFogNear; +extern_s s32 gFogFar; +extern_s UNK_TYPE F_801783E0[12]; +extern_s s32 gStarCount; +extern_s f32 gStarWarpDistortion; +extern_s f32 gCOComplete2CamRotY; +extern_s UNK_TYPE F_8017841C; +extern_s f32 gStarfieldX; +extern_s f32 gStarfieldY; +extern_s f32 gStarfieldRoll; +extern_s f32 gStarfieldScrollX; +extern_s f32 gStarfieldScrollY; +extern_s UNK_TYPE F_80178434; +extern_s UNK_TYPE F_80178438; +extern_s UNK_TYPE F_8017843C; +extern_s f32 gBossDeathCamAtX; +extern_s f32 gBossDeathCamAtY; +extern_s f32 gBossDeathCamAtZ; +extern_s f32 gCsTeamTargetsX[3]; +extern_s f32 gCsTeamTargetsY[3]; +extern_s f32 gCsTeamTargetsZ[3]; +extern_s f32 gCameraShakeY; +extern_s s32 gCameraShake; +extern_s s32 D_ctx_80178484; +extern_s bool gLoadLevelObjects; +extern_s UNK_TYPE F_8017848C; +extern_s UNK_TYPE F_80178490; +extern_s s32 D_ctx_80178494; +extern_s f32 gShotHitPosZ; +extern_s f32 gShotHitPosX; +extern_s f32 gShotHitPosY; +extern_s s32 gZoDodoraWaypointCount; +extern_s UNK_TYPE F_801784A8; +extern_s GroundType gGroundType; +extern_s UNK_TYPE F_801784B0; +extern_s UNK_TYPE F_801784B4; +extern_s f32 gLight1xRot; +extern_s f32 gLight1yRot; +extern_s f32 gLight1zRot; +extern_s f32 gLight1xRotTarget; +extern_s f32 gLight1yRotTarget; +extern_s f32 gLight1zRotTarget; +extern_s f32 gEnvLightxRot; +extern_s f32 gEnvLightyRot; +extern_s f32 gEnvLightzRot; +extern_s s32 gLight1x; +extern_s s32 gLight1y; +extern_s s32 gLight1z; +extern_s f32 gLight1rotStep; +extern_s f32 gLight2xRot; +extern_s f32 gLight2yRot; +extern_s f32 gLight2zRot; +extern_s f32 gLight2xRotTarget; +extern_s f32 gLight2yRotTarget; +extern_s f32 gLight2zRotTarget; +extern_s s32 gLight2x; +extern_s s32 gLight2y; +extern_s s32 gLight2z; +extern_s f32 gLight2rotStep; +extern_s UNK_TYPE F_801784514; +extern_s UNK_TYPE F_801784518; +extern_s UNK_TYPE F_80178451C; +extern_s f32 D_ctx_80178520; +extern_s f32 D_ctx_80178524; +extern_s f32 D_ctx_80178528; +extern_s UNK_TYPE F_80178452C; +extern_s UNK_TYPE F_801784530; +extern_s UNK_TYPE F_801784534; +extern_s f32 D_ctx_80178538; +extern_s f32 D_ctx_8017853C; +extern_s s32 gLight2colorStep; +extern_s s32 D_ctx_80178544; +extern_s s32 gLight1R; +extern_s s32 gLight1G; +extern_s s32 gLight1B; +extern_s s32 gAmbientR; +extern_s s32 gAmbientG; +extern_s s32 gAmbientB; +extern_s UNK_TYPE F_801784560; +extern_s s32 gLight2R; +extern_s s32 gLight2G; +extern_s s32 gLight2B; +extern_s s32 gLight2RTarget; +extern_s s32 gLight2GTarget; +extern_s s32 gLight2BTarget; +extern_s s32 D_ctx_80161A70; +extern_s s32 D_ctx_80161A74; +extern_s s32 D_ctx_80161A78; +extern_s s32 D_ctx_80161A7C; +extern_s s32 D_ctx_80161A80; +extern_s s32 D_ctx_80161A84; +extern_s GroundSurface gGroundSurface; +extern_s GroundSurface gSavedGroundSurface; +extern_s u8 gGoldRingCount[4]; +extern_s u8 gSavedGoldRingCount[4]; +extern_s s32 gHitCount; +extern_s s32 gSavedHitCount; +extern_s s16 gLifeCount[4]; +extern_s LaserStrength gLaserStrength[4]; +extern_s s32 gCullObjects; +extern_s UNK_TYPE F_80161AC0[16]; +extern_s Scenery gScenery[50]; +extern_s Sprite gSprites[40]; +extern_s Actor gActors[60]; +extern_s Boss gBosses[4]; +extern_s Effect gEffects[100]; +extern_s Item gItems[20]; +extern_s PlayerShot gPlayerShots[16]; +extern_s TexturedLine gTexturedLines[100]; +extern_s RadarMark gRadarMarks[65]; +extern_s BonusText gBonusText[10]; +extern_s s32 gMeMoraStatus[2]; +extern_s f32 gMeMoraXpos[2][100]; +extern_s f32 gMeMoraYpos[2][100]; +extern_s f32 gMeMoraZpos[2][100]; +extern_s f32 gMeMoraXrot[2][100]; +extern_s f32 gMeMoraYrot[2][100]; +extern_s f32 gMeMoraZrot[2][100]; +extern_s u16 gEnemyShotSpeed; +extern_s u8 gShowLevelClearStatusScreen; +extern_s s32 gLevelStartStatusScreenTimer; +extern_s s32 gLevelClearScreenTimer; +extern_s s32 gBossHealthBar; +extern_s s32 D_ctx_80177850; +extern_s s32 D_ctx_80177858[4]; +extern_s PlayerForm gPlayerForms[4]; +extern_s s32 gHandicap[4]; +extern_s VsStage gVersusStage; +extern_s s32 gVsPointsToWin; +extern_s s32 gVsMatchType; +extern_s s32 gVsTimeTrialLimit; +extern_s bool gVersusMode; +extern_s u16 gBoostButton[4]; +extern_s u16 gBrakeButton[4]; +extern_s u16 gShootButton[4]; +extern_s u16 gBombButton[4]; +extern_s f32 D_ctx_80177958[4]; +extern_s s32 gTeamLowHealthMsgTimer; +extern_s OSContPad* gInputHold; +extern_s OSContPad* gInputPress; +extern_s u8* gControllerRumble; +extern_s s32 D_ctx_80177990[4]; +extern_s f32 D_ctx_801779A8[4]; +extern_s u8 gPauseEnabled; +extern_s s32 gChargeTimers[4]; +extern_s f32 gPathVelX; +extern_s f32 gPathVelY; +extern_s s32 gUturnDownTimers[4]; +extern_s s32 gUturnBrakeTimers[4]; +extern_s s32 gLoopDownTimers[4]; +extern_s s32 gLoopBoostTimers[4]; +extern_s f32 gMuzzleFlashScale[4]; +extern_s f32 gShieldAlpha[4]; +extern_s s32 gHasShield[4]; +extern_s s32 gShieldTimer[4]; +extern_s s32 gVsLockOnTimers[4][4]; +extern_s u8 gStartAndrossFightTimer; +extern_s u8 gSoShieldsEmpty; +extern_s u8 gCoUturnCount; +extern_s u8 gGreatFoxIntact; +extern_s u8 gTiStartLandmaster; +extern_s u16 gControllerRumbleTimers[4]; +extern_s u16 gPlayerScores[4]; +extern_s s32 gCircleWipeFrame; +extern_s s32 gFovYMode; +extern_s s32 gTraining360MsgTimer; +extern_s s32 gTraining360MsgIndex; +extern_s s32 D_ctx_80177C94; +extern_s s32 D_ctx_80177C9C; +extern_s s32 D_ctx_80177CA4; +extern_s s32 D_ctx_80177CAC; +extern_s s32 D_ctx_80177CB4; +extern_s s32 D_ctx_80177CBC; +extern_s s32 D_ctx_80177CC4; +extern_s s32 gStarWolfTeamAlive[6]; +extern_s s32 gSavedStarWolfTeamAlive[6]; +extern_s s32 gRightWingHealth[4]; +extern_s s32 gLeftWingHealth[4]; +extern_s s32 gRightWingFlashTimer[4]; +extern_s s32 gLeftWingFlashTimer[4]; +extern_s s32 gRightWingDebrisTimer[4]; +extern_s s32 gLeftWingDebrisTimer[4]; +extern_s s32 gBombCount[4]; +extern_s s32 gVsPoints[4]; +extern_s s32 gVsKills[4][10]; +extern_s s32 gVsMatchWon; +extern_s bool gVsMatchStart; +extern_s bool gChangeTo360; +extern_s Vec3f gTeamArrowsViewPos[10]; +extern_s f32 D_ctx_80177F20[65]; +extern_s f32 D_ctx_80178028[65]; +extern_s f32 D_ctx_80178130[65]; +// extern_s u8 D_ctx_80178238[65]; +extern_s Player* gPlayer; +extern_s f32* gStarOffsetsX; +extern_s f32* gStarOffsetsY; +extern_s u32* gStarFillColors; +extern_s UNK_TYPE F_801782A0; +extern_s Scenery360* gScenery360; +extern_s UNK_TYPE F_801782B0; +extern_s s32 gDrawSmallRocks; +extern_s s32 D_ctx_801782BC; +extern_s PosRot* gZoDodoraPosRots; +extern_s f32* D_ctx_801782CC; +extern_s f32* D_ctx_801782D4; +extern_s f32* D_ctx_801782DC; +extern_s f32* D_ctx_801782E4; +extern_s f32* D_ctx_801782EC; +extern_s UNK_TYPE F_801782F4; +extern_s s32 gDynaFloorTimer; +extern_s UNK_TYPE F_80178304; +extern_s UNK_TYPE F_8017830C; +extern_s UNK_TYPE F_80178314; +extern_s UNK_TYPE F_80178318; +extern_s UNK_TYPE F_8017831C; +extern_s UNK_TYPE F_80178324; +extern_s UNK_TYPE F_8017832C; +extern_s UNK_TYPE F_80178334; +extern_s UNK_TYPE F_8017833C; +extern_s UNK_TYPE F_80178344; +extern_s UNK_TYPE F_8017834C; +extern_s bool gCamera1Skipped; #endif diff --git a/include/sf64math.h b/include/sf64math.h index 19b0ddbc8..9f5cf422c 100644 --- a/include/sf64math.h +++ b/include/sf64math.h @@ -4,6 +4,7 @@ #include #include "libc/math.h" #include +#include "macros.h" #define MTXF_NEW 0 #define MTXF_APPLY 1 @@ -55,20 +56,20 @@ typedef union { // u64 force_struct_alignment; } Matrix; // size = 0x40 +extern_s Mtx gIdentityMtx; // 800C4620 +extern_s Matrix gIdentityMatrix; //800C4660 + +extern_s Matrix* gGfxMatrix; +extern_s Matrix sGfxMatrixStack[]; +extern_s Matrix* gCalcMatrix; +extern_s Matrix sCalcMatrixStack[]; +extern_s Matrix* gInterpolationMatrix; +extern_s Matrix sInterpolationMatrixStack[]; + #ifdef __cplusplus extern "C" { #endif -extern Mtx gIdentityMtx; // 800C4620 -extern Matrix gIdentityMatrix; //800C4660 - -extern Matrix* gGfxMatrix; -extern Matrix sGfxMatrixStack[]; -extern Matrix* gCalcMatrix; -extern Matrix sCalcMatrixStack[]; -extern Matrix* gInterpolationMatrix; -extern Matrix sInterpolationMatrixStack[]; - f32 Math_ModF(f32 value, f32 mod); void Rand_Init(void); f32 Rand_ZeroOne(void); diff --git a/include/sf64save.h b/include/sf64save.h index dd1ce7e2e..f866311c6 100644 --- a/include/sf64save.h +++ b/include/sf64save.h @@ -65,6 +65,10 @@ typedef struct { /* 0x100 */ Save backup; } SaveFile; // size = 0x200 +#ifdef __cplusplus +extern "C" { +#endif + s32 Save_Write(void); s32 Save_Read(void); @@ -74,9 +78,13 @@ bool Save_WriteData(void); s32 Save_WriteEeprom(SaveFile*); s32 Save_ReadEeprom(SaveFile*); -extern SaveFile gSaveIOBuffer; -extern SaveFile sPrevSaveData; -extern Save gDefaultSave; -extern SaveFile gSaveFile; +#ifdef __cplusplus +} +#endif + +extern_s SaveFile gSaveIOBuffer; +extern_s SaveFile sPrevSaveData; +extern_s Save gDefaultSave; +extern_s SaveFile gSaveFile; #endif diff --git a/include/sf64thread.h b/include/sf64thread.h index 0f1900dce..b736b6a1b 100644 --- a/include/sf64thread.h +++ b/include/sf64thread.h @@ -99,92 +99,92 @@ typedef enum { /* 16 */ SI_CONT_READ_DONE, } SerialMesg; -extern OSContPad gControllerHold[4]; -extern OSContPad gControllerPress[4]; -extern u8 gControllerPlugged[4]; -extern u32 gControllerLock; -extern u8 gControllerRumbleEnabled[4]; -extern OSContPad sNextController[4]; // -extern OSContPad sPrevController[4]; // -extern OSContStatus sControllerStatus[4]; // -extern OSPfs sControllerMotor[4]; // - -extern u8 gAudioThreadStack[0x1000]; // 800DDAA0 -extern OSThread gGraphicsThread; // 800DEAA0 -extern u8 gGraphicsThreadStack[0x1000]; // 800DEC50 -extern OSThread gTimerThread; // 800DFC50 -extern u8 gTimerThreadStack[0x1000]; // 800DFE00 -extern OSThread gSerialThread; // 800E0E00 -extern u8 gSerialThreadStack[0x1000]; // 800E0FB0 - -extern SPTask* gCurrentTask; -extern SPTask* sAudioTasks[1]; -extern SPTask* sGfxTasks[2]; +extern_s OSContPad gControllerHold[4]; +extern_s OSContPad gControllerPress[4]; +extern_s u8 gControllerPlugged[4]; +extern_s u32 gControllerLock; +extern_s u8 gControllerRumbleEnabled[4]; +extern_s OSContPad sNextController[4]; // +extern_s OSContPad sPrevController[4]; // +extern_s OSContStatus sControllerStatus[4]; // +extern_s OSPfs sControllerMotor[4]; // + +extern_s u8 gAudioThreadStack[0x1000]; // 800DDAA0 +extern_s OSThread gGraphicsThread; // 800DEAA0 +extern_s u8 gGraphicsThreadStack[0x1000]; // 800DEC50 +extern_s OSThread gTimerThread; // 800DFC50 +extern_s u8 gTimerThreadStack[0x1000]; // 800DFE00 +extern_s OSThread gSerialThread; // 800E0E00 +extern_s u8 gSerialThreadStack[0x1000]; // 800E0FB0 + +extern_s SPTask* gCurrentTask; +extern_s SPTask* sAudioTasks[1]; +extern_s SPTask* sGfxTasks[2]; #ifdef AVOID_UB -extern SPTask* sNewAudioTasks[2]; +extern_s SPTask* sNewAudioTasks[2]; #else -extern SPTask* sNewAudioTasks[1]; +extern_s SPTask* sNewAudioTasks[1]; #endif -extern SPTask* sNewGfxTasks[2]; -extern u32 gSegments[16]; // 800E1FD0 -extern OSMesgQueue gPiMgrCmdQueue; // 800E2010 -extern OSMesg sPiMgrCmdBuff[50]; // 800E2028 - -extern OSMesgQueue gDmaMesgQueue; -extern OSMesg sDmaMsgBuff[1]; -extern OSIoMesg gDmaIOMsg; -extern OSMesgQueue gSerialEventQueue; -extern OSMesg sSerialEventBuff[1]; -extern OSMesgQueue gMainThreadMesgQueue; -extern OSMesg sMainThreadMsgBuff[32]; -extern OSMesgQueue gTaskMesgQueue; -extern OSMesg sTaskMsgBuff[16]; -extern OSMesgQueue gAudioVImesgQueue; -extern OSMesg sAudioVImsgBuff[1]; -extern OSMesgQueue gAudioTaskMesgQueue; -extern OSMesg sAudioTaskMsgBuff[1]; -extern OSMesgQueue gGfxVImesgQueue; -extern OSMesg sGfxVImsgBuff[4]; -extern OSMesgQueue gGfxTaskMesgQueue; -extern OSMesg sGfxTaskMsgBuff[2]; -extern OSMesgQueue gSerialThreadMesgQueue; -extern OSMesg sSerialThreadMsgBuff[8]; -extern OSMesgQueue gControllerMesgQueue; -extern OSMesg sControllerMsgBuff[1]; -extern OSMesgQueue gSaveMesgQueue; -extern OSMesg sSaveMsgBuff[1]; -extern OSMesgQueue gTimerTaskMesgQueue; -extern OSMesg sTimerTaskMsgBuff[16]; -extern OSMesgQueue gTimerWaitMesgQueue; -extern OSMesg sTimerWaitMsgBuff[1]; - -extern GfxPool gGfxPools[2]; // 800E23B0 - -extern GfxPool* gGfxPool; -extern SPTask* gGfxTask; -extern Vp* gViewport; -extern Mtx* gGfxMtx; -extern Gfx* gUnkDisp1; -extern Gfx* gMasterDisp; -extern Gfx* gUnkDisp2; -extern Lightsn* gLight; -extern FrameBuffer* gFrameBuffer; -extern u16* gTextureRender; - -extern u8 gVIsPerFrame; -extern u32 gSysFrameCount; -extern u8 gStartNMI; -extern u8 gStopTasks; -extern u8 gControllerRumbleFlags[4]; -extern u16 gFillScreenColor; -extern u16 gFillScreen; - -extern u8 gUnusedStack[0x1000]; -extern OSThread sIdleThread; // 80138E90 -extern u8 sIdleThreadStack[0x1000]; // 801390A0 -extern OSThread gMainThread; // 8013A040 -extern u8 sMainThreadStack[0x1000]; // 8013A1F0 -extern OSThread gAudioThread; //8013B1F0 +extern_s SPTask* sNewGfxTasks[2]; +extern_s u32 gSegments[16]; // 800E1FD0 +extern_s OSMesgQueue gPiMgrCmdQueue; // 800E2010 +extern_s OSMesg sPiMgrCmdBuff[50]; // 800E2028 + +extern_s OSMesgQueue gDmaMesgQueue; +extern_s OSMesg sDmaMsgBuff[1]; +extern_s OSIoMesg gDmaIOMsg; +extern_s OSMesgQueue gSerialEventQueue; +extern_s OSMesg sSerialEventBuff[1]; +extern_s OSMesgQueue gMainThreadMesgQueue; +extern_s OSMesg sMainThreadMsgBuff[32]; +extern_s OSMesgQueue gTaskMesgQueue; +extern_s OSMesg sTaskMsgBuff[16]; +extern_s OSMesgQueue gAudioVImesgQueue; +extern_s OSMesg sAudioVImsgBuff[1]; +extern_s OSMesgQueue gAudioTaskMesgQueue; +extern_s OSMesg sAudioTaskMsgBuff[1]; +extern_s OSMesgQueue gGfxVImesgQueue; +extern_s OSMesg sGfxVImsgBuff[4]; +extern_s OSMesgQueue gGfxTaskMesgQueue; +extern_s OSMesg sGfxTaskMsgBuff[2]; +extern_s OSMesgQueue gSerialThreadMesgQueue; +extern_s OSMesg sSerialThreadMsgBuff[8]; +extern_s OSMesgQueue gControllerMesgQueue; +extern_s OSMesg sControllerMsgBuff[1]; +extern_s OSMesgQueue gSaveMesgQueue; +extern_s OSMesg sSaveMsgBuff[1]; +extern_s OSMesgQueue gTimerTaskMesgQueue; +extern_s OSMesg sTimerTaskMsgBuff[16]; +extern_s OSMesgQueue gTimerWaitMesgQueue; +extern_s OSMesg sTimerWaitMsgBuff[1]; + +extern_s GfxPool gGfxPools[2]; // 800E23B0 + +extern_s GfxPool* gGfxPool; +extern_s SPTask* gGfxTask; +extern_s Vp* gViewport; +extern_s Mtx* gGfxMtx; +extern_s Gfx* gUnkDisp1; +extern_s Gfx* gMasterDisp; +extern_s Gfx* gUnkDisp2; +extern_s Lightsn* gLight; +extern_s FrameBuffer* gFrameBuffer; +extern_s u16* gTextureRender; + +extern_s u8 gVIsPerFrame; +extern_s u32 gSysFrameCount; +extern_s u8 gStartNMI; +extern_s u8 gStopTasks; +extern_s u8 gControllerRumbleFlags[4]; +extern_s u16 gFillScreenColor; +extern_s u16 gFillScreen; + +extern_s u8 gUnusedStack[0x1000]; +extern_s OSThread sIdleThread; // 80138E90 +extern_s u8 sIdleThreadStack[0x1000]; // 801390A0 +extern_s OSThread gMainThread; // 8013A040 +extern_s u8 sMainThreadStack[0x1000]; // 8013A1F0 +extern_s OSThread gAudioThread; //8013B1F0 #define MESG_QUEUE_EMPTY -1 diff --git a/include/sfx.h b/include/sfx.h index b7ed67c8b..d28ea3e58 100644 --- a/include/sfx.h +++ b/include/sfx.h @@ -3,9 +3,13 @@ #include "sys.h" -extern f32 gDefaultSfxSource[]; -extern f32 gDefaultMod; -extern s8 gDefaultReverb; +extern_s f32 gDefaultSfxSource[]; +extern_s f32 gDefaultMod; +extern_s s8 gDefaultReverb; + +#ifdef __cplusplus +extern "C" { +#endif void Audio_PlaySfx(u32 sfxId, f32* sfxSource, u8 token, f32* freqMod, f32* volMod, s8* reverbAdd); void Audio_KillSfxByBank(u8 bankId); @@ -35,6 +39,10 @@ void Audio_PlayMapMenuSfx(u8 active); void Audio_KillAllSfx(void); void Audio_SetVoiceLanguage(u8 language); +#ifdef __cplusplus +} +#endif + #define AUDIO_PLAY_SFX(sfxId, srcPos, token) (Audio_PlaySfx((sfxId),(srcPos),(token),&gDefaultMod,&gDefaultMod,&gDefaultReverb)) #define SFX_FLAG_18 (1 << 18) // makes distance ignore z position? probably more diff --git a/include/sys.h b/include/sys.h index 55bbaffce..6f376dd50 100644 --- a/include/sys.h +++ b/include/sys.h @@ -40,24 +40,24 @@ void Mio0_Decompress(void* header, u8* dst); void Game_Initialize(void); void Game_Update(void); -extern bool gShowReticles[]; -extern bool D_game_800D2870; +extern_s bool gShowReticles[]; +extern_s bool D_game_800D2870; -extern f32 gNextVsViewScale; -extern f32 gVsViewScale; -extern s32 gPlayerInactive[4]; -extern s32 gVsMenuSelection; -extern u8 gShowHud; -extern u16 gNextLevelPhase; -extern u16 gNextLevel; -extern u16 gNextGameState; -extern u16 gLastGameState; -extern u16 gBgColor; -extern u8 gBlurAlpha; -extern u8 gGameStandby; -extern f32 gFovY; -extern f32 gProjectNear; -extern f32 gProjectFar; +extern_s f32 gNextVsViewScale; +extern_s f32 gVsViewScale; +extern_s s32 gPlayerInactive[4]; +extern_s s32 gVsMenuSelection; +extern_s u8 gShowHud; +extern_s u16 gNextLevelPhase; +extern_s u16 gNextLevel; +extern_s u16 gNextGameState; +extern_s u16 gLastGameState; +extern_s u16 gBgColor; +extern_s u8 gBlurAlpha; +extern_s u8 gGameStandby; +extern_s f32 gFovY; +extern_s f32 gProjectNear; +extern_s f32 gProjectFar; typedef enum OptionState { OPTION_WAIT, diff --git a/include/variables.h b/include/variables.h index b1accc52d..69b7427a2 100644 --- a/include/variables.h +++ b/include/variables.h @@ -7,202 +7,202 @@ #include "sf64player.h" // fox_360 -extern s32 gAllRangeSpawnEvent; +extern_s s32 gAllRangeSpawnEvent; // fox_bg -extern u16 gStarColors[16]; +extern_s u16 gStarColors[16]; // fox_boss -extern s32 gBossBgms[]; +extern_s s32 gBossBgms[]; // fox_tank -extern Vec3f D_tank_800C9F2C; +extern_s Vec3f D_tank_800C9F2C; // fox_display -extern s32 D_display_800CA220; -extern f32 gCamDistortion; -extern Actor* gTeamHelpActor; -extern s32 gTeamHelpTimer; +extern_s s32 D_display_800CA220; +extern_s f32 gCamDistortion; +extern_s Actor* gTeamHelpActor; +extern_s s32 gTeamHelpTimer; // fox_edata -extern f32 gZoEnergyBallHitbox[]; -extern f32 gCubeHitbox100[]; -extern f32 gCubeHitbox150[]; -extern f32 gCubeHitbox200[]; -extern f32 gCubeHitbox300[]; -extern f32 gCubeHitbox400[]; -extern f32 gItemRingCheckHitbox[]; -extern f32 gNoHitbox[]; -extern f32 gItemCheckpointHitbox[]; -extern f32 gItemSupplyRingHitbox[]; -extern f32 gMeteoWarpHitbox[]; -extern f32 gItemPathChangeHitbox[]; -extern f32 gItemLasersHitbox[]; -extern f32 gItemBombHitbox[]; -extern f32 gActorMissileSeekHitbox[]; -extern f32 gMeMoraHitbox[]; -extern f32 gTeamHitbox[]; -extern f32 gActorAllRangeHItbox[]; -extern f32 aWzMeteor1Hitbox[]; -extern f32 aWzGateHitbox[]; -extern f32 aWzPillar1Hitbox[]; -extern f32 aWzPillar2Hitbox[]; -extern ObjectInfo gObjectInfo[]; -extern f32* D_edata_800CF964[]; +extern_s f32 gZoEnergyBallHitbox[]; +extern_s f32 gCubeHitbox100[]; +extern_s f32 gCubeHitbox150[]; +extern_s f32 gCubeHitbox200[]; +extern_s f32 gCubeHitbox300[]; +extern_s f32 gCubeHitbox400[]; +extern_s f32 gItemRingCheckHitbox[]; +extern_s f32 gNoHitbox[]; +extern_s f32 gItemCheckpointHitbox[]; +extern_s f32 gItemSupplyRingHitbox[]; +extern_s f32 gMeteoWarpHitbox[]; +extern_s f32 gItemPathChangeHitbox[]; +extern_s f32 gItemLasersHitbox[]; +extern_s f32 gItemBombHitbox[]; +extern_s f32 gActorMissileSeekHitbox[]; +extern_s f32 gMeMoraHitbox[]; +extern_s f32 gTeamHitbox[]; +extern_s f32 gActorAllRangeHItbox[]; +extern_s f32 aWzMeteor1Hitbox[]; +extern_s f32 aWzGateHitbox[]; +extern_s f32 aWzPillar1Hitbox[]; +extern_s f32 aWzPillar2Hitbox[]; +extern_s ObjectInfo gObjectInfo[]; +extern_s f32* D_edata_800CF964[]; // fox_edisplay -extern f32 D_edisplay_800CF9B0[]; -extern Gfx* D_edisplay_800CFA54[]; -extern Gfx* D_edisplay_800CFAC4[]; -extern Gfx* D_edisplay_800CFADC[]; -extern Gfx* D_edisplay_800CFB08[]; -extern Gfx* D_edisplay_800CFB14[]; -extern Gfx* D_edisplay_800CFB28[]; -extern Gfx* D_edisplay_800CFB40[]; -extern Gfx* D_edisplay_800CFB64[]; -extern Gfx* D_edisplay_800CFB88[]; -extern Gfx* D_edisplay_800CFBA8[]; -extern Gfx* D_edisplay_800CFBE4[]; -extern Gfx* D_edisplay_800CFC0C[]; -extern Gfx* D_edisplay_800CFC40[]; -extern Gfx* D_edisplay_800CFC50[]; -extern Gfx* D_edisplay_800CFC64[]; -extern Gfx* D_edisplay_800CFC7C[]; -extern f32 D_edisplay_800CFCA0[]; -extern f32 D_edisplay_800CFCCC[]; -extern Gfx D_edisplay_800CFD80[]; +extern_s f32 D_edisplay_800CF9B0[]; +extern_s Gfx* D_edisplay_800CFA54[]; +extern_s Gfx* D_edisplay_800CFAC4[]; +extern_s Gfx* D_edisplay_800CFADC[]; +extern_s Gfx* D_edisplay_800CFB08[]; +extern_s Gfx* D_edisplay_800CFB14[]; +extern_s Gfx* D_edisplay_800CFB28[]; +extern_s Gfx* D_edisplay_800CFB40[]; +extern_s Gfx* D_edisplay_800CFB64[]; +extern_s Gfx* D_edisplay_800CFB88[]; +extern_s Gfx* D_edisplay_800CFBA8[]; +extern_s Gfx* D_edisplay_800CFBE4[]; +extern_s Gfx* D_edisplay_800CFC0C[]; +extern_s Gfx* D_edisplay_800CFC40[]; +extern_s Gfx* D_edisplay_800CFC50[]; +extern_s Gfx* D_edisplay_800CFC64[]; +extern_s Gfx* D_edisplay_800CFC7C[]; +extern_s f32 D_edisplay_800CFCA0[]; +extern_s f32 D_edisplay_800CFCCC[]; +extern_s Gfx D_edisplay_800CFD80[]; // fox_enmy -extern ObjectInit* gLevelObjectInits[]; -extern u32 gWarpRingSfx[9]; +extern_s ObjectInit* gLevelObjectInits[]; +extern_s u32 gWarpRingSfx[9]; // fox_enmy2 -extern s32 gTeamEventActorIndex[4]; -extern s32 gCallVoiceParam; +extern_s s32 gTeamEventActorIndex[4]; +extern_s s32 gCallVoiceParam; // fox_hud -extern s16 D_hud_800D1970; +extern_s s16 D_hud_800D1970; // fox_col2 -extern CollisionHeader D_800D2B38[]; -extern CollisionHeader2 D_800D2CA0[]; +extern_s CollisionHeader D_800D2B38[]; +extern_s CollisionHeader2 D_800D2CA0[]; // fox_play -extern u8 gVenomHardClear; -extern u8 gLeveLClearStatus[30]; +extern_s u8 gVenomHardClear; +extern_s u8 gLeveLClearStatus[30]; // fox_radio -extern s32 gRadioMsgPri; +extern_s s32 gRadioMsgPri; // fox_360 -extern s32 gAllRangeSupplyTimer; -extern s32 sStarWolfKillTimer; -extern s16 gStarWolfMsgTimer; -extern s32 gAllRangeWingRepairTimer; -extern s32 gAllRangeSuppliesSent; -extern f32 gSzMissileR; -extern f32 gSzMissileG; -extern f32 gSzMissileB; -extern u8 gKaKilledAlly; -extern u8 gKaAllyKillCount; -extern s32 gAllRangeCheckpoint; -extern s32 gAllRangeEventTimer; -extern s32 gAllRangeCountdown[3]; -extern bool gShowAllRangeCountdown; -extern s32 gAllRangeFrameCount; -extern f32 gAllRangeCountdownScale; +extern_s s32 gAllRangeSupplyTimer; +extern_s s32 sStarWolfKillTimer; +extern_s s16 gStarWolfMsgTimer; +extern_s s32 gAllRangeWingRepairTimer; +extern_s s32 gAllRangeSuppliesSent; +extern_s f32 gSzMissileR; +extern_s f32 gSzMissileG; +extern_s f32 gSzMissileB; +extern_s u8 gKaKilledAlly; +extern_s u8 gKaAllyKillCount; +extern_s s32 gAllRangeCheckpoint; +extern_s s32 gAllRangeEventTimer; +extern_s s32 gAllRangeCountdown[3]; +extern_s bool gShowAllRangeCountdown; +extern_s s32 gAllRangeFrameCount; +extern_s f32 gAllRangeCountdownScale; // fox_bg -extern f32 gAndrossUnkAlpha; -extern u16 gBolseDynamicGround; -extern f32 gWarpZoneBgAlpha; -extern u8 D_bg_8015F964; -extern f32 D_bg_8015F968; -extern f32 D_bg_8015F96C; -extern f32 D_bg_8015F970; -extern s32 D_bg_8015F974; -extern s32 D_bg_8015F978; -extern s32 D_bg_8015F97C; -extern s32 D_bg_8015F980; -extern f32 D_bg_8015F984; +extern_s f32 gAndrossUnkAlpha; +extern_s u16 gBolseDynamicGround; +extern_s f32 gWarpZoneBgAlpha; +extern_s u8 D_bg_8015F964; +extern_s f32 D_bg_8015F968; +extern_s f32 D_bg_8015F96C; +extern_s f32 D_bg_8015F970; +extern_s s32 D_bg_8015F974; +extern_s s32 D_bg_8015F978; +extern_s s32 D_bg_8015F97C; +extern_s s32 D_bg_8015F980; +extern_s f32 D_bg_8015F984; // fox_boss -extern s32 gBossFrameCount; +extern_s s32 gBossFrameCount; // fox_display -extern Vec3f D_display_801613B0[]; // static, here for reordering -extern Vec3f D_display_801613E0[]; // static, here for reordering -extern s16 gReflectY; -extern Matrix D_display_80161418[]; // static, here for reordering -extern Vec3f D_display_80161518[]; // static, here for reordering -extern Vec3f D_display_80161548[]; // static, here for reordering -extern Vec3f gLockOnTargetViewPos[]; -extern f32 D_display_801615A8[]; -extern f32 D_display_801615B8[]; +extern_s Vec3f D_display_801613B0[]; // static, here for reordering +extern_s Vec3f D_display_801613E0[]; // static, here for reordering +extern_s s16 gReflectY; +extern_s Matrix D_display_80161418[]; // static, here for reordering +extern_s Vec3f D_display_80161518[]; // static, here for reordering +extern_s Vec3f D_display_80161548[]; // static, here for reordering +extern_s Vec3f gLockOnTargetViewPos[]; +extern_s f32 D_display_801615A8[]; +extern_s f32 D_display_801615B8[]; // fox_edisplay -extern Vec3f D_edisplay_801615D0; +extern_s Vec3f D_edisplay_801615D0; // fox_enmy -extern s32 D_enmy_Timer_80161670[4]; -extern s32 gLastPathChange; -extern u8 gMissedZoSearchlight; +extern_s s32 D_enmy_Timer_80161670[4]; +extern_s s32 gLastPathChange; +extern_s u8 gMissedZoSearchlight; // fox_enmy2 -extern s32 gCallTimer; +extern_s s32 gCallTimer; // fox_hud -extern s32 D_hud_80161704; -extern s32 D_hud_80161708; -extern s32 D_hud_8016170C; -extern s32 gRadarMissileAlarmTimer; -extern s32 gTotalHits; // 0x80161714 gTotalGameScore -extern f32 D_hud_80161720[3]; -extern s32 gDisplayedHitCount; -extern s32 D_hud_80161730; -extern s32 gShowBossHealth; // 0x80161734 +extern_s s32 D_hud_80161704; +extern_s s32 D_hud_80161708; +extern_s s32 D_hud_8016170C; +extern_s s32 gRadarMissileAlarmTimer; +extern_s s32 gTotalHits; // 0x80161714 gTotalGameScore +extern_s f32 D_hud_80161720[3]; +extern_s s32 gDisplayedHitCount; +extern_s s32 D_hud_80161730; +extern_s s32 gShowBossHealth; // 0x80161734 // fox_std_lib -extern char D_801619A0[]; +extern_s char D_801619A0[]; // fox_play -extern u8 gSavedZoSearchlightStatus; -extern f32 gArwingSpeed; -extern s32 D_play_80161A58; -extern s32 D_play_80161A5C; -extern u16 gScreenFlashTimer; -extern u16 gDropHitCountItem; +extern_s u8 gSavedZoSearchlightStatus; +extern_s f32 gArwingSpeed; +extern_s s32 D_play_80161A58; +extern_s s32 D_play_80161A5C; +extern_s u16 gScreenFlashTimer; +extern_s u16 gDropHitCountItem; //fox_radio -extern u16** gRadioMsgList; -extern s32 gRadioMsgListIndex; -extern s32 gRadioPrintPosX; -extern s32 gRadioPrintPosY; -extern f32 gRadioTextBoxPosX; -extern f32 gRadioTextBoxPosY; -extern f32 gRadioTextBoxScaleX; -extern f32 gRadioPortraitPosX; -extern f32 gRadioPortraitPosY; +extern_s u16** gRadioMsgList; +extern_s s32 gRadioMsgListIndex; +extern_s s32 gRadioPrintPosX; +extern_s s32 gRadioPrintPosY; +extern_s f32 gRadioTextBoxPosX; +extern_s f32 gRadioTextBoxPosY; +extern_s f32 gRadioTextBoxScaleX; +extern_s f32 gRadioPortraitPosX; +extern_s f32 gRadioPortraitPosY; // fox_versus -extern bool gVsMatchOver; -extern s32 gVsMatchState; -extern s32 D_versus_80178758; -extern s32 sUnlockLandmaster; // sUnlockLandmaster -extern s32 sUnlockOnFoot; // sUnlockOnFoot -extern s32 gVsCountdown[]; +extern_s bool gVsMatchOver; +extern_s s32 gVsMatchState; +extern_s s32 D_versus_80178758; +extern_s s32 sUnlockLandmaster; // sUnlockLandmaster +extern_s s32 sUnlockOnFoot; // sUnlockOnFoot +extern_s s32 gVsCountdown[]; // gfx_data -extern u16 D_Tex_800DACB8[]; -extern u16 D_Tex_800D99F8[]; -extern u16 gTextCharPalettes[]; -extern Gfx gRcpInitDL[]; -extern Gfx aCoHighwayShadowDL[]; -extern Gfx D_Gfx_800D9688[]; -extern u8 D_Tex_800DB4B8[]; -extern Gfx D_Gfx_800D94D0[]; - -extern OSTime osClockRate; +extern_s u16 D_Tex_800DACB8[]; +extern_s u16 D_Tex_800D99F8[]; +extern_s u16 gTextCharPalettes[]; +extern_s Gfx gRcpInitDL[]; +extern_s Gfx aCoHighwayShadowDL[]; +extern_s Gfx D_Gfx_800D9688[]; +extern_s u8 D_Tex_800DB4B8[]; +extern_s Gfx D_Gfx_800D94D0[]; + +extern_s OSTime osClockRate; #define osViClock 0x02E6D354; diff --git a/libultraship b/libultraship index eaaf9d0fc..55e65b81a 160000 --- a/libultraship +++ b/libultraship @@ -1 +1 @@ -Subproject commit eaaf9d0fc91e2c400f49ef2a1f8547a691ce4d3c +Subproject commit 55e65b81a2731055d1fd53ca401b9632601d44c6 diff --git a/port/shaders/directx/default.shader.hlsl b/port/shaders/directx/default.shader.hlsl index 980becb8c..baf76c9eb 100644 --- a/port/shaders/directx/default.shader.hlsl +++ b/port/shaders/directx/default.shader.hlsl @@ -11,43 +11,50 @@ struct PSInput { float4 position : SV_POSITION; + @{update_floats(1)} // aMtxSlot vertex attribute (matrix palette index) @for(i in 0..2) @if(o_textures[i]) float2 uv@{i} : TEXCOORD@{i}; @{update_floats(2)} - @for(j in 0..2) - @if(o_clamp[i][j]) - @if(j == 0) - float texClampS@{i} : TEXCLAMPS@{i}; - @else - float texClampT@{i} : TEXCLAMPT@{i}; - @end - @{update_floats(1)} - @end - @end @end @end @if(o_fog) -float4 fog : FOG; -@{update_floats(4)} -@end -@if(o_grayscale) -float4 grayscale : GRAYSCALE; -@{update_floats(4)} +// Interstage only: computed in the vertex shader, not a vertex attribute +float fogFactor : FOG; @end -@for(i in 0..o_inputs) +@if(o_shade) @if(o_alpha) - float4 input@{i + 1} : INPUT@{i}; + float4 shade : SHADE; @{update_floats(4)} @else - float3 input@{i + 1} : INPUT@{i}; + float3 shade : SHADE; @{update_floats(3)} @end @end }; +@if(o_lighting || o_texgen) +// Mirrors struct LightingUniforms in gfx_rendering_api.h +cbuffer LightCB : register(b3) { + float4 lights[96]; // 3 float4 per light: color/isPoint, dir/kc, pos/kq + float4 ambient; + float4 lookat_x; + float4 lookat_y; + float4 texgen_uv[2]; + float4 mv_rows[3]; + float4 mv_cols[3]; + int num_lights; +} +@end + +// Mirrors struct TransformUniforms in gfx_rendering_api.h +cbuffer TransformCB : register(b4) { + float4 mtx_palette[32]; // 4 float4 rows per slot + float4 y_scale; +} + @if(o_textures[0]) Texture2D g_texture0 : register(t0); SamplerState g_sampler0 : register(s0); @@ -63,6 +70,44 @@ float4 grayscale : GRAYSCALE; @if(o_blend[0]) Texture2D g_textureBlend0 : register(t4); @if(o_blend[1]) Texture2D g_textureBlend1 : register(t5); +@if(o_palette[0] || o_palette[1]) +Texture2D g_texturePal : register(t6); +SamplerState g_samplerPal : register(s6); + +// One CI tap: fetch the index (nearest sampler) and look it up in the +// 256-entry palette texture. bank is the CI4 bank entry offset. +float4 paletteTap(in Texture2D tex, in SamplerState tSampler, in float2 uv, in float bank) { + float idx = tex.Sample(tSampler, uv).r; + return g_texturePal.Sample(g_samplerPal, float2((idx * 255.0 + bank + 0.5) / 256.0, 0.5)); +} + +// Filtering happens after the palette lookup, like real hardware: +// params.y selects nearest (0), bilinear (1) or N64 three-point (2). +float4 paletteSampleCI(in Texture2D tex, in SamplerState tSampler, in float2 uv, in float2 texSize, in float4 params) { + if (params.y > 1.5) { + float2 offset = frac(uv * texSize - float2(0.5, 0.5)); + offset -= step(1.0, offset.x + offset.y); + float4 c0 = paletteTap(tex, tSampler, uv - offset / texSize, params.x); + float4 c1 = paletteTap(tex, tSampler, uv - float2(offset.x - sign(offset.x), offset.y) / texSize, params.x); + float4 c2 = paletteTap(tex, tSampler, uv - float2(offset.x, offset.y - sign(offset.y)) / texSize, params.x); + return c0 + abs(offset.x) * (c1 - c0) + abs(offset.y) * (c2 - c0); + } else if (params.y > 0.5) { + float2 t = uv * texSize - 0.5; + float2 f = frac(t); + float2 base = (floor(t) + 0.5) / texSize; + float2 px = float2(1.0, 0.0) / texSize; + float2 py = float2(0.0, 1.0) / texSize; + float4 c00 = paletteTap(tex, tSampler, base, params.x); + float4 c10 = paletteTap(tex, tSampler, base + px, params.x); + float4 c01 = paletteTap(tex, tSampler, base + py, params.x); + float4 c11 = paletteTap(tex, tSampler, base + px + py, params.x); + return lerp(lerp(c00, c10, f.x), lerp(c01, c11, f.x), f.y); + } else { + return paletteTap(tex, tSampler, uv, params.x); + } +} +@end + cbuffer PerFrameCB : register(b0) { uint noise_frame; float noise_scale; @@ -73,19 +118,69 @@ float random(in float3 value) { return frac(sin(random) * 143758.5453); } -// 3 point texture filtering -// Original author: ArthurCarvalho -// Based on GLSL implementation by twinaphex, mupen64plus-libretro project. +// N64 RDP ordered-dither matrices (values 0..7); see applyRdpDither. +static const int kDitherMagic[16] = { 0, 6, 1, 7, 4, 2, 5, 3, 3, 5, 2, 4, 7, 1, 6, 0 }; +static const int kDitherBayer[16] = { 0, 4, 1, 5, 6, 2, 7, 3, 1, 5, 0, 4, 7, 3, 6, 2 }; + +// Integer hash for the G_CD_NOISE dither: robust per-pixel + per-frame value 0..7 +// (a sin-based hash aliases to near-constant on some GPUs, washing the noise out). +int ditherNoise(int2 p, int frame) { + uint h = uint(p.x) * 1597334677u ^ uint(p.y) * 3812015801u ^ uint(frame) * 2654435761u; + h ^= h >> 16; h *= 2246822519u; + h ^= h >> 13; h *= 3266489917u; + h ^= h >> 16; + return int(h & 7u); +} -@if(o_three_point_filtering && o_textures[0] || o_textures[1]) +// RDP RGB dither + RGBA5551 quantization. mode: 0=magic square, 1=bayer, +// 2=noise (temporal), 3=disable (truncate only), >=4 = off (full precision). +float3 applyRdpDither(float3 color, float modeF, float2 fragCoord, float noiseScale, float frameCount) { + int mode = int(modeF + 0.5); + if (mode >= 4) { + return color; + } + float2 nativeCoord = floor(fragCoord * noiseScale); + float d = 0.0; + if (mode == 0) { + int2 cell = int2(nativeCoord) & 3; + d = float(kDitherMagic[cell.y * 4 + cell.x]); + } else if (mode == 1) { + int2 cell = int2(nativeCoord) & 3; + d = float(kDitherBayer[cell.y * 4 + cell.x]); + } else if (mode == 2) { + d = float(ditherNoise(int2(nativeCoord), (int) frameCount)); + } + float3 q = min(floor(clamp(color * 255.0 + d, 0.0, 255.0) / 8.0), 31.0); + return (q * 8.0 + floor(q / 4.0)) / 255.0; +} + +// Per-draw constants: texture metadata for 3-point filtering plus the combiner +// constant operands (prim, env, keys, K4/K5, fog/grayscale colors). +// Layout must mirror struct PerDrawCB in gfx_direct3d_common.h. cbuffer PerDrawCB : register(b1) { struct { uint width; uint height; bool linear_filtering; - } textures[2]; + } textures[7]; + float4 combiner_inputs[6]; + float4 fog_color; + float4 grayscale_color; + float4 uv_transform[2]; + float4 texture_clamp[2]; + float4 fog_params; + float4 palette_params[2]; + float4 lod_params; // x = res scale, y = prim_lod_min, z = G_TD mode + // Game-bindable register file; lockstep with PerDrawCB in gfx_direct3d_common.h + float4 uCustom[16]; + float4 debug_tint; } +// 3 point texture filtering +// Original author: ArthurCarvalho +// Based on GLSL implementation by twinaphex, mupen64plus-libretro project. + +@if(o_three_point_filtering && (o_textures[0] || o_textures[1])) #define TEX_OFFSET(tex, tSampler, texCoord, off, texSize) tex.Sample(tSampler, texCoord - off / texSize) float4 tex2D3PointFilter(in Texture2D tex, in SamplerState tSampler, in float2 texCoord, in float2 texSize) { @@ -98,66 +193,141 @@ float4 tex2D3PointFilter(in Texture2D tex, in SamplerState tSampler, in float2 t } @end +@if(o_prim_depth || o_uses_lod) +cbuffer PerPrimDepthCB : register(b2) { + float prim_depth; + float lod_max; + float2 _pad; // pad to 16-byte cbuffer alignment +} +@end + PSInput VSMain( float4 position : POSITION + , float mtxSlot : MTXSLOT @for(i in 0..2) @if(o_textures[i]) , float2 uv@{i} : TEXCOORD@{i} @end - @for(j in 0..2) - @if(o_clamp[i][j]) - @if(j == 0) - , float texClampS@{i} : TEXCLAMPS@{i} - @else - , float texClampT@{i} : TEXCLAMPT@{i} - @end - @end - @end -@end -@if(o_fog) - , float4 fog : FOG -@end -@if(o_grayscale) - , float4 grayscale : GRAYSCALE @end -@for(i in 0..o_inputs) +@if(o_shade || o_lighting) @if(o_alpha) - , float4 input@{i + 1} : INPUT@{i} + , float4 shade : SHADE @else - , float3 input@{i + 1} : INPUT@{i} + , float3 shade : SHADE @end @end ) { PSInput result; - result.position = position; + + // RSP position transform: matrix palette entry selected per vertex + int mtxBase = int(mtxSlot + 0.5) * 4; + float4 clipPos = position.x * mtx_palette[mtxBase] + position.y * mtx_palette[mtxBase + 1] + + position.z * mtx_palette[mtxBase + 2] + position.w * mtx_palette[mtxBase + 3]; + + // D3D clip space: z in 0..1; y flip is carried in the uniform + result.position = float4(clipPos.x, clipPos.y * y_scale.x, (clipPos.z + clipPos.w) / 2.0, clipPos.w); @for(i in 0..2) @if(o_textures[i]) - result.uv@{i} = uv@{i}; - @for(j in 0..2) - @if(o_clamp[i][j]) - @if(j == 0) - result.texClampS@{i} = texClampS@{i}; - @else - result.texClampT@{i} = texClampT@{i}; - @end - @end - @end + // Tile shift/origin/bilerp/size pipeline folded into one transform + result.uv@{i} = float2(uv@{i}.x * uv_transform[@{i}].x + uv_transform[@{i}].y, + uv@{i}.y * uv_transform[@{i}].z + uv_transform[@{i}].w); @end @end @if(o_fog) - result.fog = fog; + // N64 RSP fog from clip-space z/w; + // fog_params.w selects the source (0: computed, 1: constant, 2: vertex alpha) + float fogZ = clipPos.z; + float fogW = abs(clipPos.w) < 0.001 ? 0.001 : clipPos.w; + float fogWinv = 1.0 / fogW; + if (fogWinv < 0.0) { + fogWinv = 32767.0; + } + float fogCalc = clamp(fogZ * fogWinv * fog_params.x + fog_params.y, 0.0, 255.0) / 255.0; + @if(o_shade && o_alpha) + result.fogFactor = fog_params.w > 1.5 ? shade.a : (fog_params.w > 0.5 ? fog_params.z : fogCalc); + @else + result.fogFactor = fog_params.w > 0.5 ? fog_params.z : fogCalc; + @end @end - @if(o_grayscale) - result.grayscale = grayscale; + @if(o_shade && o_alpha) + // Standard fog forces shade alpha to 1.0; blend-color mode preserves it + float shadeAlpha = shade.a; + @if(o_fog) + if (fog_params.w < 0.5 || fog_params.w > 1.5) { + shadeAlpha = 1.0; + } + @end @end - @for(i in 0..o_inputs) - @if(o_alpha) - result.input@{i + 1} = input@{i + 1}; + @if(o_texgen) + // N64 texgen: project the vertex normal onto the lookat vectors, then run + // the result through the tile/scale UV pipeline (folded into texgen_uv). + float texgenDotX = clamp(dot(shade.xyz, lookat_x.xyz) / 127.0, -1.0, 1.0); + float texgenDotY = clamp(dot(shade.xyz, lookat_y.xyz) / 127.0, -1.0, 1.0); + @if(o_texgen_linear) + texgenDotX = acos(-texgenDotX) * 0.159155; + texgenDotY = acos(-texgenDotY) * 0.159155; @else - result.input@{i + 1} = float4(input@{i + 1}, 1.0); + texgenDotX = (texgenDotX + 1.0) / 4.0; + texgenDotY = (texgenDotY + 1.0) / 4.0; + @end + @if(o_textures[0]) + result.uv0 = float2(texgenDotX * texgen_uv[0].x + texgen_uv[0].y, + texgenDotY * texgen_uv[0].z + texgen_uv[0].w); + @end + @if(o_textures[1]) + result.uv1 = float2(texgenDotX * texgen_uv[1].x + texgen_uv[1].y, + texgenDotY * texgen_uv[1].z + texgen_uv[1].w); + @end + @end + + @if(o_point_lighting) + // World-space position derived from the object-space vertex position + float3 worldPos = float3(dot(position, mv_cols[0]), dot(position, mv_cols[1]), dot(position, mv_cols[2])); + @end + @if(o_shade) + @if(o_lighting) + // N64 RSP lighting: the shade input carries the raw signed vertex normal + float3 litColor = ambient.rgb; + for (int i = 0; i < num_lights; i++) { + float intensity = 0.0; + @if(o_point_lighting) + if (lights[i * 3].w > 0.5) { + float3 distVec = lights[i * 3 + 2].xyz - worldPos; + float distSq = distVec.x * distVec.x + distVec.y * distVec.y + distVec.z * distVec.z * 2.0; + float dist = sqrt(distSq); + float3 lightModel = float3(dot(distVec, mv_rows[0].xyz), dot(distVec, mv_rows[1].xyz), + dot(distVec, mv_rows[2].xyz)); + float3 lightIntensity = clamp(4.0 * lightModel / distSq, -1.0, 1.0); + float totalIntensity = clamp(dot(lightIntensity, shade.xyz), -1.0, 1.0); + float distF = floor(dist); + float attenuation = (distF * lights[i * 3 + 1].w * 2.0 + + distF * distF * lights[i * 3 + 2].w / 8.0) / 65535.0 + 1.0; + intensity = totalIntensity / attenuation; + } else { + intensity = dot(shade.xyz, lights[i * 3 + 1].xyz) / 127.0; + } + @else + intensity = dot(shade.xyz, lights[i * 3 + 1].xyz) / 127.0; + @end + if (intensity > 0.0) { + litColor += intensity * lights[i * 3].rgb; + } + } + litColor = min(litColor, float3(1.0, 1.0, 1.0)); + @if(o_alpha) + result.shade = float4(litColor, shadeAlpha); + @else + result.shade = litColor; + @end + @else + @if(o_alpha) + result.shade = float4(shade.rgb, shadeAlpha); + @else + result.shade = shade; + @end @end @end @@ -168,19 +338,20 @@ PSInput VSMain( [RootSignature(RS)] @end -@if(srgb_mode) - float4 fromLinear(float4 linearRGB){ - bool3 cutoff = linearRGB.rgb < float3(0.0031308, 0.0031308, 0.0031308); - float3 higher = 1.055 * pow(linearRGB.rgb, float3(1.0 / 2.4, 1.0 / 2.4, 1.0 / 2.4)) - float3(0.055, 0.055, 0.055); - float3 lower = linearRGB.rgb * float3(12.92, 12.92, 12.92); - return float4(lerp(higher, lower, cutoff), linearRGB.a); - } -@end - #define MOD(x, y) ((x) - (y) * floor((x)/(y))) #define WRAP(x, low, high) MOD((x)-(low), (high)-(low)) + (low) -float4 PSMain(PSInput input, float4 screenSpace : SV_Position) : SV_TARGET { +struct PSOutput { + float4 color : SV_TARGET; + @if(o_prim_depth) + float depth : SV_Depth; + @end +}; + +PSOutput PSMain(PSInput input, float4 screenSpace : SV_Position) { + @if(o_uses_lod) + float lodFrac = 0.0; + @end @for(i in 0..2) @if(o_textures[i]) float2 tc@{i} = input.uv@{i}; @@ -190,15 +361,80 @@ float4 PSMain(PSInput input, float4 screenSpace : SV_Position) : SV_TARGET { int2 texSize@{i}; g_texture@{i}.GetDimensions(texSize@{i}.x, texSize@{i}.y); @if(s && t) - tc@{i} = clamp(tc@{i}, 0.5 / texSize@{i}, float2(input.texClampS@{i}, input.texClampT@{i})); + tc@{i} = clamp(tc@{i}, 0.5 / texSize@{i}, texture_clamp[@{i}].xy); @elseif(s) - tc@{i} = float2(clamp(tc@{i}.x, 0.5 / texSize@{i}.x, input.texClampS@{i}), tc@{i}.y); + tc@{i} = float2(clamp(tc@{i}.x, 0.5 / texSize@{i}.x, texture_clamp[@{i}].x), tc@{i}.y); @else - tc@{i} = float2(tc@{i}.x, clamp(tc@{i}.y, 0.5 / texSize@{i}.y, input.texClampT@{i})); + tc@{i} = float2(tc@{i}.x, clamp(tc@{i}.y, 0.5 / texSize@{i}.y, texture_clamp[@{i}].y)); + @end + @end + + @if(i == 0) + @if(o_uses_lod) + @if(!s && !t) + int2 texSize0; + g_texture0.GetDimensions(texSize0.x, texSize0.y); + @end + // N64 texture LOD (RDP-accurate): max absolute UV derivative, + // linear fraction between tiles, sharpen/detail handling + float2 lodScaled = tc0 * float2(texSize0); + float2 lodMaxD = max(abs(ddx(lodScaled)), abs(ddy(lodScaled))); + float lodMaxDst = max(max(lodMaxD.x, lodMaxD.y) * lod_params.x, 0.000001); + if (lod_params.z > 0.5) { // sharpen or detail + lodMaxDst = max(lodMaxDst, lod_params.y); + } + float lodTileBase = floor(log2(lodMaxDst)); + lodFrac = lodMaxDst / exp2(max(lodTileBase, 0.0)) - 1.0; + if (lod_params.z > 0.5 && lod_params.z < 1.5 && lodMaxDst < 1.0) { // sharpen + lodFrac = lodMaxDst - 1.0; + } + if (lod_params.z > 1.5) { // detail: tile 0 is the detail texture + if (lodFrac < 0.0) { + lodFrac = lodMaxDst; + } + lodTileBase += 1.0; + } else if (lodTileBase >= lod_max) { + lodFrac = 1.0; + } + if (lod_params.z > 0.5) { + lodTileBase = max(lodTileBase, 0.0); + } else { + lodFrac = max(lodFrac, 0.0); + } + float lodTile0 = clamp(lodTileBase, 0.0, lod_max); + float lodTile1 = clamp(lodTileBase + 1.0, 0.0, lod_max); + // No real LOD level beyond the base (max level 0): the N64 never + // blends a second tile. Small EXTRA_TILE_MIPMAPS textures + // degenerate to one level yet still emit G_TL_LOD+TRILERP; without + // this the combiner blends a stale TEXEL1 by distance. + if (lod_max < 0.5) { + lodFrac = 0.0; + } @end @end - @if(o_three_point_filtering) + @if(i == 0 && o_mip_lod) + float4 texVal0 = g_texture0.SampleLevel(g_sampler0, tc0, lodTile0); + @if(o_masks[0]) + @if(o_blend[0]) + float4 blendVal0 = g_textureBlend0.Sample(g_sampler0, tc0); + @else + float4 blendVal0 = float4(0, 0, 0, 0); + @end + texVal0 = lerp(texVal0, blendVal0, g_textureMask0.Sample(g_sampler0, tc0).a); + @end + @elseif(o_palette[i]) + @if(!s && !t) + @if(i == 1) + int2 texSize1; + g_texture1.GetDimensions(texSize1.x, texSize1.y); + @elseif(!o_uses_lod) + int2 texSize0; + g_texture0.GetDimensions(texSize0.x, texSize0.y); + @end + @end + float4 texVal@{i} = paletteSampleCI(g_texture@{i}, g_sampler@{i}, tc@{i}, float2(texSize@{i}), palette_params[@{i}]); + @elseif(o_three_point_filtering) float4 texVal@{i}; if (textures[@{i}].linear_filtering) { @if(o_masks[i]) @@ -241,7 +477,18 @@ float4 PSMain(PSInput input, float4 screenSpace : SV_Position) : SV_TARGET { @end @end - @if(o_alpha) + @if(o_mip_lod) + // TEXEL1 reads the next mip level of texture 0 + float4 texVal1 = g_texture0.SampleLevel(g_sampler0, tc0, lodTile1); + @end + + @if(o_two_tile_lod) + // N64 LOD tile selection: TEXEL0's tile clamps to the max level; the + // hardware's second texel is always lod_tile + 1 (real tile 1). + texVal0 = lodTile0 < 0.5 ? texVal0 : texVal1; + @end + + @if(o_alpha) float4 texel; @else float3 texel; @@ -293,16 +540,16 @@ float4 PSMain(PSInput input, float4 screenSpace : SV_Position) : SV_TARGET { // TODO discard if alpha is 0? @if(o_fog) @if(o_alpha) - texel = float4(lerp(texel.rgb, input.fog.rgb, input.fog.a), texel.a); + texel = float4(lerp(texel.rgb, fog_color.rgb, input.fogFactor), texel.a); @else - texel = lerp(texel, input.fog.rgb, input.fog.a); + texel = lerp(texel, fog_color.rgb, input.fogFactor); @end @end @if(o_grayscale) float intensity = (texel.r + texel.g + texel.b) / 3.0; - float3 new_texel = input.grayscale.rgb * intensity; - texel.rgb = lerp(texel.rgb, new_texel, input.grayscale.a); + float3 new_texel = grayscale_color.rgb * intensity; + texel.rgb = lerp(texel.rgb, new_texel, grayscale_color.a); @end @if(o_alpha && o_noise) @@ -310,6 +557,20 @@ float4 PSMain(PSInput input, float4 screenSpace : SV_Position) : SV_TARGET { texel.a *= round(saturate(random(float3(floor(coords), noise_frame)) + texel.a - 0.5)); @end + // N64 RGB framebuffer dither (per-primitive G_CD_* mode in lod_params.w) + @if(o_alpha) + texel.rgb = applyRdpDither(texel.rgb, lod_params.w, screenSpace.xy, noise_scale, noise_frame); + @else + texel = applyRdpDither(texel, lod_params.w, screenSpace.xy, noise_scale, noise_frame); + @end + + // HD-replacement debug tint (no-op when debug_tint.a == 0) + @if(o_alpha) + texel.rgb = lerp(texel.rgb, debug_tint.rgb, debug_tint.a); + @else + texel = lerp(texel, debug_tint.rgb, debug_tint.a); + @end + @if(o_alpha) @if(o_alpha_threshold) if (texel.a < 8.0 / 256.0) discard; @@ -317,16 +578,16 @@ float4 PSMain(PSInput input, float4 screenSpace : SV_Position) : SV_TARGET { @if(o_invisible) texel.a = 0.0; @end - @if(srgb_mode) - return fromLinear(texel); - @else - return texel; - @end + @end + + PSOutput output; + @if(o_alpha) + output.color = texel; @else - @if(srgb_mode) - return fromLinear(float4(texel, 1.0)); - @else - return float4(texel, 1.0); - @end + output.color = float4(texel, 1.0); + @end + @if(o_prim_depth) + output.depth = prim_depth; @end + return output; } diff --git a/port/shaders/directx/srgb.shader.hlsl b/port/shaders/directx/srgb.shader.hlsl new file mode 100644 index 000000000..8062e87bd --- /dev/null +++ b/port/shaders/directx/srgb.shader.hlsl @@ -0,0 +1,81 @@ +@prism(type='hlsl', name='Fast3D HLSL sRGB Post', version='1.0.0', description='Final-pass linear->sRGB (gamma) output encoding', author='Fast3D') + +@if(o_root_signature) + #define RS "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | DENY_VERTEX_SHADER_ROOT_ACCESS), CBV(b0, visibility = SHADER_VISIBILITY_PIXEL), DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL), DescriptorTable(Sampler(s0), visibility = SHADER_VISIBILITY_PIXEL)" +@end + +struct PSInput { + float4 position : SV_POSITION; + @{update_floats(1)} // aMtxSlot vertex attribute (matrix palette index) + float2 uv0 : TEXCOORD0; + @{update_floats(2)} +}; + +// Mirrors struct TransformUniforms in gfx_rendering_api.h +cbuffer TransformCB : register(b4) { + float4 mtx_palette[32]; // 4 float4 rows per slot + float4 y_scale; +} + +// Per-draw constants; layout must mirror struct PerDrawCB in gfx_direct3d_common.h. +// Only uv_transform is read here, but the full layout is required so the +// register offsets line up with what the backend binds at b1. +cbuffer PerDrawCB : register(b1) { + struct { + uint width; + uint height; + bool linear_filtering; + } textures[7]; + float4 combiner_inputs[6]; + float4 fog_color; + float4 grayscale_color; + float4 uv_transform[2]; + float4 texture_clamp[2]; + float4 fog_params; + float4 palette_params[2]; + float4 lod_params; + float4 uCustom[16]; +} + +Texture2D g_texture0 : register(t0); +SamplerState g_sampler0 : register(s0); + +PSInput VSMain(float4 position : POSITION, float mtxSlot : MTXSLOT, float2 uv0 : TEXCOORD0) { + PSInput result; + + // RSP position transform: matrix palette entry selected per vertex + int mtxBase = int(mtxSlot + 0.5) * 4; + float4 clipPos = position.x * mtx_palette[mtxBase] + position.y * mtx_palette[mtxBase + 1] + + position.z * mtx_palette[mtxBase + 2] + position.w * mtx_palette[mtxBase + 3]; + + // D3D clip space: z in 0..1; y flip is carried in the uniform + result.position = float4(clipPos.x, clipPos.y * y_scale.x, (clipPos.z + clipPos.w) / 2.0, clipPos.w); + // Tile shift/origin/bilerp/size pipeline folded into one transform + result.uv0 = float2(uv0.x * uv_transform[0].x + uv_transform[0].y, + uv0.y * uv_transform[0].z + uv_transform[0].w); + return result; +} + +@if(o_root_signature) + [RootSignature(RS)] +@end + +// Linear -> sRGB transfer (the gamma boost previously baked into every fragment +// shader via srgb_mode; now applied once as a fullscreen pass). +float4 fromLinear(float4 linearRGB){ + bool3 cutoff = linearRGB.rgb < float3(0.0031308, 0.0031308, 0.0031308); + float3 higher = 1.055 * pow(linearRGB.rgb, float3(1.0 / 2.4, 1.0 / 2.4, 1.0 / 2.4)) - float3(0.055, 0.055, 0.055); + float3 lower = linearRGB.rgb * float3(12.92, 12.92, 12.92); + return float4(lerp(higher, lower, cutoff), linearRGB.a); +} + +struct PSOutput { + float4 color : SV_TARGET; +}; + +PSOutput PSMain(PSInput input, float4 screenSpace : SV_Position) { + float4 texel = g_texture0.Sample(g_sampler0, input.uv0); + PSOutput output; + output.color = fromLinear(float4(texel.rgb, 1.0)); + return output; +} diff --git a/port/shaders/metal/default.shader.metal b/port/shaders/metal/default.shader.metal index a771ba10c..a5e50885c 100644 --- a/port/shaders/metal/default.shader.metal +++ b/port/shaders/metal/default.shader.metal @@ -9,39 +9,67 @@ struct FrameUniforms { float noiseScale; }; +struct DrawUniforms { + int textureFiltering[7]; + float prim_depth; + float lod_max; + float4 inputs[6]; + float4 fog_color; + float4 grayscale_color; + float4 uv_transform[2]; + float4 texture_clamp[2]; + float4 fog_params; + float4 palette_params[2]; + float4 lod_params; + // Game-bindable register file; lockstep with DrawUniforms in gfx_metal.h + float4 uCustom[32]; + float4 debug_tint; +}; + +@if(o_lighting || o_texgen) +// Mirrors struct LightingUniforms in gfx_rendering_api.h +struct LightUniforms { + float4 lights[96]; // 3 float4 per light: color/isPoint, dir/kc, pos/kq + float4 ambient; + float4 lookat_x; + float4 lookat_y; + float4 texgen_uv[2]; + float4 mv_rows[3]; + float4 mv_cols[3]; + int num_lights; +}; +@end + +// Mirrors struct TransformUniforms in gfx_rendering_api.h +struct TransformUniforms { + float4 mtx_palette[32]; // 4 float4 rows per slot + float4 y_scale; +}; + +struct FragOut { + float4 color [[color(0)]]; + @if(o_prim_depth) + float depth [[depth(any)]]; + @end +}; + struct Vertex { float4 position [[attribute(@{get_vertex_index()})]]; @{update_floats(4)} + float mtxSlot [[attribute(@{get_vertex_index()})]]; + @{update_floats(1)} @for(i in 0..2) @if(o_textures[i]) float2 texCoord@{i} [[attribute(@{get_vertex_index()})]]; @{update_floats(2)} - @for(j in 0..2) - @if(o_clamp[i][j]) - @if(j == 0) - float texClampS@{i} [[attribute(@{get_vertex_index()})]]; - @else - float texClampT@{i} [[attribute(@{get_vertex_index()})]]; - @end - @{update_floats(1)} - @end - @end @end @end - @if(o_fog) - float4 fog [[attribute(@{get_vertex_index()})]]; - @{update_floats(4)} - @end - @if(o_grayscale) - float4 grayscale [[attribute(@{get_vertex_index()})]]; - @{update_floats(4)} - @end - @for(i in 0..o_inputs) + @if(o_shade || o_lighting) @if(o_alpha) - float4 input@{i + 1} [[attribute(@{get_vertex_index()})]]; + float4 shade [[attribute(@{get_vertex_index()})]]; @{update_floats(4)} @else - float3 input@{i + 1} [[attribute(@{get_vertex_index()})]]; + float3 shade [[attribute(@{get_vertex_index()})]]; @{update_floats(3)} @end @end @@ -51,59 +79,145 @@ struct ProjectedVertex { @for(i in 0..2) @if(o_textures[i]) float2 texCoord@{i}; - @for(j in 0..2) - @if(o_clamp[i][j]) - @if(j == 0) - float texClampS@{i}; - @else - float texClampT@{i}; - @end - @end - @end @end @end @if(o_fog) - float4 fog; + float fogFactor; @end - @if(o_grayscale) - float4 grayscale; - @end - @for(i in 0..o_inputs) + @if(o_shade) @if(o_alpha) - float4 input@{i + 1}; + float4 shade; @else - float3 input@{i + 1}; + float3 shade; @end @end float4 position [[position]]; }; -vertex ProjectedVertex vertexShader(Vertex in [[stage_in]]) { +vertex ProjectedVertex vertexShader(Vertex in [[stage_in]] + , constant DrawUniforms& drawUniforms [[buffer(2)]] + , constant TransformUniforms& transformUniforms [[buffer(3)]] +@if(o_lighting || o_texgen) + , constant LightUniforms& lightUniforms [[buffer(1)]] +@end +) { ProjectedVertex out; + + // RSP position transform: matrix palette entry selected per vertex + int mtxBase = int(in.mtxSlot + 0.5) * 4; + float4 clipPos = in.position.x * transformUniforms.mtx_palette[mtxBase] + + in.position.y * transformUniforms.mtx_palette[mtxBase + 1] + + in.position.z * transformUniforms.mtx_palette[mtxBase + 2] + + in.position.w * transformUniforms.mtx_palette[mtxBase + 3]; + @for(i in 0..2) @if(o_textures[i]) - out.texCoord@{i} = in.texCoord@{i}; - @for(j in 0..2) - @if(o_clamp[i][j]) - @if(j == 0) - out.texClampS@{i} = in.texClampS@{i}; - @else - out.texClampT@{i} = in.texClampT@{i}; - @end - @end - @end + // Tile shift/origin/bilerp/size pipeline folded into one transform + out.texCoord@{i} = float2(in.texCoord@{i}.x * drawUniforms.uv_transform[@{i}].x + drawUniforms.uv_transform[@{i}].y, + in.texCoord@{i}.y * drawUniforms.uv_transform[@{i}].z + drawUniforms.uv_transform[@{i}].w); @end @end @if(o_fog) - out.fog = in.fog; + // N64 RSP fog from clip-space z/w; + // fog_params.w selects the source (0: computed, 1: constant, 2: vertex alpha) + float fogZ = clipPos.z; + float fogW = abs(clipPos.w) < 0.001 ? 0.001 : clipPos.w; + float fogWinv = 1.0 / fogW; + if (fogWinv < 0.0) { + fogWinv = 32767.0; + } + float fogCalc = clamp(fogZ * fogWinv * drawUniforms.fog_params.x + drawUniforms.fog_params.y, 0.0, 255.0) / 255.0; + @if(o_shade && o_alpha) + out.fogFactor = drawUniforms.fog_params.w > 1.5 ? in.shade.w + : (drawUniforms.fog_params.w > 0.5 ? drawUniforms.fog_params.z : fogCalc); + @else + out.fogFactor = drawUniforms.fog_params.w > 0.5 ? drawUniforms.fog_params.z : fogCalc; + @end @end - @if(o_grayscale) - out.grayscale = in.grayscale; + @if(o_texgen) + // N64 texgen: project the vertex normal onto the lookat vectors, then + // run the result through the tile/scale UV pipeline (folded into the + // per-draw texgen linear transforms). + float texgenDotX = clamp(dot(in.shade.xyz, lightUniforms.lookat_x.xyz) / 127.0, -1.0, 1.0); + float texgenDotY = clamp(dot(in.shade.xyz, lightUniforms.lookat_y.xyz) / 127.0, -1.0, 1.0); + @if(o_texgen_linear) + texgenDotX = acos(-texgenDotX) * 0.159155; + texgenDotY = acos(-texgenDotY) * 0.159155; + @else + texgenDotX = (texgenDotX + 1.0) / 4.0; + texgenDotY = (texgenDotY + 1.0) / 4.0; + @end + @if(o_textures[0]) + out.texCoord0 = float2(texgenDotX * lightUniforms.texgen_uv[0].x + lightUniforms.texgen_uv[0].y, + texgenDotY * lightUniforms.texgen_uv[0].z + lightUniforms.texgen_uv[0].w); + @end + @if(o_textures[1]) + out.texCoord1 = float2(texgenDotX * lightUniforms.texgen_uv[1].x + lightUniforms.texgen_uv[1].y, + texgenDotY * lightUniforms.texgen_uv[1].z + lightUniforms.texgen_uv[1].w); + @end + @end + @if(o_shade && o_alpha) + // Standard fog forces shade alpha to 1.0; blend-color mode preserves it + float shadeAlpha = in.shade.w; + @if(o_fog) + if (drawUniforms.fog_params.w < 0.5 || drawUniforms.fog_params.w > 1.5) { + shadeAlpha = 1.0; + } + @end + @end + @if(o_point_lighting) + // World-space position derived from the object-space vertex position + float3 worldPos = float3(dot(in.position, lightUniforms.mv_cols[0]), + dot(in.position, lightUniforms.mv_cols[1]), + dot(in.position, lightUniforms.mv_cols[2])); @end - @for(i in 0..o_inputs) - out.input@{i + 1} = in.input@{i + 1}; + @if(o_shade) + @if(o_lighting) + // N64 RSP lighting: in.shade carries the raw signed vertex normal + float3 litColor = lightUniforms.ambient.xyz; + for (int i = 0; i < lightUniforms.num_lights; i++) { + float intensity = 0.0; + @if(o_point_lighting) + if (lightUniforms.lights[i * 3].w > 0.5) { + float3 distVec = lightUniforms.lights[i * 3 + 2].xyz - worldPos; + float distSq = distVec.x * distVec.x + distVec.y * distVec.y + distVec.z * distVec.z * 2.0; + float dist = sqrt(distSq); + float3 lightModel = float3(dot(distVec, lightUniforms.mv_rows[0].xyz), + dot(distVec, lightUniforms.mv_rows[1].xyz), + dot(distVec, lightUniforms.mv_rows[2].xyz)); + float3 lightIntensity = clamp(4.0 * lightModel / distSq, -1.0, 1.0); + float totalIntensity = clamp(dot(lightIntensity, in.shade.xyz), -1.0, 1.0); + float distF = floor(dist); + float attenuation = (distF * lightUniforms.lights[i * 3 + 1].w * 2.0 + + distF * distF * lightUniforms.lights[i * 3 + 2].w / 8.0) / 65535.0 + 1.0; + intensity = totalIntensity / attenuation; + } else { + intensity = dot(in.shade.xyz, lightUniforms.lights[i * 3 + 1].xyz) / 127.0; + } + @else + intensity = dot(in.shade.xyz, lightUniforms.lights[i * 3 + 1].xyz) / 127.0; + @end + if (intensity > 0.0) { + litColor += intensity * lightUniforms.lights[i * 3].xyz; + } + } + litColor = min(litColor, float3(1.0)); + @if(o_alpha) + out.shade = float4(litColor, shadeAlpha); + @else + out.shade = litColor; + @end + @else + @if(o_alpha) + out.shade = float4(in.shade.xyz, shadeAlpha); + @else + out.shade = in.shade; + @end + @end @end - out.position = in.position; + // Metal clip space: z in 0..1; y flip is carried in the uniform + out.position = float4(clipPos.x, clipPos.y * transformUniforms.y_scale.x, + (clipPos.z + clipPos.w) / 2.0, clipPos.w); return out; } // END - BEGIN FRAGMENT SHADER @@ -123,31 +237,112 @@ float4 mod(float4 a, float4 b) { #define WRAP(x, low, high) mod((x)-(low), (high)-(low)) + (low) #define TEX_OFFSET(tex, texSmplr, texCoord, off, texSize) tex.sample(texSmplr, texCoord - off / texSize) -@if(o_three_point_filtering) - float4 filter3point(thread const texture2d tex, thread const sampler texSmplr, thread const float2& texCoord, thread const float2& texSize) { - float2 offset = fract((texCoord * texSize) - float2(0.5)); - offset -= float2(step(1.0, offset.x + offset.y)); - float4 c0 = TEX_OFFSET(tex, texSmplr, texCoord, offset, texSize); - float4 c1 = TEX_OFFSET(tex, texSmplr, texCoord, float2(offset.x - sign(offset.x), offset.y), texSize); - float4 c2 = TEX_OFFSET(tex, texSmplr, texCoord, float2(offset.x, offset.y - sign(offset.y)), texSize); - return c0 + abs(offset.x) * (c1 - c0) + abs(offset.y) * (c2 - c0); - } +float4 filter3point(thread const texture2d tex, thread const sampler texSmplr, thread const float2& texCoord, thread const float2& texSize) { + float2 offset = fract((texCoord * texSize) - float2(0.5)); + offset -= float2(step(1.0, offset.x + offset.y)); + float4 c0 = TEX_OFFSET(tex, texSmplr, texCoord, offset, texSize); + float4 c1 = TEX_OFFSET(tex, texSmplr, texCoord, float2(offset.x - sign(offset.x), offset.y), texSize); + float4 c2 = TEX_OFFSET(tex, texSmplr, texCoord, float2(offset.x, offset.y - sign(offset.y)), texSize); + return c0 + abs(offset.x) * (c1 - c0) + abs(offset.y) * (c2 - c0); +} - float4 hookTexture2D(thread const texture2d tex, thread const sampler texSmplr, thread const float2& uv, thread const float2& texSize) { +float4 hookTexture2D(thread const texture2d tex, thread const sampler texSmplr, thread const float2& uv, thread const float2& texSize, thread const int filtering) { +@if(o_three_point_filtering) + if(filtering == @{FILTER_THREE_POINT}) { return filter3point(tex, texSmplr, uv, texSize); } -@else - float4 hookTexture2D(thread const texture2d tex, thread const sampler texSmplr, thread const float2& uv, thread const float2& texSize) { - return tex.sample(texSmplr, uv); - } @end + return tex.sample(texSmplr, uv); +} float random(float3 value) { float random = dot(sin(value), float3(12.9898, 78.233, 37.719)); return fract(sin(random) * 143758.5453); } -fragment float4 fragmentShader(ProjectedVertex in [[stage_in]], constant FrameUniforms &frameUniforms [[buffer(0)]] +// N64 RDP ordered-dither matrices (values 0..7) added to the 8-bit color before +// truncation to 5 bits, recreating the RGBA5551 framebuffer grain. +constant int kDitherMagic[16] = { 0, 6, 1, 7, 4, 2, 5, 3, 3, 5, 2, 4, 7, 1, 6, 0 }; +constant int kDitherBayer[16] = { 0, 4, 1, 5, 6, 2, 7, 3, 1, 5, 0, 4, 7, 3, 6, 2 }; + +// Integer hash for the G_CD_NOISE dither: a robust per-pixel + per-frame value 0..7. +// (The sin-based random() above aliases to near-constant on some GPUs, which washed +// the noise out so it was invisible while the ordered matrices worked fine.) +int ditherNoise(int2 p, int frame) { + uint h = uint(p.x) * 1597334677u ^ uint(p.y) * 3812015801u ^ uint(frame) * 2654435761u; + h ^= h >> 16; h *= 2246822519u; + h ^= h >> 13; h *= 3266489917u; + h ^= h >> 16; + return int(h & 7u); +} + +// Applies the RDP's RGB dither + 5-bit quantization, matching the per-primitive +// G_CD_* mode. mode: 0=magic square, 1=bayer, 2=noise (temporal), 3=disable +// (truncate only), >=4 = feature off (full precision passthrough). Dither cells are +// scaled to native resolution via noiseScale so the grain looks hardware-accurate. +float3 applyRdpDither(float3 color, float modeF, float2 fragCoord, float noiseScale, int frameCount) { + int mode = int(modeF + 0.5); + if (mode >= 4) { + return color; + } + float2 nativeCoord = floor(fragCoord * noiseScale); + float d = 0.0; + if (mode == 0) { + int2 cell = int2(nativeCoord) & 3; + d = float(kDitherMagic[cell.y * 4 + cell.x]); + } else if (mode == 1) { + int2 cell = int2(nativeCoord) & 3; + d = float(kDitherBayer[cell.y * 4 + cell.x]); + } else if (mode == 2) { + d = float(ditherNoise(int2(nativeCoord), frameCount)); + } + float3 q = min(floor(clamp(color * 255.0 + d, 0.0, 255.0) / 8.0), 31.0); + return (q * 8.0 + floor(q / 4.0)) / 255.0; +} + +@if(o_palette[0] || o_palette[1]) +// One CI tap: fetch the index (nearest sampler) and look it up in the +// 256-entry palette texture. bank is the CI4 bank entry offset. +float4 paletteTap(thread const texture2d tex, thread const sampler texSmplr, + thread const texture2d pal, thread const sampler palSmplr, + float2 uv, float bank) { + float idx = tex.sample(texSmplr, uv).r; + return pal.sample(palSmplr, float2((idx * 255.0 + bank + 0.5) / 256.0, 0.5)); +} + +// Filtering happens after the palette lookup, like real hardware: +// params.y selects nearest (0), bilinear (1) or N64 three-point (2). +float4 paletteSample(thread const texture2d tex, thread const sampler texSmplr, + thread const texture2d pal, thread const sampler palSmplr, + float2 uv, float2 texSize, float4 params) { + if (params.y > 1.5) { + float2 offset = fract(uv * texSize - float2(0.5)); + offset -= float2(step(1.0, offset.x + offset.y)); + float4 c0 = paletteTap(tex, texSmplr, pal, palSmplr, uv - offset / texSize, params.x); + float4 c1 = paletteTap(tex, texSmplr, pal, palSmplr, uv - float2(offset.x - sign(offset.x), offset.y) / texSize, params.x); + float4 c2 = paletteTap(tex, texSmplr, pal, palSmplr, uv - float2(offset.x, offset.y - sign(offset.y)) / texSize, params.x); + return c0 + abs(offset.x) * (c1 - c0) + abs(offset.y) * (c2 - c0); + } else if (params.y > 0.5) { + float2 t = uv * texSize - 0.5; + float2 f = fract(t); + float2 base = (floor(t) + 0.5) / texSize; + float2 px = float2(1.0, 0.0) / texSize; + float2 py = float2(0.0, 1.0) / texSize; + float4 c00 = paletteTap(tex, texSmplr, pal, palSmplr, base, params.x); + float4 c10 = paletteTap(tex, texSmplr, pal, palSmplr, base + px, params.x); + float4 c01 = paletteTap(tex, texSmplr, pal, palSmplr, base + py, params.x); + float4 c11 = paletteTap(tex, texSmplr, pal, palSmplr, base + px + py, params.x); + return mix(mix(c00, c10, f.x), mix(c01, c11, f.x), f.y); + } else { + return paletteTap(tex, texSmplr, pal, palSmplr, uv, params.x); + } +} +@end + +fragment FragOut fragmentShader( + ProjectedVertex in [[stage_in]], + constant FrameUniforms &frameUniforms [[buffer(0)]], + constant DrawUniforms &drawUniforms [[buffer(1)]] @if(o_textures[0]) , texture2d uTex0 [[texture(0)]], sampler uTex0Smplr [[sampler(0)]] @end @@ -166,7 +361,13 @@ fragment float4 fragmentShader(ProjectedVertex in [[stage_in]], constant FrameUn @if(o_blend[1]) , texture2d uTexBlend1 [[texture(5)]] @end +@if(o_palette[0] || o_palette[1]) + , texture2d uTexPal [[texture(6)]], sampler uTexPalSmplr [[sampler(6)]] +@end ) { + @if(o_uses_lod) + float lodFrac = 0.0; + @end @for(i in 0..2) @if(o_textures[i]) @{s = o_clamp[i][0]} @@ -176,21 +377,75 @@ fragment float4 fragmentShader(ProjectedVertex in [[stage_in]], constant FrameUn float2 vTexCoordAdj@{i} = in.texCoord@{i}; @else @if(s && t) - float2 vTexCoordAdj@{i} = fast::clamp(in.texCoord@{i}, float2(0.5) / texSize@{i}, float2(in.texClampS@{i}, in.texClampT@{i})); + float2 vTexCoordAdj@{i} = fast::clamp(in.texCoord@{i}, float2(0.5) / texSize@{i}, drawUniforms.texture_clamp[@{i}].xy); @elseif(s) - float2 vTexCoordAdj@{i} = float2(fast::clamp(in.texCoord@{i}.x, 0.5 / texSize@{i}.x, in.texClampS@{i}), in.texCoord@{i}.y); + float2 vTexCoordAdj@{i} = float2(fast::clamp(in.texCoord@{i}.x, 0.5 / texSize@{i}.x, drawUniforms.texture_clamp[@{i}].x), in.texCoord@{i}.y); @else - float2 vTexCoordAdj@{i} = float2(in.texCoord@{i}.x, fast::clamp(in.texCoord@{i}.y, 0.5 / texSize@{i}.y, in.texClampT@{i})); + float2 vTexCoordAdj@{i} = float2(in.texCoord@{i}.x, fast::clamp(in.texCoord@{i}.y, 0.5 / texSize@{i}.y, drawUniforms.texture_clamp[@{i}].y)); @end @end - float4 texVal@{i} = hookTexture2D(uTex@{i}, uTex@{i}Smplr, vTexCoordAdj@{i}, texSize@{i}); + @if(i == 0) + @if(o_uses_lod) + // N64 texture LOD (RDP-accurate): max absolute UV derivative, + // linear fraction between tiles, sharpen/detail handling + float2 lodScaled = vTexCoordAdj0 * texSize0; + float2 lodMaxD = max(abs(dfdx(lodScaled)), abs(dfdy(lodScaled))); + float lodMaxDst = max(max(lodMaxD.x, lodMaxD.y) * drawUniforms.lod_params.x, 0.000001); + if (drawUniforms.lod_params.z > 0.5) { // sharpen or detail + lodMaxDst = max(lodMaxDst, drawUniforms.lod_params.y); + } + float lodTileBase = floor(log2(lodMaxDst)); + lodFrac = lodMaxDst / exp2(max(lodTileBase, 0.0)) - 1.0; + if (drawUniforms.lod_params.z > 0.5 && drawUniforms.lod_params.z < 1.5 && lodMaxDst < 1.0) { // sharpen + lodFrac = lodMaxDst - 1.0; + } + if (drawUniforms.lod_params.z > 1.5) { // detail: tile 0 is the detail texture + if (lodFrac < 0.0) { + lodFrac = lodMaxDst; + } + lodTileBase += 1.0; + } else if (lodTileBase >= drawUniforms.lod_max) { + lodFrac = 1.0; + } + if (drawUniforms.lod_params.z > 0.5) { + lodTileBase = max(lodTileBase, 0.0); + } else { + lodFrac = max(lodFrac, 0.0); + } + float lodTile0 = clamp(lodTileBase, 0.0, drawUniforms.lod_max); + float lodTile1 = clamp(lodTileBase + 1.0, 0.0, drawUniforms.lod_max); + // No real LOD level beyond the base (max level 0): the N64 never + // blends a second tile. Small EXTRA_TILE_MIPMAPS textures + // degenerate to one level yet still emit G_TL_LOD+TRILERP; without + // this the combiner blends a stale TEXEL1 by distance. + if (drawUniforms.lod_max < 0.5) { + lodFrac = 0.0; + } + @end + @end + + @if(i == 0) + @if(o_mip_lod) + float4 texVal0 = uTex0.sample(uTex0Smplr, vTexCoordAdj0, level(lodTile0)); + @elseif(o_palette[0]) + float4 texVal0 = paletteSample(uTex0, uTex0Smplr, uTexPal, uTexPalSmplr, vTexCoordAdj0, texSize0, drawUniforms.palette_params[0]); + @else + float4 texVal@{i} = hookTexture2D(uTex@{i}, uTex@{i}Smplr, vTexCoordAdj@{i}, texSize@{i}, drawUniforms.textureFiltering[@{i}]); + @end + @else + @if(o_palette[1]) + float4 texVal1 = paletteSample(uTex1, uTex1Smplr, uTexPal, uTexPalSmplr, vTexCoordAdj1, texSize1, drawUniforms.palette_params[1]); + @else + float4 texVal@{i} = hookTexture2D(uTex@{i}, uTex@{i}Smplr, vTexCoordAdj@{i}, texSize@{i}, drawUniforms.textureFiltering[@{i}]); + @end + @end @if(o_masks[i]) float2 maskSize@{i} = float2(uTexMask@{i}.get_width(), uTexMask@{i}.get_height()); - float4 maskVal@{i} = hookTexture2D(uTexMask@{i}, uTex@{i}Smplr, vTexCoordAdj@{i}, maskSize@{i}); + float4 maskVal@{i} = hookTexture2D(uTexMask@{i}, uTex@{i}Smplr, vTexCoordAdj@{i}, maskSize@{i}, drawUniforms.textureFiltering[@{i}]); @if(o_blend[i]) - float4 blendVal@{i} = hookTexture2D(uTexBlend@{i}, uTex@{i}Smplr, vTexCoordAdj@{i}, texSize@{i}); + float4 blendVal@{i} = hookTexture2D(uTexBlend@{i}, uTex@{i}Smplr, vTexCoordAdj@{i}, texSize@{i}, drawUniforms.textureFiltering[@{i}]); @else float4 blendVal@{i} = float4(0, 0, 0, 0); @end @@ -199,7 +454,18 @@ fragment float4 fragmentShader(ProjectedVertex in [[stage_in]], constant FrameUn @end @end @end - + + @if(o_mip_lod) + // TEXEL1 reads the next mip level of texture 0 + float4 texVal1 = uTex0.sample(uTex0Smplr, vTexCoordAdj0, level(lodTile1)); + @end + + @if(o_two_tile_lod) + // N64 LOD tile selection: TEXEL0's tile clamps to the max level; the + // hardware's second texel is always lod_tile + 1 (real tile 1). + texVal0 = lodTile0 < 0.5 ? texVal0 : texVal1; + @end + @if(o_alpha) float4 texel; @else @@ -253,23 +519,38 @@ fragment float4 fragmentShader(ProjectedVertex in [[stage_in]], constant FrameUn @if(o_fog) @if(o_alpha) - texel = float4(mix(texel.xyz, in.fog.xyz, in.fog.w), texel.w); + texel = float4(mix(texel.xyz, drawUniforms.fog_color.xyz, in.fogFactor), texel.w); @else - texel = mix(texel, in.fog.xyz, in.fog.w); + texel = mix(texel, drawUniforms.fog_color.xyz, in.fogFactor); @end @end @if(o_grayscale) float intensity = (texel.x + texel.y + texel.z) / 3.0; - float3 new_texel = in.grayscale.xyz * intensity; - texel.xyz = mix(texel.xyz, new_texel, in.grayscale.w); + float3 new_texel = drawUniforms.grayscale_color.xyz * intensity; + texel.xyz = mix(texel.xyz, new_texel, drawUniforms.grayscale_color.w); @end @if(o_alpha && o_noise) - float2 coords = screenSpace.xy * noise_scale; - texel.w *= round(saturate(random(float3(floor(coords), noise_frame)) + texel.w - 0.5)); + float2 coords = in.position.xy * frameUniforms.noiseScale; + texel.w *= round(saturate(random(float3(floor(coords), float(frameUniforms.frameCount))) + texel.w - 0.5)); + @end + + // N64 RGB framebuffer dither (per-primitive G_CD_* mode in lod_params.w) + @if(o_alpha) + texel.xyz = applyRdpDither(texel.xyz, drawUniforms.lod_params.w, in.position.xy, frameUniforms.noiseScale, frameUniforms.frameCount); + @else + texel = applyRdpDither(texel, drawUniforms.lod_params.w, in.position.xy, frameUniforms.noiseScale, frameUniforms.frameCount); @end + // HD-replacement debug tint (no-op when debug_tint.w == 0) + @if(o_alpha) + texel.xyz = mix(texel.xyz, drawUniforms.debug_tint.xyz, drawUniforms.debug_tint.w); + @else + texel = mix(texel, drawUniforms.debug_tint.xyz, drawUniforms.debug_tint.w); + @end + + FragOut out; @if(o_alpha) @if(o_alpha_threshold) if (texel.w < 8.0 / 256.0) discard_fragment(); @@ -277,8 +558,12 @@ fragment float4 fragmentShader(ProjectedVertex in [[stage_in]], constant FrameUn @if(o_invisible) texel.w = 0.0; @end - return texel; + out.color = texel; @else - return float4(texel, 1.0); + out.color = float4(texel, 1.0); @end + @if(o_prim_depth) + out.depth = drawUniforms.prim_depth; + @end + return out; } \ No newline at end of file diff --git a/port/shaders/metal/srgb.shader.metal b/port/shaders/metal/srgb.shader.metal new file mode 100644 index 000000000..443eaa362 --- /dev/null +++ b/port/shaders/metal/srgb.shader.metal @@ -0,0 +1,93 @@ +@prism(type='metal', name='Fast3D Metal sRGB Post', version='1.0.0', description='Final-pass linear->sRGB (gamma) output encoding', author='Fast3D') + +#include +using namespace metal; + +// BEGIN VERTEX SHADER +struct FrameUniforms { + int frameCount; + float noiseScale; +}; + +struct DrawUniforms { + int textureFiltering[7]; + float prim_depth; + float lod_max; + float4 inputs[6]; + float4 fog_color; + float4 grayscale_color; + float4 uv_transform[2]; + float4 texture_clamp[2]; + float4 fog_params; + float4 palette_params[2]; + float4 lod_params; + // Game-bindable register file; lockstep with DrawUniforms in gfx_metal.h + float4 uCustom[32]; +}; + +// Mirrors struct TransformUniforms in gfx_rendering_api.h +struct TransformUniforms { + float4 mtx_palette[32]; // 4 float4 rows per slot + float4 y_scale; +}; + +struct FragOut { + float4 color [[color(0)]]; +}; + +struct Vertex { + float4 position [[attribute(@{get_vertex_index()})]]; + @{update_floats(4)} + float mtxSlot [[attribute(@{get_vertex_index()})]]; + @{update_floats(1)} + float2 texCoord0 [[attribute(@{get_vertex_index()})]]; + @{update_floats(2)} +}; + +struct ProjectedVertex { + float2 texCoord0; + float4 position [[position]]; +}; + +vertex ProjectedVertex vertexShader(Vertex in [[stage_in]] + , constant DrawUniforms& drawUniforms [[buffer(2)]] + , constant TransformUniforms& transformUniforms [[buffer(3)]] +) { + ProjectedVertex out; + + // RSP position transform: matrix palette entry selected per vertex + int mtxBase = int(in.mtxSlot + 0.5) * 4; + float4 clipPos = in.position.x * transformUniforms.mtx_palette[mtxBase] + + in.position.y * transformUniforms.mtx_palette[mtxBase + 1] + + in.position.z * transformUniforms.mtx_palette[mtxBase + 2] + + in.position.w * transformUniforms.mtx_palette[mtxBase + 3]; + + // Tile shift/origin/bilerp/size pipeline folded into one transform + out.texCoord0 = float2(in.texCoord0.x * drawUniforms.uv_transform[0].x + drawUniforms.uv_transform[0].y, + in.texCoord0.y * drawUniforms.uv_transform[0].z + drawUniforms.uv_transform[0].w); + + out.position = float4(clipPos.x, clipPos.y * transformUniforms.y_scale.x, (clipPos.z + clipPos.w) / 2.0, clipPos.w); + return out; +} +// END - BEGIN FRAGMENT SHADER + +// Linear -> sRGB transfer (the gamma boost previously applied via an sRGB +// framebuffer pixel format; now applied once as a fullscreen pass). +float4 fromLinear(float4 linearRGB) { + bool3 cutoff = linearRGB.rgb < float3(0.0031308); + float3 higher = float3(1.055) * pow(linearRGB.rgb, float3(1.0 / 2.4)) - float3(0.055); + float3 lower = linearRGB.rgb * float3(12.92); + return float4(mix(higher, lower, float3(cutoff)), linearRGB.a); +} + +fragment FragOut fragmentShader( + ProjectedVertex in [[stage_in]], + constant FrameUniforms &frameUniforms [[buffer(0)]], + constant DrawUniforms &drawUniforms [[buffer(1)]] + , texture2d uTex0 [[texture(0)]], sampler uTex0Smplr [[sampler(0)]] +) { + float4 texel = uTex0.sample(uTex0Smplr, in.texCoord0); + FragOut out; + out.color = fromLinear(float4(texel.rgb, 1.0)); + return out; +} diff --git a/port/shaders/opengl/default.shader.fs b/port/shaders/opengl/default.shader.fs deleted file mode 100644 index 404caae62..000000000 --- a/port/shaders/opengl/default.shader.fs +++ /dev/null @@ -1,211 +0,0 @@ -@prism(type='fragment', name='Fast3D Fragment Shader', version='1.0.0', description='Ported shader to prism', author='Emill & Prism Team') - -@{GLSL_VERSION} - -@if(core_opengl || opengles) -out vec4 vOutColor; -@end - -@for(i in 0..2) - @if(o_textures[i]) - @{attr} vec2 vTexCoord@{i}; - @for(j in 0..2) - @if(o_clamp[i][j]) - @if(j == 0) - @{attr} float vTexClampS@{i}; - @else - @{attr} float vTexClampT@{i}; - @end - @end - @end - @end -@end - -@if(o_fog) @{attr} vec4 vFog; -@if(o_grayscale) @{attr} vec4 vGrayscaleColor; - -@for(i in 0..o_inputs) - @if(o_alpha) - @{attr} vec4 vInput@{i + 1}; - @else - @{attr} vec3 vInput@{i + 1}; - @end -@end - -@if(o_textures[0]) uniform sampler2D uTex0; -@if(o_textures[1]) uniform sampler2D uTex1; - -@if(o_masks[0]) uniform sampler2D uTexMask0; -@if(o_masks[1]) uniform sampler2D uTexMask1; - -@if(o_blend[0]) uniform sampler2D uTexBlend0; -@if(o_blend[1]) uniform sampler2D uTexBlend1; - -uniform int frame_count; -uniform float noise_scale; - -uniform int texture_width[2]; -uniform int texture_height[2]; -uniform int texture_filtering[2]; - -#define TEX_OFFSET(off) @{texture}(tex, texCoord - off / texSize) -#define WRAP(x, low, high) mod((x)-(low), (high)-(low)) + (low) - -float random(in vec3 value) { - float random = dot(sin(value), vec3(12.9898, 78.233, 37.719)); - return fract(sin(random) * 143758.5453); -} - -vec4 fromLinear(vec4 linearRGB){ - bvec3 cutoff = lessThan(linearRGB.rgb, vec3(0.0031308)); - vec3 higher = vec3(1.055)*pow(linearRGB.rgb, vec3(1.0/2.4)) - vec3(0.055); - vec3 lower = linearRGB.rgb * vec3(12.92); - return vec4(mix(higher, lower, cutoff), linearRGB.a); -} - -vec4 filter3point(in sampler2D tex, in vec2 texCoord, in vec2 texSize) { - vec2 offset = fract(texCoord*texSize - vec2(0.5)); - offset -= step(1.0, offset.x + offset.y); - vec4 c0 = TEX_OFFSET(offset); - vec4 c1 = TEX_OFFSET(vec2(offset.x - sign(offset.x), offset.y)); - vec4 c2 = TEX_OFFSET(vec2(offset.x, offset.y - sign(offset.y))); - return c0 + abs(offset.x)*(c1-c0) + abs(offset.y)*(c2-c0); -} - -vec4 hookTexture2D(in int id, sampler2D tex, in vec2 uv, in vec2 texSize) { -@if(o_three_point_filtering) - if(texture_filtering[id] == @{FILTER_THREE_POINT}) { - return filter3point(tex, uv, texSize); - } -@end - return @{texture}(tex, uv); -} - -#define TEX_SIZE(tex) vec2(texture_width[tex], texture_height[tex]) - -void main() { - @for(i in 0..2) - @if(o_textures[i]) - @{s = o_clamp[i][0]} - @{t = o_clamp[i][1]} - - vec2 texSize@{i} = TEX_SIZE(@{i}); - - @if(!s && !t) - vec2 vTexCoordAdj@{i} = vTexCoord@{i}; - @else - @if(s && t) - vec2 vTexCoordAdj@{i} = clamp(vTexCoord@{i}, 0.5 / texSize@{i}, vec2(vTexClampS@{i}, vTexClampT@{i})); - @elseif(s) - vec2 vTexCoordAdj@{i} = vec2(clamp(vTexCoord@{i}.s, 0.5 / texSize@{i}.s, vTexClampS@{i}), vTexCoord@{i}.t); - @else - vec2 vTexCoordAdj@{i} = vec2(vTexCoord@{i}.s, clamp(vTexCoord@{i}.t, 0.5 / texSize@{i}.t, vTexClampT@{i})); - @end - @end - - vec4 texVal@{i} = hookTexture2D(@{i}, uTex@{i}, vTexCoordAdj@{i}, texSize@{i}); - - @if(o_masks[i]) - @if(opengles) - vec2 maskSize@{i} = vec2(textureSize(uTexMask@{i}, 0)); - @else - vec2 maskSize@{i} = textureSize(uTexMask@{i}, 0); - @end - - vec4 maskVal@{i} = hookTexture2D(@{i}, uTexMask@{i}, vTexCoordAdj@{i}, maskSize@{i}); - - @if(o_blend[i]) - vec4 blendVal@{i} = hookTexture2D(@{i}, uTexBlend@{i}, vTexCoordAdj@{i}, texSize@{i}); - @else - vec4 blendVal@{i} = vec4(0, 0, 0, 0); - @end - - texVal@{i} = mix(texVal@{i}, blendVal@{i}, maskVal@{i}.a); - @end - @end - @end - - @if(o_alpha) - vec4 texel; - @else - vec3 texel; - @end - - @if(o_2cyc) - @{f_range = 2} - @else - @{f_range = 1} - @end - - @for(c in 0..f_range) - @if(c == 1) - @if(o_alpha) - @if(o_c[c][1][2] == SHADER_COMBINED) - texel.a = WRAP(texel.a, -1.01, 1.01); - @else - texel.a = WRAP(texel.a, -0.51, 1.51); - @end - @end - - @if(o_c[c][0][2] == SHADER_COMBINED) - texel.rgb = WRAP(texel.rgb, -1.01, 1.01); - @else - texel.rgb = WRAP(texel.rgb, -0.51, 1.51); - @end - @end - - @if(!o_color_alpha_same[c] && o_alpha) - texel = vec4(@{ - append_formula(o_c[c], o_do_single[c][0], - o_do_multiply[c][0], o_do_mix[c][0], false, false, true, c == 0) - }, @{append_formula(o_c[c], o_do_single[c][1], - o_do_multiply[c][1], o_do_mix[c][1], true, true, true, c == 0) - }); - @else - texel = @{append_formula(o_c[c], o_do_single[c][0], - o_do_multiply[c][0], o_do_mix[c][0], o_alpha, false, - o_alpha, c == 0)}; - @end - @end - - texel = WRAP(texel, -0.51, 1.51); - texel = clamp(texel, 0.0, 1.0); - // TODO discard if alpha is 0? - @if(o_fog) - @if(o_alpha) - texel = vec4(mix(texel.rgb, vFog.rgb, vFog.a), texel.a); - @else - texel = mix(texel, vFog.rgb, vFog.a); - @end - @end - - @if(o_texture_edge && o_alpha) - if (texel.a > 0.19) texel.a = 1.0; else discard; - @end - - @if(o_alpha && o_noise) - texel.a *= floor(clamp(random(vec3(floor(gl_FragCoord.xy * noise_scale), float(frame_count))) + texel.a, 0.0, 1.0)); - @end - - @if(o_grayscale) - float intensity = (texel.r + texel.g + texel.b) / 3.0; - vec3 new_texel = vGrayscaleColor.rgb * intensity; - texel.rgb = mix(texel.rgb, new_texel, vGrayscaleColor.a); - @end - - @if(o_alpha) - @if(o_alpha_threshold) - if (texel.a < 8.0 / 256.0) discard; - @end - @if(o_invisible) - texel.a = 0.0; - @end - @{vOutColor} = texel; - @else - @{vOutColor} = vec4(texel, 1.0); - @end - - @if(srgb_mode) - @{vOutColor} = fromLinear(@{vOutColor}); - @end -} \ No newline at end of file diff --git a/port/shaders/opengl/default.shader.glsl b/port/shaders/opengl/default.shader.glsl new file mode 100644 index 000000000..d5e72328a --- /dev/null +++ b/port/shaders/opengl/default.shader.glsl @@ -0,0 +1,328 @@ +@prism(type='fragment', name='Fast3D Fragment Shader', version='1.0.0', description='Ported shader to prism', author='Emill & Prism Team') + +@{GLSL_VERSION} + +@if(VERTEX_SHADER) + @include("shaders/opengl/include/fast3d_vs.glsli") + +@else + @if(core_opengl || opengles) + out vec4 vOutColor; + @end + + @for(i in 0..2) + @if(o_textures[i]) + @{attr} vec2 vTexCoord@{i}; + @end + @end + + @if(o_textures[0] || o_textures[1]) + uniform vec4 uTexClamp[2]; + @end + + @if(o_fog) @{attr} float vFogFactor; + + @if(o_shade) + @if(o_alpha) + @{attr} vec4 vShade; + @else + @{attr} vec3 vShade; + @end + @end + + @if(o_has_inputs) + uniform vec4 uInputs[@{o_inputs}]; + @end + @if(o_fog) + uniform vec4 uFogColor; + @end + @if(o_grayscale) + uniform vec4 uGrayscaleColor; + @end + + @if(o_textures[0]) uniform sampler2D uTex0; + @if(o_textures[1]) uniform sampler2D uTex1; + + @if(o_masks[0]) uniform sampler2D uTexMask0; + @if(o_masks[1]) uniform sampler2D uTexMask1; + + @if(o_blend[0]) uniform sampler2D uTexBlend0; + @if(o_blend[1]) uniform sampler2D uTexBlend1; + + uniform int frame_count; + uniform float noise_scale; + + // Game-bindable custom uniform registers; [0]-[1] are engine built-ins + // (frame/time/delta, resolution). See CustomUniforms in gfx_rendering_api.h. + uniform vec4 uCustom[32]; + + @if(o_prim_depth) + uniform float prim_depth; + @end + + @if(o_uses_lod) + uniform float lod_max; + @end + // Declared unconditionally: .w carries the RGB dither mode used by every draw. + uniform vec4 uLodParams; // x=res scale, y=prim_lod_min, z=G_TD mode, w=RGB dither mode + uniform vec4 uDebugTint; + + uniform int texture_width[2]; + uniform int texture_height[2]; + uniform int texture_filtering[2]; + + @include("shaders/opengl/include/filter.glsli") + + @include("shaders/opengl/include/palette.glsli") + + // N64 RDP ordered-dither matrices (values 0..7); see applyRdpDither. + const int kDitherMagic[16] = int[16](0, 6, 1, 7, 4, 2, 5, 3, 3, 5, 2, 4, 7, 1, 6, 0); + const int kDitherBayer[16] = int[16](0, 4, 1, 5, 6, 2, 7, 3, 1, 5, 0, 4, 7, 3, 6, 2); + + // Integer hash for the G_CD_NOISE dither: robust per-pixel + per-frame value 0..7 + // (a sin-based hash aliases to near-constant on some GPUs, washing the noise out). + int ditherNoise(ivec2 p, int frame) { + uint h = uint(p.x) * 1597334677u ^ uint(p.y) * 3812015801u ^ uint(frame) * 2654435761u; + h ^= h >> 16u; h *= 2246822519u; + h ^= h >> 13u; h *= 3266489917u; + h ^= h >> 16u; + return int(h & 7u); + } + + // RDP RGB dither + RGBA5551 quantization. mode: 0=magic square, 1=bayer, + // 2=noise (temporal), 3=disable (truncate only), >=4 = off (full precision). + // Hash inlined (this shader doesn't pull in noise.glsli's random()). + vec3 applyRdpDither(vec3 color, float modeF, vec2 fragCoord, float noiseScaleV, int frameCountV) { + int mode = int(modeF + 0.5); + if (mode >= 4) { + return color; + } + vec2 nativeCoord = floor(fragCoord * noiseScaleV); + float d = 0.0; + if (mode == 0) { + ivec2 cell = ivec2(nativeCoord) & 3; + d = float(kDitherMagic[cell.y * 4 + cell.x]); + } else if (mode == 1) { + ivec2 cell = ivec2(nativeCoord) & 3; + d = float(kDitherBayer[cell.y * 4 + cell.x]); + } else if (mode == 2) { + d = float(ditherNoise(ivec2(nativeCoord), frameCountV)); + } + vec3 q = min(floor(clamp(color * 255.0 + d, 0.0, 255.0) / 8.0), 31.0); + return (q * 8.0 + floor(q / 4.0)) / 255.0; + } + + #define TEX_SIZE(tex) vec2(texture_width[tex], texture_height[tex]) + + void main() { + @if(o_uses_lod) + float lodFrac = 0.0; + @end + @for(i in 0..2) + @if(o_textures[i]) + @{s = o_clamp[i][0]} + @{t = o_clamp[i][1]} + + vec2 texSize@{i} = TEX_SIZE(@{i}); + + @if(!s && !t) + vec2 vTexCoordAdj@{i} = vTexCoord@{i}; + @else + @if(s && t) + vec2 vTexCoordAdj@{i} = clamp(vTexCoord@{i}, 0.5 / texSize@{i}, uTexClamp[@{i}].xy); + @elseif(s) + vec2 vTexCoordAdj@{i} = vec2(clamp(vTexCoord@{i}.s, 0.5 / texSize@{i}.s, uTexClamp[@{i}].x), vTexCoord@{i}.t); + @else + vec2 vTexCoordAdj@{i} = vec2(vTexCoord@{i}.s, clamp(vTexCoord@{i}.t, 0.5 / texSize@{i}.t, uTexClamp[@{i}].y)); + @end + @end + + @if(i == 0) + @if(o_uses_lod) + // N64 texture LOD (RDP-accurate): max absolute UV derivative, + // linear fraction between tiles, sharpen/detail handling + vec2 lodScaled = vTexCoordAdj0 * texSize0; + vec2 lodMaxD = max(abs(dFdx(lodScaled)), abs(dFdy(lodScaled))); + float lodMaxDst = max(max(lodMaxD.x, lodMaxD.y) * uLodParams.x, 0.000001); + if (uLodParams.z > 0.5) { // sharpen or detail + lodMaxDst = max(lodMaxDst, uLodParams.y); + } + float lodTileBase = floor(log2(lodMaxDst)); + lodFrac = lodMaxDst / exp2(max(lodTileBase, 0.0)) - 1.0; + if (uLodParams.z > 0.5 && uLodParams.z < 1.5 && lodMaxDst < 1.0) { // sharpen + lodFrac = lodMaxDst - 1.0; + } + if (uLodParams.z > 1.5) { // detail: tile 0 is the detail texture + if (lodFrac < 0.0) { + lodFrac = lodMaxDst; + } + lodTileBase += 1.0; + } else if (lodTileBase >= lod_max) { + lodFrac = 1.0; + } + if (uLodParams.z > 0.5) { + lodTileBase = max(lodTileBase, 0.0); + } else { + lodFrac = max(lodFrac, 0.0); + } + float lodTile0 = clamp(lodTileBase, 0.0, lod_max); + float lodTile1 = clamp(lodTileBase + 1.0, 0.0, lod_max); + // No real LOD level beyond the base (max level 0): the N64 + // never blends a second tile, so kill the LOD fraction. + // Small EXTRA_TILE_MIPMAPS textures degenerate to one + // level yet still emit G_TL_LOD+TRILERP; without this the + // combiner blends a stale TEXEL1 by distance. + if (lod_max < 0.5) { + lodFrac = 0.0; + } + @end + @end + + @if(i == 0) + @if(o_mip_lod) + vec4 texVal0 = textureLod(uTex0, vTexCoordAdj0, lodTile0); + @elseif(o_palette[0]) + vec4 texVal0 = paletteSample(uTex0, vTexCoordAdj0, texSize0, uPaletteParams[0]); + @else + vec4 texVal@{i} = hookTexture2D(@{i}, uTex@{i}, vTexCoordAdj@{i}, texSize@{i}); + @end + @else + @if(o_palette[1]) + vec4 texVal1 = paletteSample(uTex1, vTexCoordAdj1, texSize1, uPaletteParams[1]); + @else + vec4 texVal@{i} = hookTexture2D(@{i}, uTex@{i}, vTexCoordAdj@{i}, texSize@{i}); + @end + @end + + @if(o_masks[i]) + @if(opengles) + vec2 maskSize@{i} = vec2(textureSize(uTexMask@{i}, 0)); + @else + vec2 maskSize@{i} = textureSize(uTexMask@{i}, 0); + @end + + vec4 maskVal@{i} = hookTexture2D(@{i}, uTexMask@{i}, vTexCoordAdj@{i}, maskSize@{i}); + + @if(o_blend[i]) + vec4 blendVal@{i} = hookTexture2D(@{i}, uTexBlend@{i}, vTexCoordAdj@{i}, texSize@{i}); + @else + vec4 blendVal@{i} = vec4(0, 0, 0, 0); + @end + + texVal@{i} = mix(texVal@{i}, blendVal@{i}, maskVal@{i}.a); + @end + @end + @end + + @if(o_mip_lod) + // TEXEL1 reads the next mip level of texture 0 + vec4 texVal1 = textureLod(uTex0, vTexCoordAdj0, lodTile1); + @end + + @if(o_two_tile_lod) + // N64 LOD tile selection: TEXEL0's tile is clamped to the max level, + // but the hardware's second texel is always lod_tile + 1 — at + // magnification TEXEL1 still reads the real tile 1 (Paper Mario's + // sprite shading relies on this with a stale G_TL_LOD). + texVal0 = lodTile0 < 0.5 ? texVal0 : texVal1; + @end + + @if(o_alpha) + vec4 texel; + @else + vec3 texel; + @end + + @if(o_2cyc) + @{f_range = 2} + @else + @{f_range = 1} + @end + + @for(c in 0..f_range) + @if(c == 1) + @if(o_alpha) + @if(o_c[c][1][2] == SHADER_COMBINED) + texel.a = WRAP(texel.a, -1.01, 1.01); + @else + texel.a = WRAP(texel.a, -0.51, 1.51); + @end + @end + + @if(o_c[c][0][2] == SHADER_COMBINED) + texel.rgb = WRAP(texel.rgb, -1.01, 1.01); + @else + texel.rgb = WRAP(texel.rgb, -0.51, 1.51); + @end + @end + + @if(!o_color_alpha_same[c] && o_alpha) + texel = vec4(@{ + append_formula(o_c[c], o_do_single[c][0], + o_do_multiply[c][0], o_do_mix[c][0], false, false, true, c == 0) + }, @{append_formula(o_c[c], o_do_single[c][1], + o_do_multiply[c][1], o_do_mix[c][1], true, true, true, c == 0) + }); + @else + texel = @{append_formula(o_c[c], o_do_single[c][0], + o_do_multiply[c][0], o_do_mix[c][0], o_alpha, false, + o_alpha, c == 0)}; + @end + @end + + texel = WRAP(texel, -0.51, 1.51); + texel = clamp(texel, 0.0, 1.0); + // TODO discard if alpha is 0? + @if(o_fog) + @if(o_alpha) + texel = vec4(mix(texel.rgb, uFogColor.rgb, vFogFactor), texel.a); + @else + texel = mix(texel, uFogColor.rgb, vFogFactor); + @end + @end + + @if(o_texture_edge && o_alpha) + if (texel.a > 0.19) texel.a = 1.0; else discard; + @end + + @if(o_alpha && o_noise) + texel.a *= floor(clamp(random(vec3(floor(gl_FragCoord.xy * noise_scale), float(frame_count))) + texel.a, 0.0, 1.0)); + @end + + @if(o_grayscale) + float intensity = (texel.r + texel.g + texel.b) / 3.0; + vec3 new_texel = uGrayscaleColor.rgb * intensity; + texel.rgb = mix(texel.rgb, new_texel, uGrayscaleColor.a); + @end + + // N64 RGB framebuffer dither (per-primitive G_CD_* mode in uLodParams.w) + @if(o_alpha) + texel.rgb = applyRdpDither(texel.rgb, uLodParams.w, gl_FragCoord.xy, noise_scale, frame_count); + @else + texel = applyRdpDither(texel, uLodParams.w, gl_FragCoord.xy, noise_scale, frame_count); + @end + + // HD-replacement debug tint (no-op when uDebugTint.a == 0) + @if(o_alpha) + texel.rgb = mix(texel.rgb, uDebugTint.rgb, uDebugTint.a); + @else + texel = mix(texel, uDebugTint.rgb, uDebugTint.a); + @end + + @if(o_alpha) + @if(o_alpha_threshold) + if (texel.a < 8.0 / 256.0) discard; + @end + @if(o_invisible) + texel.a = 0.0; + @end + @{vOutColor} = texel; + @else + @{vOutColor} = vec4(texel, 1.0); + @end + + @if(o_prim_depth) + gl_FragDepth = prim_depth; + @end + } +@end \ No newline at end of file diff --git a/port/shaders/opengl/default.shader.vs b/port/shaders/opengl/default.shader.vs deleted file mode 100644 index cf0f62765..000000000 --- a/port/shaders/opengl/default.shader.vs +++ /dev/null @@ -1,79 +0,0 @@ -@prism(type='fragment', name='Fast3D Fragment Shader', version='1.0.0', description='Ported shader to prism', author='Emill & Prism Team') - -@{GLSL_VERSION} - -@{attr} vec4 aVtxPos; - -@for(i in 0..2) - @if(o_textures[i]) - @{attr} vec2 aTexCoord@{i}; - @{out} vec2 vTexCoord@{i}; - @{update_floats(2)} - @for(j in 0..2) - @if(o_clamp[i][j]) - @if(j == 0) - @{attr} float aTexClampS@{i}; - @{out} float vTexClampS@{i}; - @else - @{attr} float aTexClampT@{i}; - @{out} float vTexClampT@{i}; - @end - @{update_floats(1)} - @end - @end - @end -@end - -@if(o_fog) - @{attr} vec4 aFog; - @{out} vec4 vFog; - @{update_floats(4)} -@end - -@if(o_grayscale) - @{attr} vec4 aGrayscaleColor; - @{out} vec4 vGrayscaleColor; - @{update_floats(4)} -@end - -@for(i in 0..o_inputs) - @if(o_alpha) - @{attr} vec4 aInput@{i + 1}; - @{out} vec4 vInput@{i + 1}; - @{update_floats(4)} - @else - @{attr} vec3 aInput@{i + 1}; - @{out} vec3 vInput@{i + 1}; - @{update_floats(3)} - @end -@end - -void main() { - @for(i in 0..2) - @if(o_textures[i]) - vTexCoord@{i} = aTexCoord@{i}; - @for(j in 0..2) - @if(o_clamp[i][j]) - @if(j == 0) - vTexClampS@{i} = aTexClampS@{i}; - @else - vTexClampT@{i} = aTexClampT@{i}; - @end - @end - @end - @end - @end - @if(o_fog) - vFog = aFog; - @end - @if(o_grayscale) - vGrayscaleColor = aGrayscaleColor; - @end - @for(i in 0..o_inputs) - vInput@{i + 1} = aInput@{i + 1}; - @end - gl_Position = aVtxPos; - @if(opengles) - gl_Position.z *= 0.3f; - @end -} \ No newline at end of file diff --git a/port/shaders/opengl/include/fast3d_vs.glsli b/port/shaders/opengl/include/fast3d_vs.glsli new file mode 100644 index 000000000..e42508b68 --- /dev/null +++ b/port/shaders/opengl/include/fast3d_vs.glsli @@ -0,0 +1,171 @@ +@prism(type='fragment', name='Fast3D Vertex Stage', version='1.0.0', description='Complete default vertex shader body; custom shaders @include this to reuse the standard vertex pipeline', author='Fast3D') + @{attr} vec4 aVtxPos; + @{attr} float aMtxSlot; + @{update_floats(1)} + + // Matrix palette: 4 vec4 rows per slot; clip = obj.x*r0 + obj.y*r1 + obj.z*r2 + obj.w*r3 + uniform vec4 uMtxPalette[32]; + uniform vec4 uYScale; + + // Game-bindable custom uniform registers; [0]-[1] are engine built-ins + // (frame/time/delta, resolution). See CustomUniforms in gfx_rendering_api.h. + uniform vec4 uCustom[32]; + + @for(i in 0..2) + @if(o_textures[i]) + @{attr} vec2 aTexCoord@{i}; + @{out} vec2 vTexCoord@{i}; + @{update_floats(2)} + @end + @end + + @if(o_textures[0] || o_textures[1]) + uniform vec4 uUvTransform[2]; + @end + + @if(o_fog) + @{out} float vFogFactor; + uniform vec4 uFogParams; + @end + + @if(o_shade || o_lighting) + @if(o_alpha) + @{attr} vec4 aShade; + @{update_floats(4)} + @else + @{attr} vec3 aShade; + @{update_floats(3)} + @end + @end + @if(o_shade) + @if(o_alpha) + @{out} vec4 vShade; + @else + @{out} vec3 vShade; + @end + @end + + @if(o_lighting) + uniform vec4 uAmbient; + uniform int uNumLights; + uniform vec4 uLights[96]; + @if(o_point_lighting) + uniform vec4 uMvRows[3]; + uniform vec4 uMvCols[3]; + @end + @end + @if(o_texgen) + uniform vec4 uLookatX; + uniform vec4 uLookatY; + @if(o_textures[0]) uniform vec4 uTexgen0; + @if(o_textures[1]) uniform vec4 uTexgen1; + @end + + void main() { + // RSP position transform: matrix palette entry selected per vertex + int mtxBase = int(aMtxSlot + 0.5) * 4; + vec4 clipPos = aVtxPos.x * uMtxPalette[mtxBase] + aVtxPos.y * uMtxPalette[mtxBase + 1] + + aVtxPos.z * uMtxPalette[mtxBase + 2] + aVtxPos.w * uMtxPalette[mtxBase + 3]; + + @for(i in 0..2) + @if(o_textures[i]) + // Tile shift/origin/bilerp/size pipeline folded into one transform + vTexCoord@{i} = vec2(aTexCoord@{i}.x * uUvTransform[@{i}].x + uUvTransform[@{i}].y, + aTexCoord@{i}.y * uUvTransform[@{i}].z + uUvTransform[@{i}].w); + @end + @end + @if(o_fog) + // N64 RSP fog from clip-space z/w; uFogParams.w selects the source + // (0: computed, 1: constant register, 2: legacy vertex-alpha fallback) + float fogW = abs(clipPos.w) < 0.001 ? 0.001 : clipPos.w; + float fogWinv = 1.0 / fogW; + if (fogWinv < 0.0) { + fogWinv = 32767.0; + } + float fogCalc = clamp(clipPos.z * fogWinv * uFogParams.x + uFogParams.y, 0.0, 255.0) / 255.0; + @if(o_shade && o_alpha) + vFogFactor = uFogParams.w > 1.5 ? aShade.a : (uFogParams.w > 0.5 ? uFogParams.z : fogCalc); + @else + vFogFactor = uFogParams.w > 0.5 ? uFogParams.z : fogCalc; + @end + @end + @if(o_texgen) + // N64 texgen: project the vertex normal onto the lookat vectors, then + // run the result through the standard tile/scale UV pipeline (folded + // into the per-draw uTexgen linear transforms). + float texgenDotX = clamp(dot(aShade.xyz, uLookatX.xyz) / 127.0, -1.0, 1.0); + float texgenDotY = clamp(dot(aShade.xyz, uLookatY.xyz) / 127.0, -1.0, 1.0); + @if(o_texgen_linear) + texgenDotX = acos(-texgenDotX) * 0.159155; + texgenDotY = acos(-texgenDotY) * 0.159155; + @else + texgenDotX = (texgenDotX + 1.0) / 4.0; + texgenDotY = (texgenDotY + 1.0) / 4.0; + @end + @if(o_textures[0]) + vTexCoord0 = vec2(texgenDotX * uTexgen0.x + uTexgen0.y, texgenDotY * uTexgen0.z + uTexgen0.w); + @end + @if(o_textures[1]) + vTexCoord1 = vec2(texgenDotX * uTexgen1.x + uTexgen1.y, texgenDotY * uTexgen1.z + uTexgen1.w); + @end + @end + @if(o_shade && o_alpha) + // Standard fog forces shade alpha to 1.0 (the factor rides vFogFactor); + // blend-color mode (fog mode 1) preserves the vertex alpha. + float shadeAlpha = aShade.a; + @if(o_fog) + if (uFogParams.w < 0.5 || uFogParams.w > 1.5) { + shadeAlpha = 1.0; + } + @end + @end + @if(o_point_lighting) + // World-space position derived from the object-space vertex position + vec3 worldPos = vec3(dot(aVtxPos, uMvCols[0]), dot(aVtxPos, uMvCols[1]), dot(aVtxPos, uMvCols[2])); + @end + @if(o_shade) + @if(o_lighting) + // N64 RSP lighting: aShade carries the raw signed vertex normal + vec3 litColor = uAmbient.rgb; + for (int i = 0; i < uNumLights; i++) { + float intensity = 0.0; + @if(o_point_lighting) + if (uLights[i * 3].w > 0.5) { + vec3 distVec = uLights[i * 3 + 2].xyz - worldPos; + float distSq = distVec.x * distVec.x + distVec.y * distVec.y + distVec.z * distVec.z * 2.0; + float dist = sqrt(distSq); + vec3 lightModel = vec3(dot(distVec, uMvRows[0].xyz), dot(distVec, uMvRows[1].xyz), dot(distVec, uMvRows[2].xyz)); + vec3 lightIntensity = clamp(4.0 * lightModel / distSq, -1.0, 1.0); + float totalIntensity = clamp(dot(lightIntensity, aShade.xyz), -1.0, 1.0); + float distF = floor(dist); + float attenuation = (distF * uLights[i * 3 + 1].w * 2.0 + distF * distF * uLights[i * 3 + 2].w / 8.0) / 65535.0 + 1.0; + intensity = totalIntensity / attenuation; + } else { + intensity = dot(aShade.xyz, uLights[i * 3 + 1].xyz) / 127.0; + } + @else + intensity = dot(aShade.xyz, uLights[i * 3 + 1].xyz) / 127.0; + @end + if (intensity > 0.0) { + litColor += intensity * uLights[i * 3].rgb; + } + } + litColor = min(litColor, vec3(1.0)); + @if(o_alpha) + vShade = vec4(litColor, shadeAlpha); + @else + vShade = litColor; + @end + @else + @if(o_alpha) + vShade = vec4(aShade.rgb, shadeAlpha); + @else + vShade = aShade; + @end + @end + @end + gl_Position = vec4(clipPos.x, clipPos.y * uYScale.x, clipPos.z, clipPos.w); + @if(opengles) + gl_Position.z *= 0.3f; + @end + } diff --git a/port/shaders/opengl/include/filter.glsli b/port/shaders/opengl/include/filter.glsli new file mode 100644 index 000000000..23414cd10 --- /dev/null +++ b/port/shaders/opengl/include/filter.glsli @@ -0,0 +1,30 @@ +@prism(type='fragment', name='Fast3D Filtering', version='1.0.0', description='WRAP/TEX_OFFSET macros - sRGB conversion - N64 three-point filtering and the hookTexture2D dispatcher', author='Fast3D') + #define TEX_OFFSET(off) @{texture}(tex, texCoord - off / texSize) + #define WRAP(x, low, high) mod((x)-(low), (high)-(low)) + (low) + + @include("shaders/opengl/include/noise.glsli") + + vec4 fromLinear(vec4 linearRGB){ + bvec3 cutoff = lessThan(linearRGB.rgb, vec3(0.0031308)); + vec3 higher = vec3(1.055)*pow(linearRGB.rgb, vec3(1.0/2.4)) - vec3(0.055); + vec3 lower = linearRGB.rgb * vec3(12.92); + return vec4(mix(higher, lower, cutoff), linearRGB.a); + } + + vec4 filter3point(in sampler2D tex, in vec2 texCoord, in vec2 texSize) { + vec2 offset = fract(texCoord*texSize - vec2(0.5)); + offset -= step(1.0, offset.x + offset.y); + vec4 c0 = TEX_OFFSET(offset); + vec4 c1 = TEX_OFFSET(vec2(offset.x - sign(offset.x), offset.y)); + vec4 c2 = TEX_OFFSET(vec2(offset.x, offset.y - sign(offset.y))); + return c0 + abs(offset.x)*(c1-c0) + abs(offset.y)*(c2-c0); + } + + vec4 hookTexture2D(in int id, sampler2D tex, in vec2 uv, in vec2 texSize) { + @if(o_three_point_filtering) + if(texture_filtering[id] == @{FILTER_THREE_POINT}) { + return filter3point(tex, uv, texSize); + } + @end + return @{texture}(tex, uv); + } diff --git a/port/shaders/opengl/include/noise.glsli b/port/shaders/opengl/include/noise.glsli new file mode 100644 index 000000000..9b7baf840 --- /dev/null +++ b/port/shaders/opengl/include/noise.glsli @@ -0,0 +1,5 @@ +@prism(type='fragment', name='Fast3D Noise', version='1.0.0', description='Hash-based random() used for N64 noise; expects frame_count/noise_scale uniforms', author='Fast3D') + float random(in vec3 value) { + float random = dot(sin(value), vec3(12.9898, 78.233, 37.719)); + return fract(sin(random) * 143758.5453); + } diff --git a/port/shaders/opengl/include/palette.glsli b/port/shaders/opengl/include/palette.glsli new file mode 100644 index 000000000..9e830ebe1 --- /dev/null +++ b/port/shaders/opengl/include/palette.glsli @@ -0,0 +1,38 @@ +@prism(type='fragment', name='Fast3D CI Palettes', version='1.0.0', description='Palette tap/sample helpers for color-index textures; filtering applied after the palette lookup', author='Fast3D') + @if(o_palette[0] || o_palette[1]) + uniform sampler2D uTexPal; + uniform vec4 uPaletteParams[2]; + + // One CI tap: fetch the index (nearest sampler) and look it up in the + // 256-entry palette texture. params.x is the CI4 bank entry offset. + vec4 paletteTap(in sampler2D tex, in vec2 uv, in float bank) { + float idx = @{texture}(tex, uv).r; + return @{texture}(uTexPal, vec2((idx * 255.0 + bank + 0.5) / 256.0, 0.5)); + } + + // Filtering must happen after the palette lookup, like real hardware: + // params.y selects nearest (0), bilinear (1) or N64 three-point (2). + vec4 paletteSample(in sampler2D tex, in vec2 uv, in vec2 texSize, in vec4 params) { + if (params.y > 1.5) { + vec2 offset = fract(uv * texSize - vec2(0.5)); + offset -= step(1.0, offset.x + offset.y); + vec4 c0 = paletteTap(tex, uv - offset / texSize, params.x); + vec4 c1 = paletteTap(tex, uv - vec2(offset.x - sign(offset.x), offset.y) / texSize, params.x); + vec4 c2 = paletteTap(tex, uv - vec2(offset.x, offset.y - sign(offset.y)) / texSize, params.x); + return c0 + abs(offset.x) * (c1 - c0) + abs(offset.y) * (c2 - c0); + } else if (params.y > 0.5) { + vec2 t = uv * texSize - 0.5; + vec2 f = fract(t); + vec2 base = (floor(t) + 0.5) / texSize; + vec2 px = vec2(1.0, 0.0) / texSize; + vec2 py = vec2(0.0, 1.0) / texSize; + vec4 c00 = paletteTap(tex, base, params.x); + vec4 c10 = paletteTap(tex, base + px, params.x); + vec4 c01 = paletteTap(tex, base + py, params.x); + vec4 c11 = paletteTap(tex, base + px + py, params.x); + return mix(mix(c00, c10, f.x), mix(c01, c11, f.x), f.y); + } else { + return paletteTap(tex, uv, params.x); + } + } + @end diff --git a/port/shaders/opengl/srgb.shader.glsl b/port/shaders/opengl/srgb.shader.glsl new file mode 100644 index 000000000..9f69320a7 --- /dev/null +++ b/port/shaders/opengl/srgb.shader.glsl @@ -0,0 +1,30 @@ +@prism(type='fragment', name='Fast3D OpenGL sRGB Post', version='1.0.0', description='Final-pass linear->sRGB (gamma) output encoding', author='Fast3D') + +@{GLSL_VERSION} + +@if(VERTEX_SHADER) + @include("shaders/opengl/include/fast3d_vs.glsli") + +@else + @if(core_opengl || opengles) + out vec4 vOutColor; + @end + + @{attr} vec2 vTexCoord0; + + uniform sampler2D uTex0; + + // Linear -> sRGB transfer (the gamma boost previously baked into every + // fragment shader via srgb_mode; now applied once as a fullscreen pass). + vec4 fromLinear(vec4 linearRGB){ + bvec3 cutoff = lessThan(linearRGB.rgb, vec3(0.0031308)); + vec3 higher = vec3(1.055)*pow(linearRGB.rgb, vec3(1.0/2.4)) - vec3(0.055); + vec3 lower = linearRGB.rgb * vec3(12.92); + return vec4(mix(higher, lower, cutoff), linearRGB.a); + } + + void main() { + vec4 texel = @{texture}(uTex0, vTexCoord0); + @{vOutColor} = fromLinear(vec4(texel.rgb, 1.0)); + } +@end diff --git a/port/shaders/vulkan/default.shader.glsl b/port/shaders/vulkan/default.shader.glsl new file mode 100644 index 000000000..db1d4d772 --- /dev/null +++ b/port/shaders/vulkan/default.shader.glsl @@ -0,0 +1,308 @@ +@prism(type='fragment', name='Fast3D Vulkan Shader', version='1.0.0', description='Fast3D combiner shader for Vulkan', author='Ghostship') + +#version 450 +@include("shaders/vulkan/include/common.glsli") + +@if(VERTEX_SHADER) + @include("shaders/vulkan/include/fast3d_vs.glsli") + +@else + layout(location = 0) out vec4 vOutColor; + + @for(i in 0..2) + @if(o_textures[i]) + layout(location = @{i}) in vec2 vTexCoord@{i}; + @end + @end + + @if(o_fog) + layout(location = 2) in float vFogFactor; + @end + + @if(o_shade) + @if(o_alpha) + layout(location = 3) in vec4 vShade; + @else + layout(location = 3) in vec3 vShade; + @end + @end + + @if(o_textures[0]) layout(set = 1, binding = 0) uniform sampler2D uTex0; + @if(o_textures[1]) layout(set = 1, binding = 1) uniform sampler2D uTex1; + + @if(o_masks[0]) layout(set = 1, binding = 2) uniform sampler2D uTexMask0; + @if(o_masks[1]) layout(set = 1, binding = 3) uniform sampler2D uTexMask1; + + @if(o_blend[0]) layout(set = 1, binding = 4) uniform sampler2D uTexBlend0; + @if(o_blend[1]) layout(set = 1, binding = 5) uniform sampler2D uTexBlend1; + + #define TEX_OFFSET(off) texture(tex, texCoord - off / texSize) + #define WRAP(x, low, high) mod((x)-(low), (high)-(low)) + (low) + + float random(in vec3 value) { + float random = dot(sin(value), vec3(12.9898, 78.233, 37.719)); + return fract(sin(random) * 143758.5453); + } + + // N64 RDP ordered-dither matrices (values 0..7); see applyRdpDither. + const int kDitherMagic[16] = int[16](0, 6, 1, 7, 4, 2, 5, 3, 3, 5, 2, 4, 7, 1, 6, 0); + const int kDitherBayer[16] = int[16](0, 4, 1, 5, 6, 2, 7, 3, 1, 5, 0, 4, 7, 3, 6, 2); + + // Integer hash for the G_CD_NOISE dither: robust per-pixel + per-frame value 0..7 + // (a sin-based hash aliases to near-constant on some GPUs, washing the noise out). + int ditherNoise(ivec2 p, int frame) { + uint h = uint(p.x) * 1597334677u ^ uint(p.y) * 3812015801u ^ uint(frame) * 2654435761u; + h ^= h >> 16u; h *= 2246822519u; + h ^= h >> 13u; h *= 3266489917u; + h ^= h >> 16u; + return int(h & 7u); + } + + // RDP RGB dither + RGBA5551 quantization. mode: 0=magic square, 1=bayer, + // 2=noise (temporal), 3=disable (truncate only), >=4 = off (full precision). + vec3 applyRdpDither(vec3 color, float modeF, vec2 fragCoord, float noiseScale, int frameCount) { + int mode = int(modeF + 0.5); + if (mode >= 4) { + return color; + } + vec2 nativeCoord = floor(fragCoord * noiseScale); + float d = 0.0; + if (mode == 0) { + ivec2 cell = ivec2(nativeCoord) & 3; + d = float(kDitherMagic[cell.y * 4 + cell.x]); + } else if (mode == 1) { + ivec2 cell = ivec2(nativeCoord) & 3; + d = float(kDitherBayer[cell.y * 4 + cell.x]); + } else if (mode == 2) { + d = float(ditherNoise(ivec2(nativeCoord), frameCount)); + } + vec3 q = min(floor(clamp(color * 255.0 + d, 0.0, 255.0) / 8.0), 31.0); + return (q * 8.0 + floor(q / 4.0)) / 255.0; + } + + vec4 filter3point(in sampler2D tex, in vec2 texCoord, in vec2 texSize) { + vec2 offset = fract(texCoord*texSize - vec2(0.5)); + offset -= step(1.0, offset.x + offset.y); + vec4 c0 = TEX_OFFSET(offset); + vec4 c1 = TEX_OFFSET(vec2(offset.x - sign(offset.x), offset.y)); + vec4 c2 = TEX_OFFSET(vec2(offset.x, offset.y - sign(offset.y))); + return c0 + abs(offset.x)*(c1-c0) + abs(offset.y)*(c2-c0); + } + + vec4 hookTexture2D(in int id, sampler2D tex, in vec2 uv, in vec2 texSize) { + @if(o_three_point_filtering) + if(drawU.tex_filter[0][id] == @{FILTER_THREE_POINT}) { + return filter3point(tex, uv, texSize); + } + @end + return texture(tex, uv); + } + + @include("shaders/vulkan/include/palette.glsli") + + void main() { + @if(o_uses_lod) + float lodFrac = 0.0; + @end + @for(i in 0..2) + @if(o_textures[i]) + @{s = o_clamp[i][0]} + @{t = o_clamp[i][1]} + + vec2 texSize@{i} = vec2(textureSize(uTex@{i}, 0)); + + @if(!s && !t) + vec2 vTexCoordAdj@{i} = vTexCoord@{i}; + @else + @if(s && t) + vec2 vTexCoordAdj@{i} = clamp(vTexCoord@{i}, 0.5 / texSize@{i}, drawU.tex_clamp[@{i}].xy); + @elseif(s) + vec2 vTexCoordAdj@{i} = vec2(clamp(vTexCoord@{i}.s, 0.5 / texSize@{i}.s, drawU.tex_clamp[@{i}].x), vTexCoord@{i}.t); + @else + vec2 vTexCoordAdj@{i} = vec2(vTexCoord@{i}.s, clamp(vTexCoord@{i}.t, 0.5 / texSize@{i}.t, drawU.tex_clamp[@{i}].y)); + @end + @end + + @if(i == 0) + @if(o_uses_lod) + // N64 texture LOD (RDP-accurate): max absolute UV derivative, + // linear fraction between tiles, sharpen/detail handling + vec2 lodScaled = vTexCoordAdj0 * texSize0; + vec2 lodMaxD = max(abs(dFdx(lodScaled)), abs(dFdy(lodScaled))); + float lodMaxDst = max(max(lodMaxD.x, lodMaxD.y) * drawU.lod_params.x, 0.000001); + if (drawU.lod_params.z > 0.5) { // sharpen or detail + lodMaxDst = max(lodMaxDst, drawU.lod_params.y); + } + float lodTileBase = floor(log2(lodMaxDst)); + lodFrac = lodMaxDst / exp2(max(lodTileBase, 0.0)) - 1.0; + if (drawU.lod_params.z > 0.5 && drawU.lod_params.z < 1.5 && lodMaxDst < 1.0) { // sharpen + lodFrac = lodMaxDst - 1.0; + } + if (drawU.lod_params.z > 1.5) { // detail: tile 0 is the detail texture + if (lodFrac < 0.0) { + lodFrac = lodMaxDst; + } + lodTileBase += 1.0; + } else if (lodTileBase >= drawU.misc.y) { + lodFrac = 1.0; + } + if (drawU.lod_params.z > 0.5) { + lodTileBase = max(lodTileBase, 0.0); + } else { + lodFrac = max(lodFrac, 0.0); + } + float lodTile0 = clamp(lodTileBase, 0.0, drawU.misc.y); + float lodTile1 = clamp(lodTileBase + 1.0, 0.0, drawU.misc.y); + // No real LOD level beyond the base (max level 0): the N64 + // never blends a second tile. Small EXTRA_TILE_MIPMAPS + // textures degenerate to one level yet still emit + // G_TL_LOD+TRILERP; without this the combiner blends a stale + // TEXEL1 by distance. + if (drawU.misc.y < 0.5) { + lodFrac = 0.0; + } + @end + @end + + @if(i == 0) + @if(o_mip_lod) + vec4 texVal0 = textureLod(uTex0, vTexCoordAdj0, lodTile0); + @elseif(o_palette[0]) + vec4 texVal0 = paletteSample(uTex0, vTexCoordAdj0, texSize0, drawU.palette_params[0]); + @else + vec4 texVal@{i} = hookTexture2D(@{i}, uTex@{i}, vTexCoordAdj@{i}, texSize@{i}); + @end + @else + @if(o_palette[1]) + vec4 texVal1 = paletteSample(uTex1, vTexCoordAdj1, texSize1, drawU.palette_params[1]); + @else + vec4 texVal@{i} = hookTexture2D(@{i}, uTex@{i}, vTexCoordAdj@{i}, texSize@{i}); + @end + @end + + @if(o_masks[i]) + vec2 maskSize@{i} = vec2(textureSize(uTexMask@{i}, 0)); + + vec4 maskVal@{i} = hookTexture2D(@{i}, uTexMask@{i}, vTexCoordAdj@{i}, maskSize@{i}); + + @if(o_blend[i]) + vec4 blendVal@{i} = hookTexture2D(@{i}, uTexBlend@{i}, vTexCoordAdj@{i}, texSize@{i}); + @else + vec4 blendVal@{i} = vec4(0, 0, 0, 0); + @end + + texVal@{i} = mix(texVal@{i}, blendVal@{i}, maskVal@{i}.a); + @end + @end + @end + + @if(o_mip_lod) + // TEXEL1 reads the next mip level of texture 0 + vec4 texVal1 = textureLod(uTex0, vTexCoordAdj0, lodTile1); + @end + + @if(o_two_tile_lod) + // N64 LOD tile selection: TEXEL0's tile is clamped to the max level, + // but the hardware's second texel is always lod_tile + 1 — at + // magnification TEXEL1 still reads the real tile 1 (Paper Mario's + // sprite shading relies on this with a stale G_TL_LOD). + texVal0 = lodTile0 < 0.5 ? texVal0 : texVal1; + @end + + @if(o_alpha) + vec4 texel; + @else + vec3 texel; + @end + + @if(o_2cyc) + @{f_range = 2} + @else + @{f_range = 1} + @end + + @for(c in 0..f_range) + @if(c == 1) + @if(o_alpha) + @if(o_c[c][1][2] == SHADER_COMBINED) + texel.a = WRAP(texel.a, -1.01, 1.01); + @else + texel.a = WRAP(texel.a, -0.51, 1.51); + @end + @end + + @if(o_c[c][0][2] == SHADER_COMBINED) + texel.rgb = WRAP(texel.rgb, -1.01, 1.01); + @else + texel.rgb = WRAP(texel.rgb, -0.51, 1.51); + @end + @end + + @if(!o_color_alpha_same[c] && o_alpha) + texel = vec4(@{ + append_formula(o_c[c], o_do_single[c][0], + o_do_multiply[c][0], o_do_mix[c][0], false, false, true, c == 0) + }, @{append_formula(o_c[c], o_do_single[c][1], + o_do_multiply[c][1], o_do_mix[c][1], true, true, true, c == 0) + }); + @else + texel = @{append_formula(o_c[c], o_do_single[c][0], + o_do_multiply[c][0], o_do_mix[c][0], o_alpha, false, + o_alpha, c == 0)}; + @end + @end + + texel = WRAP(texel, -0.51, 1.51); + texel = clamp(texel, 0.0, 1.0); + @if(o_fog) + @if(o_alpha) + texel = vec4(mix(texel.rgb, drawU.fog_color.rgb, vFogFactor), texel.a); + @else + texel = mix(texel, drawU.fog_color.rgb, vFogFactor); + @end + @end + + @if(o_texture_edge && o_alpha) + if (texel.a > 0.19) texel.a = 1.0; else discard; + @end + + @if(o_alpha && o_noise) + texel.a *= floor(clamp(random(vec3(floor(gl_FragCoord.xy * frameU.noise_scale), float(frameU.frame_count))) + texel.a, 0.0, 1.0)); + @end + + @if(o_grayscale) + float intensity = (texel.r + texel.g + texel.b) / 3.0; + vec3 new_texel = drawU.grayscale_color.rgb * intensity; + texel.rgb = mix(texel.rgb, new_texel, drawU.grayscale_color.a); + @end + + // N64 RGB framebuffer dither (per-primitive G_CD_* mode in lod_params.w) + @if(o_alpha) + texel.rgb = applyRdpDither(texel.rgb, drawU.lod_params.w, gl_FragCoord.xy, frameU.noise_scale, frameU.frame_count); + @else + texel = applyRdpDither(texel, drawU.lod_params.w, gl_FragCoord.xy, frameU.noise_scale, frameU.frame_count); + @end + + @if(o_alpha) + texel.rgb = mix(texel.rgb, drawU.debug_tint.rgb, drawU.debug_tint.a); + @else + texel = mix(texel, drawU.debug_tint.rgb, drawU.debug_tint.a); + @end + + @if(o_alpha) + @if(o_alpha_threshold) + if (texel.a < 8.0 / 256.0) discard; + @end + @if(o_invisible) + texel.a = 0.0; + @end + vOutColor = texel; + @else + vOutColor = vec4(texel, 1.0); + @end + + @if(o_prim_depth) + gl_FragDepth = drawU.misc.x; + @end + } +@end diff --git a/port/shaders/vulkan/include/common.glsli b/port/shaders/vulkan/include/common.glsli new file mode 100644 index 000000000..ba55e0a23 --- /dev/null +++ b/port/shaders/vulkan/include/common.glsli @@ -0,0 +1,45 @@ +@prism(type='fragment', name='Fast3D Vulkan Common', version='1.0.0', description='Shared descriptor-set uniform blocks (frameU/drawU/lightU/xformU); lockstep with gfx_vulkan.h', author='Fast3D') + +// Uniform layout mirrors the structs in gfx_vulkan.h (std140; everything is +// vec4-aligned on the C++ side). Set 0 = ring-buffer UBOs with dynamic +// offsets, set 1 = the 7 fast3d texture slots. +layout(std140, set = 0, binding = 0) uniform FrameUniforms { + int frame_count; + float noise_scale; +} frameU; + +layout(std140, set = 0, binding = 1) uniform DrawUniforms { + ivec4 tex_filter[2]; // slots 0..6, [0].xyzw = 0..3, [1].xyz = 4..6 + vec4 misc; // x = prim_depth, y = lod_max + vec4 inputs[6]; + vec4 fog_color; + vec4 grayscale_color; + vec4 uv_transform[2]; + vec4 tex_clamp[2]; + vec4 fog_params; + vec4 palette_params[2]; + vec4 lod_params; // x = res scale, y = prim_lod_min, z = G_TD mode + // Game-bindable register file; lockstep with VulkanDrawUniforms (gfx_vulkan.h) + vec4 uCustomRegs[32]; + vec4 debug_tint; +} drawU; + +// Loose-uniform-style alias so shader code matches the GL dialect +#define uCustom drawU.uCustomRegs + +layout(std140, set = 0, binding = 2) uniform LightUniforms { + vec4 lights[96]; // 32 lights x [color+kind, model dir+kc, world pos+kq] + vec4 ambient; + vec4 lookat_x; + vec4 lookat_y; + vec4 texgen[2]; + vec4 mv_rows[3]; + vec4 mv_cols[3]; + ivec4 num_lights; +} lightU; + +layout(std140, set = 0, binding = 3) uniform TransformUniforms { + vec4 mtx_palette[32]; // 8 slots x 4 vec4 rows + vec4 y_scale; +} xformU; + diff --git a/port/shaders/vulkan/include/fast3d_vs.glsli b/port/shaders/vulkan/include/fast3d_vs.glsli new file mode 100644 index 000000000..1242a352e --- /dev/null +++ b/port/shaders/vulkan/include/fast3d_vs.glsli @@ -0,0 +1,141 @@ +@prism(type='fragment', name='Fast3D Vulkan Vertex Stage', version='1.0.0', description='Complete default vertex shader body for the Vulkan dialect', author='Fast3D') + layout(location = 0) in vec4 aVtxPos; + layout(location = 1) in float aMtxSlot; + + @for(i in 0..2) + @if(o_textures[i]) + @if(i == 0) + layout(location = 2) in vec2 aTexCoord0; + @else + layout(location = 3) in vec2 aTexCoord1; + @end + layout(location = @{i}) out vec2 vTexCoord@{i}; + @end + @end + + @if(o_fog) + layout(location = 2) out float vFogFactor; + @end + + @if(o_shade || o_lighting) + @if(o_alpha) + layout(location = 4) in vec4 aShade; + @else + layout(location = 4) in vec3 aShade; + @end + @end + @if(o_shade) + @if(o_alpha) + layout(location = 3) out vec4 vShade; + @else + layout(location = 3) out vec3 vShade; + @end + @end + + void main() { + // RSP position transform: matrix palette entry selected per vertex + int mtxBase = int(aMtxSlot + 0.5) * 4; + vec4 clipPos = aVtxPos.x * xformU.mtx_palette[mtxBase] + aVtxPos.y * xformU.mtx_palette[mtxBase + 1] + + aVtxPos.z * xformU.mtx_palette[mtxBase + 2] + aVtxPos.w * xformU.mtx_palette[mtxBase + 3]; + + @for(i in 0..2) + @if(o_textures[i]) + // Tile shift/origin/bilerp/size pipeline folded into one transform + vTexCoord@{i} = vec2(aTexCoord@{i}.x * drawU.uv_transform[@{i}].x + drawU.uv_transform[@{i}].y, + aTexCoord@{i}.y * drawU.uv_transform[@{i}].z + drawU.uv_transform[@{i}].w); + @end + @end + @if(o_fog) + // N64 RSP fog from clip-space z/w; fog_params.w selects the source + // (0: computed, 1: constant register, 2: legacy vertex-alpha fallback) + float fogW = abs(clipPos.w) < 0.001 ? 0.001 : clipPos.w; + float fogWinv = 1.0 / fogW; + if (fogWinv < 0.0) { + fogWinv = 32767.0; + } + float fogCalc = clamp(clipPos.z * fogWinv * drawU.fog_params.x + drawU.fog_params.y, 0.0, 255.0) / 255.0; + @if(o_shade && o_alpha) + vFogFactor = drawU.fog_params.w > 1.5 ? aShade.a : (drawU.fog_params.w > 0.5 ? drawU.fog_params.z : fogCalc); + @else + vFogFactor = drawU.fog_params.w > 0.5 ? drawU.fog_params.z : fogCalc; + @end + @end + @if(o_texgen) + // N64 texgen: project the vertex normal onto the lookat vectors, then + // run the result through the standard tile/scale UV pipeline (folded + // into the per-draw texgen linear transforms). + float texgenDotX = clamp(dot(aShade.xyz, lightU.lookat_x.xyz) / 127.0, -1.0, 1.0); + float texgenDotY = clamp(dot(aShade.xyz, lightU.lookat_y.xyz) / 127.0, -1.0, 1.0); + @if(o_texgen_linear) + texgenDotX = acos(-texgenDotX) * 0.159155; + texgenDotY = acos(-texgenDotY) * 0.159155; + @else + texgenDotX = (texgenDotX + 1.0) / 4.0; + texgenDotY = (texgenDotY + 1.0) / 4.0; + @end + @if(o_textures[0]) + vTexCoord0 = vec2(texgenDotX * lightU.texgen[0].x + lightU.texgen[0].y, texgenDotY * lightU.texgen[0].z + lightU.texgen[0].w); + @end + @if(o_textures[1]) + vTexCoord1 = vec2(texgenDotX * lightU.texgen[1].x + lightU.texgen[1].y, texgenDotY * lightU.texgen[1].z + lightU.texgen[1].w); + @end + @end + @if(o_shade && o_alpha) + // Standard fog forces shade alpha to 1.0 (the factor rides vFogFactor); + // blend-color mode (fog mode 1) preserves the vertex alpha. + float shadeAlpha = aShade.a; + @if(o_fog) + if (drawU.fog_params.w < 0.5 || drawU.fog_params.w > 1.5) { + shadeAlpha = 1.0; + } + @end + @end + @if(o_point_lighting) + // World-space position derived from the object-space vertex position + vec3 worldPos = vec3(dot(aVtxPos, lightU.mv_cols[0]), dot(aVtxPos, lightU.mv_cols[1]), dot(aVtxPos, lightU.mv_cols[2])); + @end + @if(o_shade) + @if(o_lighting) + // N64 RSP lighting: aShade carries the raw signed vertex normal + vec3 litColor = lightU.ambient.rgb; + for (int i = 0; i < lightU.num_lights.x; i++) { + float intensity = 0.0; + @if(o_point_lighting) + if (lightU.lights[i * 3].w > 0.5) { + vec3 distVec = lightU.lights[i * 3 + 2].xyz - worldPos; + float distSq = distVec.x * distVec.x + distVec.y * distVec.y + distVec.z * distVec.z * 2.0; + float dist = sqrt(distSq); + vec3 lightModel = vec3(dot(distVec, lightU.mv_rows[0].xyz), dot(distVec, lightU.mv_rows[1].xyz), dot(distVec, lightU.mv_rows[2].xyz)); + vec3 lightIntensity = clamp(4.0 * lightModel / distSq, -1.0, 1.0); + float totalIntensity = clamp(dot(lightIntensity, aShade.xyz), -1.0, 1.0); + float distF = floor(dist); + float attenuation = (distF * lightU.lights[i * 3 + 1].w * 2.0 + distF * distF * lightU.lights[i * 3 + 2].w / 8.0) / 65535.0 + 1.0; + intensity = totalIntensity / attenuation; + } else { + intensity = dot(aShade.xyz, lightU.lights[i * 3 + 1].xyz) / 127.0; + } + @else + intensity = dot(aShade.xyz, lightU.lights[i * 3 + 1].xyz) / 127.0; + @end + if (intensity > 0.0) { + litColor += intensity * lightU.lights[i * 3].rgb; + } + } + litColor = min(litColor, vec3(1.0)); + @if(o_alpha) + vShade = vec4(litColor, shadeAlpha); + @else + vShade = litColor; + @end + @else + @if(o_alpha) + vShade = vec4(aShade.rgb, shadeAlpha); + @else + vShade = aShade; + @end + @end + @end + // Same clip conventions as Metal: z mapped to 0..w; y flip handled by + // y_scale plus the negative viewport set by the backend. + gl_Position = vec4(clipPos.x, clipPos.y * xformU.y_scale.x, (clipPos.z + clipPos.w) / 2.0, clipPos.w); + } diff --git a/port/shaders/vulkan/include/palette.glsli b/port/shaders/vulkan/include/palette.glsli new file mode 100644 index 000000000..ea54800e6 --- /dev/null +++ b/port/shaders/vulkan/include/palette.glsli @@ -0,0 +1,37 @@ +@prism(type='fragment', name='Fast3D Vulkan CI Palettes', version='1.0.0', description='Palette tap/sample helpers for color-index textures (Vulkan dialect)', author='Fast3D') + @if(o_palette[0] || o_palette[1]) + layout(set = 1, binding = 6) uniform sampler2D uTexPal; + + // One CI tap: fetch the index (nearest sampler) and look it up in the + // 256-entry palette texture. params.x is the CI4 bank entry offset. + vec4 paletteTap(in sampler2D tex, in vec2 uv, in float bank) { + float idx = texture(tex, uv).r; + return texture(uTexPal, vec2((idx * 255.0 + bank + 0.5) / 256.0, 0.5)); + } + + // Filtering must happen after the palette lookup, like real hardware: + // params.y selects nearest (0), bilinear (1) or N64 three-point (2). + vec4 paletteSample(in sampler2D tex, in vec2 uv, in vec2 texSize, in vec4 params) { + if (params.y > 1.5) { + vec2 offset = fract(uv * texSize - vec2(0.5)); + offset -= step(1.0, offset.x + offset.y); + vec4 c0 = paletteTap(tex, uv - offset / texSize, params.x); + vec4 c1 = paletteTap(tex, uv - vec2(offset.x - sign(offset.x), offset.y) / texSize, params.x); + vec4 c2 = paletteTap(tex, uv - vec2(offset.x, offset.y - sign(offset.y)) / texSize, params.x); + return c0 + abs(offset.x) * (c1 - c0) + abs(offset.y) * (c2 - c0); + } else if (params.y > 0.5) { + vec2 t = uv * texSize - 0.5; + vec2 f = fract(t); + vec2 base = (floor(t) + 0.5) / texSize; + vec2 px = vec2(1.0, 0.0) / texSize; + vec2 py = vec2(0.0, 1.0) / texSize; + vec4 c00 = paletteTap(tex, base, params.x); + vec4 c10 = paletteTap(tex, base + px, params.x); + vec4 c01 = paletteTap(tex, base + py, params.x); + vec4 c11 = paletteTap(tex, base + px + py, params.x); + return mix(mix(c00, c10, f.x), mix(c01, c11, f.x), f.y); + } else { + return paletteTap(tex, uv, params.x); + } + } + @end diff --git a/port/shaders/vulkan/srgb.shader.glsl b/port/shaders/vulkan/srgb.shader.glsl new file mode 100644 index 000000000..909805ccc --- /dev/null +++ b/port/shaders/vulkan/srgb.shader.glsl @@ -0,0 +1,28 @@ +@prism(type='fragment', name='Fast3D Vulkan sRGB Post', version='1.0.0', description='Final-pass linear->sRGB (gamma) output encoding', author='Fast3D') + +#version 450 +@include("shaders/vulkan/include/common.glsli") + +@if(VERTEX_SHADER) + @include("shaders/vulkan/include/fast3d_vs.glsli") + +@else + layout(location = 0) out vec4 vOutColor; + layout(location = 0) in vec2 vTexCoord0; + + layout(set = 1, binding = 0) uniform sampler2D uTex0; + + // Linear -> sRGB transfer (the gamma boost previously baked into every + // fragment shader via srgb_mode; now applied once as a fullscreen pass). + vec4 fromLinear(vec4 linearRGB) { + bvec3 cutoff = lessThan(linearRGB.rgb, vec3(0.0031308)); + vec3 higher = vec3(1.055) * pow(linearRGB.rgb, vec3(1.0 / 2.4)) - vec3(0.055); + vec3 lower = linearRGB.rgb * vec3(12.92); + return vec4(mix(higher, lower, cutoff), linearRGB.a); + } + + void main() { + vec4 texel = texture(uTex0, vTexCoord0); + vOutColor = fromLinear(vec4(texel.rgb, 1.0)); + } +@end diff --git a/src/audio/audio_effects.c b/src/audio/audio_effects.c index 574516348..2816fdc8d 100644 --- a/src/audio/audio_effects.c +++ b/src/audio/audio_effects.c @@ -1,6 +1,6 @@ #include "sys.h" #include "sf64audio_provisional.h" -#include "endianness.h" +#include static const char devstr[] = "Audio:Envp: overflow %f\n"; diff --git a/src/audio/audio_general.c b/src/audio/audio_general.c index 55142c193..73b112cef 100644 --- a/src/audio/audio_general.c +++ b/src/audio/audio_general.c @@ -4,6 +4,7 @@ #include "audiothread_cmd.h" #include "audioseq_cmd.h" #include "port/Engine.h" +#include "port/hooks/Events.h" void Audio_SetModulationAndPlaySfx(f32* sfxSource, u32 sfxId, f32 freqMod); s32 Audio_GetCurrentVoice(void); @@ -676,6 +677,7 @@ void Audio_StartSequence(u8 seqPlayId, u8 seqId, u8 seqArgs, u16 fadeInTime) { } void Audio_StopSequence(u8 seqPlayId, u16 fadeOutTime) { + CALL_CANCELLABLE_RETURN_EVENT(StopSequenceEvent, seqPlayId, fadeOutTime); AUDIOCMD_GLOBAL_DISABLE_SEQPLAYER(seqPlayId, fadeOutTime); sActiveSequences[seqPlayId].seqId = SEQ_ID_NONE; } @@ -982,6 +984,7 @@ void Audio_DisableSetupOp(u8 seqPlayId, u8 opcode) { } void Audio_SetSequenceFade(u8 seqPlayId, u8 fadeModId, u8 fadeMod, u8 fadeTime) { + CALL_CANCELLABLE_RETURN_EVENT(SetSequenceFadeEvent, seqPlayId, fadeModId, &fadeMod, &fadeTime); sActiveSequences[seqPlayId].mainVolume.fadeMod[fadeModId] = fadeMod; sActiveSequences[seqPlayId].mainVolume.fadeTimer = fadeTime; sActiveSequences[seqPlayId].mainVolume.fadeActive = true; @@ -1278,6 +1281,7 @@ void Audio_ClearBGMMute(u8 channelIndex) { } void Audio_PlaySfx(u32 sfxId, f32* sfxSource, u8 token, f32* freqMod, f32* volMod, s8* reverbAdd) { + CALL_CANCELLABLE_RETURN_EVENT(PlaySfxEvent, &sfxId, sfxSource, token, &freqMod, &volMod, &reverbAdd); if (sSfxBankMuted[SFX_BANK_ALT(sfxId)] == 0) { SfxRequest* request = &sSfxRequests[sSfxRequestWriteIndex]; @@ -1850,6 +1854,8 @@ void Audio_ResetSfx(void) { void Audio_PlayVoice(s32 msgId) { sCurrentVoiceId = sNextVoiceId = msgId; sSetNextVoiceId = true; + // [port - voice hook - notifies port layer of new voice playback request] + CALL_EVENT(PlayVoiceEvent, msgId); } void Audio_PlayVoiceWithoutBGM(u32 msgId) { @@ -1864,6 +1870,8 @@ void Audio_UpdateVoice(void) { u8 voiceIdHi; u8 voiceIdLo; + CALL_CANCELLABLE_RETURN_EVENT(UpdateVoiceEvent); + if (sSetNextVoiceId) { voiceBank = sNextVoiceId / 1000; voiceId = sNextVoiceId % 1000; @@ -1882,6 +1890,8 @@ void Audio_UpdateVoice(void) { } void Audio_ClearVoice(void) { + // [port - voice hook - resets voice override state on clear] + CALL_EVENT(ClearVoiceEvent); sCurrentVoiceId = 0; sNextVoiceId = 1; sSetNextVoiceId = true; @@ -1891,6 +1901,13 @@ s32 Audio_GetCurrentVoice(void) { // LAudioTODO: Stub for now // return 0; + // [port - voice hook - allows port layer to report currently playing voice msgId] + s32 voiceResult = -1; + CALL_EVENT(GetCurrentVoiceEvent, &voiceResult); + if (voiceResult != -1) { + return voiceResult; + } + if (!IS_SEQUENCE_CHANNEL_VALID(gSeqPlayers[SEQ_PLAYER_VOICE].channels[15])) { return 0; } @@ -1908,6 +1925,13 @@ s32 Audio_GetCurrentVoiceStatus(void) { // LAudioTODO: Stub for now // return 1; + // [port - voice hook - allows port layer to drive mouth animation from custom audio waveform] + s32 statusResult = -1; + CALL_EVENT(GetVoiceStatusEvent, &statusResult); + if (statusResult != -1) { + return statusResult; + } + SequenceChannel* channel = gSeqPlayers[SEQ_PLAYER_VOICE].channels[15]; SequenceLayer* layer = channel->layers[0]; @@ -2600,11 +2624,13 @@ void Audio_SetBgmParam(s8 bgmParam) { void Audio_PlaySequence(u8 seqPlayId, u16 seqId, u8 fadeinTime, u8 bgmParam) { // seqId &= 0xFF; + CALL_CANCELLABLE_RETURN_EVENT(PlaySequenceEvent, seqPlayId, &seqId, fadeinTime, bgmParam); SEQCMD_SET_SEQPLAYER_IO(seqPlayId, 0, bgmParam); SEQCMD_PLAY_SEQUENCE(seqPlayId, fadeinTime, 0, seqId); } void Audio_PlayFanfare(u16 seqId, u8 bgmVolume, u8 bgmFadeoutTime, u8 bgmFadeinTime) { + CALL_CANCELLABLE_RETURN_EVENT(PlayFanfareEvent, &seqId, bgmVolume, bgmFadeoutTime, bgmFadeinTime); if (Audio_GetActiveSeqId(SEQ_PLAYER_BGM) != NA_BGM_PLAYER_DOWN) { Audio_SetSequenceFade(SEQ_PLAYER_BGM, 1, bgmVolume, bgmFadeoutTime); SEQCMD_SETUP_RESTORE_SEQPLAYER_VOLUME(SEQ_PLAYER_FANFARE, SEQ_PLAYER_BGM, bgmFadeinTime); @@ -2678,6 +2704,7 @@ void Audio_SetVolume(u8 audioType, u8 volume) { if (volume > 99) { volume = 99; } + CALL_CANCELLABLE_RETURN_EVENT(SetVolumeEvent, audioType, &volume); sVolumeSettings[audioType] = volume; Audio_RestoreVolumeSettings(audioType); } @@ -2760,6 +2787,7 @@ void Audio_SetAudioSpec(u8 unused, u16 specParam) { u8 sfxChannelLayout = ((specParam & 0xFF00) >> 8); u8 specId = specParam & 0xFF; + CALL_EVENT(SetAudioSpecEvent, &sfxChannelLayout, &specId); SEQCMD_RESET_AUDIO_HEAP(sfxChannelLayout, specId); } @@ -2848,4 +2876,5 @@ void Audio_Update(void) { AudioThread_ScheduleProcessCmds(); } sAudioFrameCounter++; + CALL_EVENT(AudioUpdateEvent); } diff --git a/src/audio/audio_load.c b/src/audio/audio_load.c index 9d3766957..c43551ceb 100644 --- a/src/audio/audio_load.c +++ b/src/audio/audio_load.c @@ -4,8 +4,8 @@ #include "sf64audio_provisional.h" #include "assets/ast_audio.h" #include "port/Engine.h" -#include "endianness.h" #include "port/resource/loaders/AudioLoader.h" +#include s32 D_80146D80; s32 PAD_80146D88[2]; @@ -395,7 +395,8 @@ void AudioLoad_SyncInitSeqPlayerInternal(s32 playerIdx, s32 seqId, s32 arg2) { s32 fontId; s32 i; - // seqId = AudioLoad_GetLoadTableIndex(SEQUENCE_TABLE, seqId); + // @port: seqId is looked up via ResourceGetDataByCrc in AudioLoad_SyncLoadSeq below. + // Mod replacement sequences override the same CRC path automatically. AudioSeq_SequencePlayerDisable(&gSeqPlayers[playerIdx]); diff --git a/src/audio/audio_seqplayer.c b/src/audio/audio_seqplayer.c index 91a4462c5..a77c74c0a 100644 --- a/src/audio/audio_seqplayer.c +++ b/src/audio/audio_seqplayer.c @@ -1,7 +1,10 @@ #include "sys.h" +#include "audioseq_cmd.h" #include "sf64audio_provisional.h" -#include "endianness.h" +#include #include "port/Engine.h" +#include "port/audio/AudioDebug.h" +#include "port/hooks/Events.h" #define PORTAMENTO_IS_SPECIAL(x) ((x).mode & 0x80) #define PORTAMENTO_MODE(x) ((x).mode & ~0x80) @@ -701,6 +704,8 @@ void AudioSeq_SeqLayerProcessScript(SequenceLayer* layer) { } } + CALL_EVENT(SeqLayerPreNoteEvent, layer, channel); + if ((layer->muted == false) && (layer->tunedSample != NULL) && (layer->tunedSample->sample->codec == 2) && (layer->tunedSample->sample->medium != 0)) { layer->muted = 1; @@ -730,6 +735,10 @@ void AudioSeq_SeqLayerProcessScript(SequenceLayer* layer) { Audio_NoteVibratoInit(layer->note); } } + + if (layer->note != NULL) { + CALL_EVENT(SeqLayerPostNoteEvent, layer); + } if (!channel) {} } @@ -1524,12 +1533,23 @@ void AudioSeq_SequencePlayerProcessSequence(SequencePlayer* seqPlayer) { } void AudioSeq_ProcessSequences(s32 arg0) { - s32 i; + s32 i, j, k; for (i = 0; i < ARRAY_COUNT(gSeqPlayers); i++) { if (gSeqPlayers[i].enabled == true) { AudioSeq_SequencePlayerProcessSequence(&gSeqPlayers[i]); Audio_SequencePlayerProcessSound(&gSeqPlayers[i]); + for (j = 0; j < SEQ_NUM_CHANNELS; j++) { + SequenceChannel* ch = gSeqPlayers[i].channels[j]; + if (IS_SEQUENCE_CHANNEL_VALID(ch) && AudioDebug_IsChannelMuted(j)) { + ch->appliedVolume = 0.0f; + for (k = 0; k < ARRAY_COUNT(ch->layers); k++) { + if (ch->layers[k] != NULL && ch->layers[k]->note != NULL) { + ch->layers[k]->noteVelocity = 0.0f; + } + } + } + } } } Audio_ProcessNotes(); diff --git a/src/audio/audio_synthesis.c b/src/audio/audio_synthesis.c index 2bf7e87ce..aeeb9d02c 100644 --- a/src/audio/audio_synthesis.c +++ b/src/audio/audio_synthesis.c @@ -1,8 +1,9 @@ #include "sys.h" #include "sf64audio_provisional.h" #include "audio/mixer.h" -#include "endianness.h" #include "port/Engine.h" +#include +#include "port/audio/AudioDebug.h" #define DMEM_WET_SCRATCH 0x470 #define DMEM_COMPRESSED_ADPCM_DATA 0xD50 @@ -944,6 +945,16 @@ Acmd* AudioSynth_ProcessNote(s32 noteIndex, NoteSubEu* noteSub, NoteSynthesisSta synthState->samplePosInt += numSamplesToLoad; } else { bookSample = *(noteSub->waveSampleAddr); + AudioDebug_SetLastPlayed( + (void*)bookSample, + synthState->samplePosInt, + bookSample->loop->end, + (int)bookSample->loop->start, + (int)bookSample->loop->end, + bookSample->loop->count, + noteSub->resampleRate, + (int)bookSample->codec, + bookSample->size); loopInfo = bookSample->loop; endPos = loopInfo->end; @@ -986,6 +997,14 @@ Acmd* AudioSynth_ProcessNote(s32 noteIndex, NoteSubEu* noteSub, NoteSynthesisSta while (numSamplesProcessed != numSamplesToLoadAdj) { sampleFinished = false; loopToPoint = false; + size_t s16LoopStartAdvance = 0; + + // Guard against samplePosInt overshooting endPos (e.g. after a loop + // reset lands past the end due to rounding, or on the very first call + // after a loop reset with a large numSamplesToLoadAdj). + if (loopInfo->count != 0 && synthState->samplePosInt >= endPos) { + synthState->samplePosInt = loopInfo->start; + } samplesRemaining = endPos - synthState->samplePosInt; nSamplesToProcess = numSamplesToLoadAdj - numSamplesProcessed; @@ -1045,6 +1064,7 @@ Acmd* AudioSynth_ProcessNote(s32 noteIndex, NoteSubEu* noteSub, NoteSynthesisSta goto skip; case CODEC_S16: + synthState->restart = 0; aClearBuffer(aList++, DMEM_UNCOMPRESSED_NOTE, (numSamplesToLoadAdj + SAMPLES_PER_FRAME) * SAMPLE_SIZE); @@ -1054,14 +1074,62 @@ Acmd* AudioSynth_ProcessNote(s32 noteIndex, NoteSubEu* noteSub, NoteSynthesisSta numSamplesProcessed += numSamplesToLoadAdj; dmemUncompressedAddrOffset1 = numSamplesToLoadAdj; - if (((synthState->samplePosInt * 2) + (numSamplesToLoadAdj) *SAMPLE_SIZE) < bookSample->size) { - bytesToRead = (numSamplesToLoadAdj + 16) * SAMPLE_SIZE; - } else { - bytesToRead = bookSample->size - (synthState->samplePosInt * 2); + { + // 2S2H [Port] [Custom audio] Handle decoding OPUS data + // Guard against underflow: decoder may not be ready yet (size==0) + // or loop end exceeds actual buffer length. + size_t bytePos = (size_t)synthState->samplePosInt * 2; + if (sampleAddr == 0 || bookSample->size == 0 || bytePos >= bookSample->size) { + // Decoder not ready (sampleAddr/size not yet set) or past end. + // aClearBuffer already zeroed DMEM, so we produce silence. + goto skip; + } + + if (loopToPoint && loopInfo->count != 0 && + (u32)synthState->samplePosInt < endPos) { + // Loop boundary crossing: load up to endPos, then stitch in + // samples from loopInfo->start to fill the rest of the DMEM + // buffer. Without stitching the tail is silence and the loop + // sounds like it ends before restarting. + // Exact byte count — no 16-byte rounding so every sample up to + // loopInfo->end is loaded and the splice happens at the precise + // loop boundary. aLoadBufferExact is used instead of aLoadBuffer + // because the standard variant internally rounds down to 16 bytes. + size_t bytesBeforeLoop = ((size_t)endPos - (size_t)synthState->samplePosInt) * 2; + s16LoopStartAdvance = (size_t)numSamplesToLoadAdj - (bytesBeforeLoop >> 1); + if (bytesBeforeLoop > 0) { + aLoadBufferExact(aList++, OS_K0_TO_PHYSICAL(sampleAddr + bytePos), + DMEM_UNCOMPRESSED_NOTE, bytesBeforeLoop); + } + // Fill the tail from the loop-start position. + size_t loopStartBytePos = (size_t)loopInfo->start * 2; + if (loopStartBytePos < bookSample->size) { + size_t tailNeeded = ((size_t)(numSamplesToLoadAdj + 16) * SAMPLE_SIZE) + - bytesBeforeLoop; + size_t tailAvail = bookSample->size - loopStartBytePos; + bytesToRead = tailNeeded < tailAvail ? tailNeeded : tailAvail; + if (bytesToRead > 0) { + aLoadBufferExact(aList++, + OS_K0_TO_PHYSICAL(sampleAddr + loopStartBytePos), + DMEM_UNCOMPRESSED_NOTE + bytesBeforeLoop, + bytesToRead); + } + } + } else { + // Normal load (no loop crossing in this frame). + size_t availBytes = bookSample->size - bytePos; + if ((size_t)(numSamplesToLoadAdj * SAMPLE_SIZE) < availBytes) { + bytesToRead = (numSamplesToLoadAdj + 16) * SAMPLE_SIZE; + if (bytesToRead > availBytes) { + bytesToRead = availBytes; + } + } else { + bytesToRead = availBytes; + } + aLoadBuffer(aList++, OS_K0_TO_PHYSICAL(sampleAddr + bytePos), + DMEM_UNCOMPRESSED_NOTE, bytesToRead); + } } - // 2S2H [Port] [Custom audio] Handle decoding OPUS data - aLoadBuffer(cmd++, sampleAddr + (synthState->samplePosInt * 2), DMEM_UNCOMPRESSED_NOTE, - bytesToRead); goto skip; } @@ -1173,7 +1241,7 @@ Acmd* AudioSynth_ProcessNote(s32 noteIndex, NoteSubEu* noteSub, NoteSynthesisSta if (loopToPoint) { synthState->restart = true; - synthState->samplePosInt = loopInfo->start; + synthState->samplePosInt = loopInfo->start + s16LoopStartAdvance; } else { synthState->samplePosInt += nSamplesToProcess; } diff --git a/src/audio/mixer.c b/src/audio/mixer.c index f80bd4bb8..a4242c3cd 100644 --- a/src/audio/mixer.c +++ b/src/audio/mixer.c @@ -156,6 +156,10 @@ void aLoadBufferImpl(const void* source_addr, uint16_t dest_addr, uint16_t nbyte #endif } +void aLoadBufferExactImpl(const void* source_addr, uint16_t dest_addr, uint16_t nbytes) { + memcpy(BUF_U8(dest_addr), source_addr, nbytes); +} + void aSaveBufferImpl(uint16_t source_addr, int16_t* dest_addr, uint16_t nbytes) { // printf("source_addr: %x\n dest_addr; %x\n nbytes: %d\n", source_addr, dest_addr, nbytes); // if (nbytes > 704) {nbytes = 704;} diff --git a/src/audio/mixer.h b/src/audio/mixer.h index 52cafd98c..af323d13d 100644 --- a/src/audio/mixer.h +++ b/src/audio/mixer.h @@ -34,6 +34,7 @@ void aClearBufferImpl(uint16_t addr, int nbytes); void aLoadBufferImpl(const void* source_addr, uint16_t dest_addr, uint16_t nbytes); +void aLoadBufferExactImpl(const void* source_addr, uint16_t dest_addr, uint16_t nbytes); void aSaveBufferImpl(uint16_t source_addr, int16_t* dest_addr, uint16_t nbytes); void aLoadADPCMImpl(int num_entries_times_16, const int16_t* book_source_addr); void aSetBufferImpl(uint8_t flags, uint16_t in, uint16_t out, uint16_t nbytes); @@ -65,6 +66,7 @@ void aUnkCmd19Impl(uint8_t f, uint16_t count, uint16_t out_addr, uint16_t in_add } while (0) #define aClearBuffer(pkt, d, c) aClearBufferImpl(d, c) #define aLoadBuffer(pkt, s, d, c) aLoadBufferImpl(s, d, c) +#define aLoadBufferExact(pkt, s, d, c) aLoadBufferExactImpl(s, d, c) #define aSaveBuffer(pkt, s, d, c) aSaveBufferImpl(s, d, c) #define aLoadADPCM(pkt, c, d) aLoadADPCMImpl(c, d) #define aSetBuffer(pkt, f, i, o, c) aSetBufferImpl(f, i, o, c) diff --git a/src/audio/note_data.c b/src/audio/note_data.c index 8409dbd03..79f03ca2c 100644 --- a/src/audio/note_data.c +++ b/src/audio/note_data.c @@ -1,6 +1,6 @@ #include "sys.h" -#include "endianness.h" #include "sf64audio_provisional.h" +#include f32 gBendPitchOneOctaveFrequencies[] = { 0.5f, 0.5f, 0.502736f, 0.505488f, 0.508254f, 0.511036f, 0.513833f, 0.516645f, 0.519472f, 0.522315f, diff --git a/src/engine/fox_bg.c b/src/engine/fox_bg.c index 06f83608a..ba7587aea 100644 --- a/src/engine/fox_bg.c +++ b/src/engine/fox_bg.c @@ -149,45 +149,64 @@ float FloatMod(float a, float b) { return result; } -// Define a single 1x1 star as two triangles -static Vtx starVerts[4] = { - // Format: VTX(x, y, z, s, t, r, g, b, a) - VTX(0, 0, 0, 0, 0, 255, 255, 255, 255), // Bottom-left - VTX(0, 1, 0, 0, 0, 255, 255, 255, 255), // Top-left - VTX(1, 0, 0, 0, 0, 255, 255, 255, 255), // Bottom-right - VTX(1, 1, 0, 0, 0, 255, 255, 255, 255), // Top-right -}; - -// Display list to render the two triangles forming the star quad -static Gfx starDL[] = { - gsSPVertex(starVerts, ARRAY_COUNT(starVerts), 0), - gsSP2Triangles(0, 1, 2, 0, 1, 2, 3, 0), - gsSPEndDisplayList(), -}; - -// Display list to render the two triangles forming the partial star quad -static Gfx starDLPartial[] = { - gsSPVertex(starVerts, ARRAY_COUNT(starVerts), 0), - gsSP2Triangles(0, 1, 2, 0, 1, 2, 3, 0), - gsSPEndDisplayList(), -}; - -// Setup render state for stars static Gfx starSetupDL[] = { gsSPTexture(0xFFFF, 0xFFFF, 0, G_TX_RENDERTILE, G_OFF), // Disable texturing - gsSPClearGeometryMode(G_ZBUFFER | G_SHADE | G_LIGHTING | G_TEXTURE_GEN | G_TEXTURE_GEN_LINEAR | G_CULL_BACK | - G_SHADING_SMOOTH), - gsDPSetCombineMode(G_CC_PRIMITIVE, G_CC_PRIMITIVE), // Use primitive color + gsSPClearGeometryMode(G_ZBUFFER | G_LIGHTING | G_TEXTURE_GEN | G_TEXTURE_GEN_LINEAR | G_CULL_BACK), + gsSPSetGeometryMode(G_SHADE | G_SHADING_SMOOTH), // Vertex colors flow through as shade + gsDPSetCombineMode(G_CC_SHADE, G_CC_SHADE), // Output the shade (vertex) color gsDPSetOtherMode(G_AD_NOTPATTERN | G_CD_MAGICSQ | G_CK_NONE | G_TC_FILT | G_TF_BILERP | G_TT_NONE | G_TL_TILE | G_TD_CLAMP | G_TP_PERSP | G_CYC_1CYCLE | G_PM_NPRIMITIVE, G_AC_NONE | G_ZS_PIXEL | G_RM_OPA_SURF | G_RM_OPA_SURF2), gsSPEndDisplayList(), }; -// New global variables for storing the previoous positions f32 gStarPrevX[3000]; f32 gStarPrevY[3000]; +#define STARFIELD_MAX_STARS 3100 +static Vtx sStarVtx[2][STARFIELD_MAX_STARS * 4]; +static void* sStarVtxLastPool = NULL; +static s32 sStarVtxBank = 0; +static s32 sStarVtxCount = 0; + +static Vtx* Starfield_AllocQuad(void) { + if ((void*) gGfxPool != sStarVtxLastPool) { + sStarVtxLastPool = (void*) gGfxPool; + sStarVtxBank = (gGfxPool == &gGfxPools[1]) ? 1 : 0; + sStarVtxCount = 0; + } + if (sStarVtxCount >= STARFIELD_MAX_STARS) { + return NULL; + } + return &sStarVtx[sStarVtxBank][sStarVtxCount++ * 4]; +} + +// Emit a 1x1 colored star quad transformed by the currently-set matrix. +static void Starfield_EmitStar(u8 r, u8 g, u8 b, u8 a) { + static const s16 corner[4][2] = { { 0, 0 }, { 0, 1 }, { 1, 0 }, { 1, 1 } }; + Vtx* q = Starfield_AllocQuad(); + + if (q == NULL) { + return; + } + + for (s32 k = 0; k < 4; k++) { + q[k].v.ob[0] = corner[k][0]; + q[k].v.ob[1] = corner[k][1]; + q[k].v.ob[2] = 0; + q[k].v.flag = 0; + q[k].v.tc[0] = 0; + q[k].v.tc[1] = 0; + q[k].v.cn[0] = r; + q[k].v.cn[1] = g; + q[k].v.cn[2] = b; + q[k].v.cn[3] = a; + } + + gSPVertex(gMasterDisp++, q, 4, 0); + gSP2Triangles(gMasterDisp++, 0, 1, 2, 0, 1, 2, 3, 0); +} + // @port: Starfield drawn with triangles, re-engineered by @Tharo & @TheBoy181 void Background_DrawStarfield(void) { f32 by; @@ -325,10 +344,8 @@ void Background_DrawStarfield(void) { b = (b << 3) | (b >> 2); // Convert 5-bit to 8-bit u8 a = 255; // Fully opaque - gDPSetPrimColor(gMasterDisp++, 0, 0, r, g, b, a); - - // Draw the star using the predefined display list - gSPDisplayList(gMasterDisp++, starDL); + // Draw the star as a colored quad (color carried in the verts) + Starfield_EmitStar(r, g, b, a); Matrix_Pop(&gGfxMatrix); if (skipInterpolation) { @@ -459,10 +476,8 @@ void Background_DrawPartialStarfield(s32 yMin, s32 yMax) { // Stars that are in b = (b << 3) | (b >> 2); // Convert 5-bit to 8-bit u8 a = 255; // Fully opaque - gDPSetPrimColor(gMasterDisp++, 0, 0, r, g, b, a); - - // Draw the star using the predefined display list - gSPDisplayList(gMasterDisp++, starDLPartial); + // Draw the star as a colored quad (color carried in the verts) + Starfield_EmitStar(r, g, b, a); // Pop the transform id FrameInterpolation_RecordCloseChild(); @@ -1413,29 +1428,17 @@ void Background_DrawGround(void) { if (gLevelMode == LEVELMODE_ON_RAILS) { gDPSetTextureImage(gMasterDisp++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 1, SEGMENTED_TO_VIRTUAL(D_CO_601B6C0)); - int interpolatedFrames = GameEngine_GetInterpolationFrameCount(); - temp_s0 = fabsf(Math_ModF(2.0f * (gPathTexScroll * 0.2133333f), 128.0f)); // 0.64f / 3.0f temp_fv0 = Math_ModF((10000.0f - gPlayer[gPlayerNum].xPath) * 0.32f, 128.0f); float xScroll = temp_fv0; float yScroll = temp_s0; + float yScrollDelta = fabsf(2.0f * (gPathTexScroll - gLastPathTexScroll) * 0.2133333f); - float inc = (2.0f * (gPathTexScroll - gLastPathTexScroll) * 0.2133333f) / (float) interpolatedFrames; - - for (int i = 0; i < interpolatedFrames; i++) { - gDPSetInterpolation(gMasterDisp++, i); - - gDPSetupTile2(gMasterDisp++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 32, 32, temp_fv0, temp_s0, - G_TX_NOMIRROR | G_TX_WRAP, G_TX_NOMIRROR | G_TX_WRAP, 5, 5, G_TX_NOLOD, G_TX_NOLOD); - - gDPSetTileSizeInterp(gMasterDisp, G_TX_RENDERTILE, xScroll, yScroll, 32 << 2, 32 << 2); - - gMasterDisp += 3; - - yScroll += inc >= 0 ? inc : -inc; - yScroll = fabs(Math_ModF(yScroll, 128.0f)); - } + gDPSetupTile2(gMasterDisp++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 32, 32, xScroll, yScroll, + G_TX_NOMIRROR | G_TX_WRAP, G_TX_NOMIRROR | G_TX_WRAP, 5, 5, G_TX_NOLOD, G_TX_NOLOD); + gDPSetTileScrollInterp(gMasterDisp, G_TX_RENDERTILE, xScroll, yScroll, 32 << 2, 32 << 2, 0.0f, yScrollDelta); + gMasterDisp += 4; switch (gGroundSurface) { case SURFACE_GRASS: @@ -1533,29 +1536,17 @@ void Background_DrawGround(void) { // gDPSetupTile(gMasterDisp++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 32, 32, temp_fv0, temp_s0, // G_TX_NOMIRROR | G_TX_WRAP, G_TX_NOMIRROR | G_TX_WRAP, 5, 5, G_TX_NOLOD, G_TX_NOLOD); - int interpolatedFrames = GameEngine_GetInterpolationFrameCount(); - temp_s0 = fabsf(Math_ModF(2.0f * (gPathTexScroll * 0.2133333f), 128.0f)); temp_fv0 = Math_ModF((10000.0f - gPlayer[gPlayerNum].xPath) * 0.32f, 128.0f); float xScroll = temp_fv0; float yScroll = temp_s0; + float yScrollDelta = fabsf(2.0f * (gPathTexScroll - gLastPathTexScroll) * 0.2133333f); - float inc = (2.0f * (gPathTexScroll - gLastPathTexScroll) * 0.2133333f) / (float) interpolatedFrames; - - for (int i = 0; i < interpolatedFrames; i++) { - gDPSetInterpolation(gMasterDisp++, i); - - gDPSetupTile2(gMasterDisp++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 32, 32, temp_fv0, temp_s0, - G_TX_NOMIRROR | G_TX_WRAP, G_TX_NOMIRROR | G_TX_WRAP, 5, 5, G_TX_NOLOD, G_TX_NOLOD); - - gDPSetTileSizeInterp(gMasterDisp, G_TX_RENDERTILE, xScroll, yScroll, 32 << 2, 32 << 2); - - gMasterDisp += 3; - - yScroll += inc >= 0 ? inc : -inc; - yScroll = fabs(Math_ModF(yScroll, 128.0f)); - } + gDPSetupTile2(gMasterDisp++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 32, 32, xScroll, yScroll, + G_TX_NOMIRROR | G_TX_WRAP, G_TX_NOMIRROR | G_TX_WRAP, 5, 5, G_TX_NOLOD, G_TX_NOLOD); + gDPSetTileScrollInterp(gMasterDisp, G_TX_RENDERTILE, xScroll, yScroll, 32 << 2, 32 << 2, 0.0f, yScrollDelta); + gMasterDisp += 4; // CENTER FAR Matrix_Push(&gGfxMatrix); @@ -1640,29 +1631,17 @@ void Background_DrawGround(void) { // } gDPSetTextureImage(gMasterDisp++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 1, sp1C4); - int interpolatedFrames = GameEngine_GetInterpolationFrameCount(); - temp_s0 = fabsf(Math_ModF(2.0f * (gPathTexScroll * 0.2133333f), 128.0f)); // 0.64f / 3.0f temp_fv0 = Math_ModF((10000.0f - gPlayer[gPlayerNum].xPath) * 0.32f, 128.0f); float xScroll = temp_fv0; float yScroll = temp_s0; + float yScrollDelta = fabsf(2.0f * (gPathTexScroll - gLastPathTexScroll) * 0.2133333f); - float inc = (2.0f * (gPathTexScroll - gLastPathTexScroll) * 0.2133333f) / (float) interpolatedFrames; - - for (int i = 0; i < interpolatedFrames; i++) { - gDPSetInterpolation(gMasterDisp++, i); - - gDPSetupTile2(gMasterDisp++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 32, 32, temp_fv0, temp_s0, - G_TX_NOMIRROR | G_TX_WRAP, G_TX_NOMIRROR | G_TX_WRAP, 5, 5, G_TX_NOLOD, G_TX_NOLOD); - - gDPSetTileSizeInterp(gMasterDisp, G_TX_RENDERTILE, xScroll, yScroll, 32 << 2, 32 << 2); - - gMasterDisp += 3; - - yScroll += inc >= 0 ? inc : -inc; - yScroll = fabs(Math_ModF(yScroll, 128.0f)); - } + gDPSetupTile2(gMasterDisp++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 32, 32, xScroll, yScroll, + G_TX_NOMIRROR | G_TX_WRAP, G_TX_NOMIRROR | G_TX_WRAP, 5, 5, G_TX_NOLOD, G_TX_NOLOD); + gDPSetTileScrollInterp(gMasterDisp, G_TX_RENDERTILE, xScroll, yScroll, 32 << 2, 32 << 2, 0.0f, yScrollDelta); + gMasterDisp += 4; // Original Display (Center) Matrix_Push(&gGfxMatrix); @@ -1733,29 +1712,17 @@ void Background_DrawGround(void) { 32); gDPSetTextureImage(gMasterDisp++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 1, SEGMENTED_TO_VIRTUAL(D_AQ_600AB68)); - int interpolatedFrames = GameEngine_GetInterpolationFrameCount(); - temp_s0 = fabsf(Math_ModF(2.0f * (gPathTexScroll * 0.2133333f), 128.0f)); temp_fv0 = Math_ModF((10000.0f - gPlayer[gPlayerNum].xPath) * 0.32f, 128.0f); float xScroll = temp_fv0; float yScroll = temp_s0; + float yScrollDelta = fabsf(2.0f * (gPathTexScroll - gLastPathTexScroll) * 0.2133333f); - float inc = (2.0f * (gPathTexScroll - gLastPathTexScroll) * 0.2133333f) / (float) interpolatedFrames; - - for (int i = 0; i < interpolatedFrames; i++) { - gDPSetInterpolation(gMasterDisp++, i); - - gDPSetupTile2(gMasterDisp++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 32, 32, temp_fv0, temp_s0, - G_TX_NOMIRROR | G_TX_WRAP, G_TX_NOMIRROR | G_TX_WRAP, 5, 5, G_TX_NOLOD, G_TX_NOLOD); - - gDPSetTileSizeInterp(gMasterDisp, G_TX_RENDERTILE, xScroll, yScroll, 32 << 2, 32 << 2); - - gMasterDisp += 3; - - yScroll += inc >= 0 ? inc : -inc; - yScroll = fabs(Math_ModF(yScroll, 128.0f)); - } + gDPSetupTile2(gMasterDisp++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 32, 32, xScroll, yScroll, + G_TX_NOMIRROR | G_TX_WRAP, G_TX_NOMIRROR | G_TX_WRAP, 5, 5, G_TX_NOLOD, G_TX_NOLOD); + gDPSetTileScrollInterp(gMasterDisp, G_TX_RENDERTILE, xScroll, yScroll, 32 << 2, 32 << 2, 0.0f, yScrollDelta); + gMasterDisp += 4; // CENTER FAR Matrix_Push(&gGfxMatrix); @@ -1808,29 +1775,17 @@ void Background_DrawGround(void) { 32); gDPSetTextureImage(gMasterDisp++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 1, SEGMENTED_TO_VIRTUAL(D_AQ_602ACC0)); - int interpolatedFrames = GameEngine_GetInterpolationFrameCount(); - temp_s0 = fabsf(Math_ModF(2.0f * (gPathTexScroll * 0.2133333f), 128.0f)); temp_fv0 = Math_ModF((10000.0f - gPlayer[gPlayerNum].xPath) * 0.32f, 128.0f); float xScroll = temp_fv0; float yScroll = temp_s0; + float yScrollDelta = fabsf(2.0f * (gPathTexScroll - gLastPathTexScroll) * 0.2133333f); - float inc = (2.0f * (gPathTexScroll - gLastPathTexScroll) * 0.2133333f) / (float) interpolatedFrames; - - for (int i = 0; i < interpolatedFrames; i++) { - gDPSetInterpolation(gMasterDisp++, i); - - gDPSetupTile2(gMasterDisp++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 32, 32, temp_fv0, temp_s0, - G_TX_NOMIRROR | G_TX_WRAP, G_TX_NOMIRROR | G_TX_WRAP, 5, 5, G_TX_NOLOD, G_TX_NOLOD); - - gDPSetTileSizeInterp(gMasterDisp, G_TX_RENDERTILE, xScroll, yScroll, 32 << 2, 32 << 2); - - gMasterDisp += 3; - - yScroll += inc >= 0 ? inc : -inc; - yScroll = fabs(Math_ModF(yScroll, 128.0f)); - } + gDPSetupTile2(gMasterDisp++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 32, 32, xScroll, yScroll, + G_TX_NOMIRROR | G_TX_WRAP, G_TX_NOMIRROR | G_TX_WRAP, 5, 5, G_TX_NOLOD, G_TX_NOLOD); + gDPSetTileScrollInterp(gMasterDisp, G_TX_RENDERTILE, xScroll, yScroll, 32 << 2, 32 << 2, 0.0f, yScrollDelta); + gMasterDisp += 4; if (gAqDrawMode != 0) { RCP_SetupDL(&gMasterDisp, SETUPDL_47); diff --git a/src/engine/fox_context.c b/src/engine/fox_context.c index 5b92b875f..eb5a1e771 100644 --- a/src/engine/fox_context.c +++ b/src/engine/fox_context.c @@ -1,8 +1,6 @@ #include "prevent_context_reordering.h" -#include "sys.h" -#include "sf64level.h" -#include "sf64object.h" -#include "sf64player.h" + +#include "sf64context.h" s32 gSceneId; s32 gSceneSetup; @@ -146,7 +144,7 @@ f32 gSunViewX; // something x translate f32 gSunViewY; // something y translate s32 gFogNear; // near s32 gFogFar; // far -UNK_TYPE F_801783E0; +UNK_TYPE F_801783E0[12]; UNK_TYPE F_801783E4; UNK_TYPE F_801783E8; UNK_TYPE F_801783EC; @@ -272,7 +270,7 @@ s32 gSavedHitCount; s16 gLifeCount[4]; LaserStrength gLaserStrength[4]; s32 gCullObjects; -UNK_TYPE F_80161AC0[4]; +UNK_TYPE F_80161AC0[16]; UNK_TYPE F_80161AD0[4]; UNK_TYPE F_80161AE0[4]; UNK_TYPE F_80161AF0[4]; diff --git a/src/engine/fox_demo.c b/src/engine/fox_demo.c index dfdacc778..0c6ce65d7 100644 --- a/src/engine/fox_demo.c +++ b/src/engine/fox_demo.c @@ -467,7 +467,9 @@ void Cutscene_EnterWarpZone(Player* player) { } player->unk_190 = 2.0f; player->camDist -= 2.0f; - gBlurAlpha = 128; + // @port: match the boost warp's trail strength (original pins this at 128, which + // reads much milder than the rest of the warp effect). See fox_play.c warp-zone case. + gBlurAlpha = 64; break; case 2: diff --git a/src/engine/fox_game.c b/src/engine/fox_game.c index 9591dad80..1f7597fe8 100644 --- a/src/engine/fox_game.c +++ b/src/engine/fox_game.c @@ -7,6 +7,12 @@ #include "port/hooks/list/EngineEvent.h" #include "port/mods/PortEnhancements.h" +// @port: motion-blur trail compensation (see Game_InitMasterDL) +extern u32 GameEngine_GetInterpolationFrameCount(void); +extern float powf(float base, float exponent); + +#define BLUR_MAX_PERSISTENCE_PCT_DEFAULT 30 + f32 gNextVsViewScale; f32 gVsViewScale; s32 gPlayerInactive[4]; @@ -171,12 +177,41 @@ void Game_InitMasterDL(Gfx** dList) { gDPSetColorImage((*dList)++, G_IM_FMT_RGBA, G_IM_SIZ_16b, RIGHT_MARGIN, gFrameBuffer); if (gBlurAlpha < 255) { + // @port: Motion-blur trail. On N64 this translucent fill was applied once per displayed + // frame to a triple-buffered target (each of the 3 buffers revisited every 3 frames), + // so a pixel decays by (1 - a) every 3 frames => (1 - a)^(1/3) per frame. + s32 interpFrames = GameEngine_GetInterpolationFrameCount(); + u8 blurAlpha; + f32 perFrame; + f32 aEff; + + if (interpFrames < 1) { + interpFrames = 1; + } + + f32 a = gBlurAlpha / 255.0f; + + perFrame = powf(1.0f - a, 1.0f / 3.0f); + + f32 maxPersistence = CVarGetInteger("gEnhancements.Graphics.BlurTrailCap", BLUR_MAX_PERSISTENCE_PCT_DEFAULT) / + 100.0f; + if (perFrame > maxPersistence) { + perFrame = maxPersistence; + } + + aEff = 1.0f - powf(perFrame, 1.0f / (f32) interpFrames); + + blurAlpha = (u8) (aEff * 255.0f + 0.5f); + if (blurAlpha < 1) { + blurAlpha = 1; // keep some erase, otherwise the trail would never fade out + } + gDPPipeSync((*dList)++); gDPSetCycleType((*dList)++, G_CYC_1CYCLE); gDPSetCombineMode((*dList)++, G_CC_PRIMITIVE, G_CC_PRIMITIVE); gDPSetRenderMode((*dList)++, G_RM_XLU_SURF, G_RM_XLU_SURF2); gDPSetPrimColor((*dList)++, 0x00, 0x00, RGBA16_RED(gBgColor) * 8, RGBA16_GRN(gBgColor) * 8, - RGBA16_BLU(gBgColor) * 8, gBlurAlpha); + RGBA16_BLU(gBgColor) * 8, blurAlpha); } else { gDPSetFillColor((*dList)++, FILL_COLOR(gBgColor | 1)); } diff --git a/src/engine/fox_play.c b/src/engine/fox_play.c index c11c9dd64..e09b6118f 100644 --- a/src/engine/fox_play.c +++ b/src/engine/fox_play.c @@ -6881,7 +6881,10 @@ void Play_UpdateLevel(void) { /* fallthrough */ case LEVEL_SECTOR_X: if (gLevelPhase == 1) { - gBlurAlpha = 128; + // @port: warp-zone trail. The original pins this at 128, which reads much + // milder than the boost warp (which ramps down to 64). Match the boost so the + // warp zone is as lush as the rest of the warp effect. + gBlurAlpha = 64; if (gPlayer[0].state == PLAYERSTATE_LEVEL_COMPLETE) { Math_SmoothStepToF(&gWarpZoneBgAlpha, 0.0f, 1.0f, 1.0f, 0.0f); } else { diff --git a/src/engine/fox_radio.c b/src/engine/fox_radio.c index e60f80c1e..f3412f293 100644 --- a/src/engine/fox_radio.c +++ b/src/engine/fox_radio.c @@ -190,6 +190,76 @@ void Radio_CalculatePositions() { s32 sRadioUseRedBox; +// @port: The radio box/portrait originally draw as 2D texture rectangles, whose +// coordinates are baked on the CPU -- the frame-interpolation system only +// interpolates matrices, so those texrects can't be smoothed and the slide/scale +// animation runs at the native (20fps) tick rate. Drawing them as matrix-transformed +// quads instead lets the matrix interpolation smooth them (the Matrix_* calls below +// self-record into the interpolation tree, like the 3D character heads already do). +#define RADIO_MAX_QUADS 4 +static Vtx sRadioVtx[2][RADIO_MAX_QUADS * 4]; +static void* sRadioVtxLastPool = NULL; +static s32 sRadioVtxBank = 0; +static s32 sRadioVtxCount = 0; + +static Vtx* Radio_AllocQuad(void) { + // Double-buffered in lockstep with the gfx pool so the previous frame's verts + // are never overwritten while still being rendered/replayed for interpolation. + if ((void*) gGfxPool != sRadioVtxLastPool) { + sRadioVtxLastPool = (void*) gGfxPool; + sRadioVtxBank = (gGfxPool == &gGfxPools[1]) ? 1 : 0; + sRadioVtxCount = 0; + } + if (sRadioVtxCount >= RADIO_MAX_QUADS) { + return NULL; + } + return &sRadioVtx[sRadioVtxBank][sRadioVtxCount++ * 4]; +} + +// Draws a w x h-texel quad (texture/tile already loaded) at screen-space top-left +// (xPos, yPos), sized (w*xScale, h*yScale), through an ortho matrix so the slide/scale +// animation is interpolated. The Matrix_* transform records itself for interpolation. +static void Radio_DrawInterpTexQuad(f32 xPos, f32 yPos, u32 w, u32 h, f32 xScale, f32 yScale) { + Vtx* q = Radio_AllocQuad(); + s16 uMax; + s16 vMax; + s32 k; + + if (q == NULL) { + return; + } + + uMax = (s16) (w << 5); + vMax = (s16) (h << 5); + + q[0].v.ob[0] = 0; q[0].v.ob[1] = 0; q[0].v.tc[0] = 0; q[0].v.tc[1] = 0; // top-left + q[1].v.ob[0] = (s16) w; q[1].v.ob[1] = 0; q[1].v.tc[0] = uMax; q[1].v.tc[1] = 0; // top-right + q[2].v.ob[0] = 0; q[2].v.ob[1] = -(s16) h; q[2].v.tc[0] = 0; q[2].v.tc[1] = vMax; // bottom-left + q[3].v.ob[0] = (s16) w; q[3].v.ob[1] = -(s16) h; q[3].v.tc[0] = uMax; q[3].v.tc[1] = vMax; // bottom-right + for (k = 0; k < 4; k++) { + q[k].v.ob[2] = 0; + q[k].v.flag = 0; + q[k].v.cn[0] = 255; + q[k].v.cn[1] = 255; + q[k].v.cn[2] = 255; + q[k].v.cn[3] = 255; + } + + // Ortho maps [-SCREEN_WIDTH/2, SCREEN_WIDTH/2] x [-SCREEN_HEIGHT/2, SCREEN_HEIGHT/2] + // (Y up) to the screen; convert the screen top-left accordingly. + Lib_InitOrtho(&gMasterDisp); + // Unlike a texture rectangle, a real triangle quad is subject to back-face culling. + gSPClearGeometryMode(gMasterDisp++, G_CULL_BACK); + Matrix_Push(&gGfxMatrix); + Matrix_Translate(gGfxMatrix, xPos - (SCREEN_WIDTH / 2.0f), (SCREEN_HEIGHT / 2.0f) - yPos, 0.0f, MTXF_NEW); + Matrix_Scale(gGfxMatrix, xScale, yScale, 1.0f, MTXF_APPLY); + Matrix_SetGfxMtx(&gMasterDisp); + gSPVertex(gMasterDisp++, q, 4, 0); + gSP2Triangles(gMasterDisp++, 0, 1, 2, 0, 1, 2, 3, 0); + Matrix_Pop(&gGfxMatrix); + Lib_InitPerspective(&gMasterDisp); +} + void func_radio_800BAAE8(void) { static f32 D_800D4A74 = -1.0f; u16* radioPortraitTex = NULL; @@ -517,8 +587,12 @@ void func_radio_800BB388(void) { gDPSetPrimColor(gMasterDisp++, 0x00, 0x00, 60, 60, 255, 170); } - Lib_TextureRect_CI8(&gMasterDisp, texture, palette, 32, 32, gRadioTextBoxPosX, gRadioTextBoxPosY + 16.0f + sp30, - gRadioTextBoxScaleX, gRadioTextBoxScaleY); + // @port: matrix-quad instead of Lib_TextureRect_CI8 so the slide/scale interpolates. + gDPLoadTLUT_pal256(gMasterDisp++, palette); + gDPLoadTextureBlock(gMasterDisp++, texture, G_IM_FMT_CI, G_IM_SIZ_8b, 32, 32, 0, G_TX_NOMIRROR | G_TX_WRAP, + G_TX_NOMIRROR | G_TX_WRAP, G_TX_NOMASK, G_TX_NOMASK, G_TX_NOLOD, G_TX_NOLOD); + Radio_DrawInterpTexQuad(gRadioTextBoxPosX, gRadioTextBoxPosY + 16.0f + sp30, 32, 32, gRadioTextBoxScaleX, + gRadioTextBoxScaleY); } if (gRadioTextBoxScaleY == 1.3f) { diff --git a/src/overlays/ovl_ending/fox_end2.c b/src/overlays/ovl_ending/fox_end2.c index 4525c76f6..109deb5e6 100644 --- a/src/overlays/ovl_ending/fox_end2.c +++ b/src/overlays/ovl_ending/fox_end2.c @@ -459,23 +459,13 @@ void Ending_8018EDB8(u32 arg0, AssetInfo* asset) { gDPLoadTextureBlock(gMasterDisp++, D_END_700EA38, G_IM_FMT_RGBA, G_IM_SIZ_16b, 32, 32, 0, G_TX_WRAP | G_TX_NOMIRROR, G_TX_WRAP | G_TX_NOMIRROR, 5, 5, G_TX_NOLOD, G_TX_NOLOD); - int interpolatedFrames = GameEngine_GetInterpolationFrameCount(); float scrollArg = arg0 * 14; - float inc = 14 / (float) interpolatedFrames; - for (int i = 0; i < interpolatedFrames; i++) { - gDPSetInterpolation(gMasterDisp++, i); - - gDPSetupTile2(gMasterDisp++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 32, 32, scrollArg, 0, G_TX_NOMIRROR | G_TX_WRAP, - G_TX_NOMIRROR | G_TX_WRAP, 5, 5, G_TX_NOLOD, G_TX_NOLOD); - - gDPSetTileSizeInterp(gMasterDisp, G_TX_RENDERTILE, scrollArg, 0, 32 << 2, 0); - - gMasterDisp += 3; - - scrollArg += inc; - } + gDPSetupTile2(gMasterDisp++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 32, 32, scrollArg, 0, G_TX_NOMIRROR | G_TX_WRAP, + G_TX_NOMIRROR | G_TX_WRAP, 5, 5, G_TX_NOLOD, G_TX_NOLOD); + gDPSetTileScrollInterp(gMasterDisp, G_TX_RENDERTILE, scrollArg, 0, 32 << 2, 0, 14.0f, 0.0f); + gMasterDisp += 4; gSPDisplayList(gMasterDisp++, D_END_700E9E0); } diff --git a/src/overlays/ovl_menu/fox_map.c b/src/overlays/ovl_menu/fox_map.c index cff27e657..1d3fdfc62 100644 --- a/src/overlays/ovl_menu/fox_map.c +++ b/src/overlays/ovl_menu/fox_map.c @@ -2075,10 +2075,10 @@ void Map_Texture_Sphere(u8* textureDest, u8* textureSrc, f32* offset) { if (*offset > 95.0f) { *offset = 0.0f; } - -#ifndef __SWITCH__ - gSPInvalidateTexCache(gMasterDisp++, NULL); -#endif + + for (s32 band = 0; band < 12; band++) { + gSPInvalidateTexCache(gMasterDisp++, (textureDest + (96 * 8 * band))); + } } void Map_Prologue_Update(void) { diff --git a/src/overlays/ovl_menu/fox_title.h b/src/overlays/ovl_menu/fox_title.h index 4e2226232..48330b3d2 100644 --- a/src/overlays/ovl_menu/fox_title.h +++ b/src/overlays/ovl_menu/fox_title.h @@ -114,141 +114,141 @@ typedef struct { /* 0x10 */ f32 scale; } TitleCorneria; // size = 0x14 -extern CameraPoint D_menu_801B6B40[]; -extern CameraPoint D_menu_801B6C60[]; -extern f32 D_menu_801B7BB0; -extern f32 D_menu_801B7BB4; -extern f32 D_menu_801B7BB8; -extern f32 D_menu_801B7BBC; -extern f32 D_menu_801B7BC0; -extern f32 D_menu_801B7BC4; -extern f32 sTitleTextPrimCol; -extern f32 sTitleTextPrimColTarget; -extern s32 D_menu_801B7BD0; -extern TitleLogoStates sTitleLogoState; -extern s32 D_menu_801B7BD8; -extern f32 sStarfoxLogoAlpha; -extern f32 sInAlpha; -extern s32 D_menu_801B7BE4; -extern f32 D_menu_801B7BE8; -extern s32 D_menu_801B7BEC; -extern TitleCardStates sTitleCardState; -extern f32 D_menu_801B7BF8[10]; -extern f32 D_menu_801B7C20[10]; -extern f32 D_menu_801B7C48[10]; -extern f32 D_menu_801B7C70[10]; -extern s32 sMaxExplosions; -extern s32 D_menu_801B7CA0[10]; -extern s32 D_menu_801B7CC8[10]; -extern s32 D_menu_801B7CF0[10]; -extern s32 D_menu_801B7D18[10]; -extern f32 D_menu_801B7D40[40]; -extern f32 D_menu_801B7DE0[40]; -extern f32 D_menu_801B7E80[40]; -extern f32 D_menu_801B7F20[40]; -extern f32 D_menu_801B7FC0[40]; -extern f32 D_menu_801B8060[40]; -extern s32 D_menu_801B8100; -extern s32 D_menu_801B8108[40]; -extern s32 gRankingTeamAlive[10][3]; -extern s32 gTotalHitsRanking[10]; -extern u8 sRankNameEntry[10][4]; -extern UNK_TYPE D_menu_801B8270[3]; -extern bool gGoToTitle; -extern u8 sLevelStartState; -extern s32 sWipeHeight; -extern s32 sTitleRankMaxRecords; -extern f32 D_menu_801B828C; -extern f32 D_menu_801B8290; -extern CameraPoint* D_menu_801B8294; -extern s32 D_menu_801B8298; -extern f32 sTitleCamUpX; -extern f32 sTitleCamUpY; -extern f32 sTitleCamUpZ; -extern s32 sTimer1; -extern s32 sTimer2; -extern s32 D_menu_801B82B0; -extern s32 sTimer3; -extern s32 sTitleMsgFrameCount; -extern s32 D_menu_801B82BC; -extern s32 sSceneState; -extern s32 sCutsceneState; -extern f32 sPassageWayZoffset; -extern f32 D_menu_801B82CC; -extern f32 D_menu_801B82D0; -extern f32 D_menu_801B82D4; -extern f32 D_menu_801B82D8; -extern f32 D_menu_801B82DC; -extern f32 D_menu_801B82E0; -extern f32 D_menu_801B82E4; -extern f32 D_menu_801B82E8; -extern f32 D_menu_801B82EC; -extern f32 D_menu_801B82F0; -extern f32 D_menu_801B82F4; -extern s32 D_menu_801B82F8; -extern s32 D_menu_801B82FC; -extern s32 D_menu_801B8300; -extern f32 D_menu_801B8304; -extern f32 D_menu_801B8308; -extern f32 D_menu_801B830C; -extern s32 D_menu_801B8310; -extern s32 D_menu_801B8314; -extern s32 D_menu_801B8318; -extern s32 D_menu_801B831C; -extern s32 D_menu_801B8320; -extern s32 D_menu_801B8324; -extern f32 sAmbientR; -extern f32 sAmbientG; -extern f32 sAmbientB; -extern s32 D_menu_801B8334; -extern bool D_menu_801B8338; -extern f32 D_menu_801B833C; -extern TitleTeam D_menu_801B8340; -extern bool sDrawTeamName; -extern bool D_menu_801B8348; -extern TitleTeamInfo sTitleTeam[4]; -extern f32 D_menu_801B84D0; -extern f32 D_menu_801B84D4; -extern f32 D_menu_801B84D8[3]; -extern TitleArwingInfo sTitleArwing[4]; -extern TitleGreatFoxInfo sTitleGreatFox; -extern TitleCorneria sTitleCorneria; -extern s32 D_menu_801B869C; -extern bool sDrawTakeOffSpace; -extern s32 D_menu_801B86A4; -extern f32 D_menu_801B86A8; -extern f32 D_menu_801B86AC; -extern f32 D_menu_801B86B0; -extern f32 D_menu_801B86B4; -extern f32 D_menu_801B86B8; -extern f32 D_menu_801B86BC; -extern f32 D_menu_801B86C0; -extern f32 D_menu_801B86C4; -extern f32 D_menu_801B86C8; -extern f32 D_menu_801B86CC; -extern f32 D_menu_801B86D0; -extern f32 D_menu_801B86D4; -extern f32 D_menu_801B86D8; -extern f32 D_menu_801B86DC; -extern Vec3f sCharFrameTable[4][50]; -extern bool D_menu_801B9040; -extern f32 sTitleDeckLauncherZpos; -extern f32 D_menu_801B9048; -extern f32 D_menu_801B904C; -extern f32 D_menu_801B9050; -extern f32 sTitleStarfoxLogoXpos; -extern f32 sTitleStarfoxLogoYpos; -extern f32 D_menu_801B905C; -extern f32 D_menu_801B9060; -extern f32 D_menu_801B9064; -extern f32 D_menu_801B9068; -extern f32 D_menu_801B906C; -extern f32 D_menu_801B9070; -extern f32 D_menu_801B9074; -extern f32 D_menu_801B9078; -extern f32 D_menu_801B907C; -extern f32 D_menu_801B9080; -extern f32 D_menu_801B9084; +extern_s CameraPoint D_menu_801B6B40[]; +extern_s CameraPoint D_menu_801B6C60[]; +extern_s f32 D_menu_801B7BB0; +extern_s f32 D_menu_801B7BB4; +extern_s f32 D_menu_801B7BB8; +extern_s f32 D_menu_801B7BBC; +extern_s f32 D_menu_801B7BC0; +extern_s f32 D_menu_801B7BC4; +extern_s f32 sTitleTextPrimCol; +extern_s f32 sTitleTextPrimColTarget; +extern_s s32 D_menu_801B7BD0; +extern_s TitleLogoStates sTitleLogoState; +extern_s s32 D_menu_801B7BD8; +extern_s f32 sStarfoxLogoAlpha; +extern_s f32 sInAlpha; +extern_s s32 D_menu_801B7BE4; +extern_s f32 D_menu_801B7BE8; +extern_s s32 D_menu_801B7BEC; +extern_s TitleCardStates sTitleCardState; +extern_s f32 D_menu_801B7BF8[10]; +extern_s f32 D_menu_801B7C20[10]; +extern_s f32 D_menu_801B7C48[10]; +extern_s f32 D_menu_801B7C70[10]; +extern_s s32 sMaxExplosions; +extern_s s32 D_menu_801B7CA0[10]; +extern_s s32 D_menu_801B7CC8[10]; +extern_s s32 D_menu_801B7CF0[10]; +extern_s s32 D_menu_801B7D18[10]; +extern_s f32 D_menu_801B7D40[40]; +extern_s f32 D_menu_801B7DE0[40]; +extern_s f32 D_menu_801B7E80[40]; +extern_s f32 D_menu_801B7F20[40]; +extern_s f32 D_menu_801B7FC0[40]; +extern_s f32 D_menu_801B8060[40]; +extern_s s32 D_menu_801B8100; +extern_s s32 D_menu_801B8108[40]; +extern_s s32 gRankingTeamAlive[10][3]; +extern_s s32 gTotalHitsRanking[10]; +extern_s u8 sRankNameEntry[10][4]; +extern_s UNK_TYPE D_menu_801B8270[3]; +extern_s bool gGoToTitle; +extern_s u8 sLevelStartState; +extern_s s32 sWipeHeight; +extern_s s32 sTitleRankMaxRecords; +extern_s f32 D_menu_801B828C; +extern_s f32 D_menu_801B8290; +extern_s CameraPoint* D_menu_801B8294; +extern_s s32 D_menu_801B8298; +extern_s f32 sTitleCamUpX; +extern_s f32 sTitleCamUpY; +extern_s f32 sTitleCamUpZ; +extern_s s32 sTimer1; +extern_s s32 sTimer2; +extern_s s32 D_menu_801B82B0; +extern_s s32 sTimer3; +extern_s s32 sTitleMsgFrameCount; +extern_s s32 D_menu_801B82BC; +extern_s s32 sSceneState; +extern_s s32 sCutsceneState; +extern_s f32 sPassageWayZoffset; +extern_s f32 D_menu_801B82CC; +extern_s f32 D_menu_801B82D0; +extern_s f32 D_menu_801B82D4; +extern_s f32 D_menu_801B82D8; +extern_s f32 D_menu_801B82DC; +extern_s f32 D_menu_801B82E0; +extern_s f32 D_menu_801B82E4; +extern_s f32 D_menu_801B82E8; +extern_s f32 D_menu_801B82EC; +extern_s f32 D_menu_801B82F0; +extern_s f32 D_menu_801B82F4; +extern_s s32 D_menu_801B82F8; +extern_s s32 D_menu_801B82FC; +extern_s s32 D_menu_801B8300; +extern_s f32 D_menu_801B8304; +extern_s f32 D_menu_801B8308; +extern_s f32 D_menu_801B830C; +extern_s s32 D_menu_801B8310; +extern_s s32 D_menu_801B8314; +extern_s s32 D_menu_801B8318; +extern_s s32 D_menu_801B831C; +extern_s s32 D_menu_801B8320; +extern_s s32 D_menu_801B8324; +extern_s f32 sAmbientR; +extern_s f32 sAmbientG; +extern_s f32 sAmbientB; +extern_s s32 D_menu_801B8334; +extern_s bool D_menu_801B8338; +extern_s f32 D_menu_801B833C; +extern_s TitleTeam D_menu_801B8340; +extern_s bool sDrawTeamName; +extern_s bool D_menu_801B8348; +extern_s TitleTeamInfo sTitleTeam[4]; +extern_s f32 D_menu_801B84D0; +extern_s f32 D_menu_801B84D4; +extern_s f32 D_menu_801B84D8[3]; +extern_s TitleArwingInfo sTitleArwing[4]; +extern_s TitleGreatFoxInfo sTitleGreatFox; +extern_s TitleCorneria sTitleCorneria; +extern_s s32 D_menu_801B869C; +extern_s bool sDrawTakeOffSpace; +extern_s s32 D_menu_801B86A4; +extern_s f32 D_menu_801B86A8; +extern_s f32 D_menu_801B86AC; +extern_s f32 D_menu_801B86B0; +extern_s f32 D_menu_801B86B4; +extern_s f32 D_menu_801B86B8; +extern_s f32 D_menu_801B86BC; +extern_s f32 D_menu_801B86C0; +extern_s f32 D_menu_801B86C4; +extern_s f32 D_menu_801B86C8; +extern_s f32 D_menu_801B86CC; +extern_s f32 D_menu_801B86D0; +extern_s f32 D_menu_801B86D4; +extern_s f32 D_menu_801B86D8; +extern_s f32 D_menu_801B86DC; +extern_s Vec3f sCharFrameTable[4][50]; +extern_s bool D_menu_801B9040; +extern_s f32 sTitleDeckLauncherZpos; +extern_s f32 D_menu_801B9048; +extern_s f32 D_menu_801B904C; +extern_s f32 D_menu_801B9050; +extern_s f32 sTitleStarfoxLogoXpos; +extern_s f32 sTitleStarfoxLogoYpos; +extern_s f32 D_menu_801B905C; +extern_s f32 D_menu_801B9060; +extern_s f32 D_menu_801B9064; +extern_s f32 D_menu_801B9068; +extern_s f32 D_menu_801B906C; +extern_s f32 D_menu_801B9070; +extern_s f32 D_menu_801B9074; +extern_s f32 D_menu_801B9078; +extern_s f32 D_menu_801B907C; +extern_s f32 D_menu_801B9080; +extern_s f32 D_menu_801B9084; void Title_Screen_Input(void); void Title_Cutscene_SetCamera(CameraPoint*, s32, f32); diff --git a/src/port/Engine.cpp b/src/port/Engine.cpp index bc0ccb1f7..072edc664 100644 --- a/src/port/Engine.cpp +++ b/src/port/Engine.cpp @@ -1,10 +1,13 @@ #include "Engine.h" #include "ui/ImguiUI.h" -#include "StringHelper.h" +#include +#include +#include +#include "audio/AudioDebug.h" +#ifndef __SWITCH__ #include "extractor/GameExtractor.h" -#include "libultraship/src/Context.h" -#include "libultraship/src/controller/controldevice/controller/mapping/ControllerDefaultMappings.h" +#endif #include "resource/type/ResourceType.h" #include "resource/importers/AnimFactory.h" #include "resource/importers/ColPolyFactory.h" @@ -28,24 +31,35 @@ #include "resource/importers/audio/InstrumentFactory.h" #include "resource/importers/audio/LoopFactory.h" #include "resource/importers/audio/SampleFactory.h" +#include "resource/importers/audio/SequenceFactory.h" #include "resource/importers/audio/SoundFontFactory.h" #include "port/interpolation/FrameInterpolation.h" -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include "audio/GameAudio.h" +#include "controller/controldeck/ControlDeck.h" +#include "fast/resource/ResourceType.h" #include "port/patches/DisplayListPatch.h" #include "port/mods/PortEnhancements.h" - -#include -#include +#include "port/ui/cvar_prefixes.h" +#include "port/build.h" +#include "port/ShipInit.h" +#ifndef __SWITCH__ +#include +#endif +#include "port/notification/notification.h" #ifdef __SWITCH__ -#include +#include #endif namespace fs = std::filesystem; @@ -64,7 +78,7 @@ GameEngine* GameEngine::Instance; GameEngine::GameEngine() { // Initialize context properties early to recognize paths properly for non-portable builds - this->context = Ship::Context::CreateUninitializedInstance("Starship", "ship", "starship.cfg.json"); + context = Ship::Context::CreateUninitializedInstance("Starship", "ship", "starship.cfg.json"); #ifdef __SWITCH__ Ship::Switch::Init(Ship::PreInitPhase); @@ -104,8 +118,9 @@ GameEngine::GameEngine() { archiveFiles.push_back(assets_path); } - if (const std::string patches_path = Ship::Context::GetPathRelativeToAppDirectory("mods"); - !patches_path.empty()) { + const std::string patches_path = Ship::Context::GetPathRelativeToAppDirectory("mods"); + + if (!patches_path.empty()) { if (!std::filesystem::exists(patches_path)) { std::filesystem::create_directories(patches_path); } @@ -122,11 +137,18 @@ GameEngine::GameEngine() { archiveFiles.push_back(p.path().generic_string()); } } + + for (const auto& p : std::filesystem::directory_iterator(patches_path)) { + if (p.is_directory()) { + SPDLOG_INFO("Found mod directory: {}", p.path().generic_string()); + archiveFiles.push_back(p.path().generic_string()); + } + } } } - this->context->InitConfiguration(); // without this line InitConsoleVariables fails at Config::Reload() - this->context->InitConsoleVariables(); // without this line the controldeck constructor failes in + context->InitConfiguration(); // without this line InitConsoleVariables fails at Config::Reload() + context->InitConsoleVariables(); // without this line the controldeck constructor failes in // ShipDeviceIndexMappingManager::UpdateControllerNamesFromConfig() auto defaultMappings = std::make_shared( @@ -160,22 +182,133 @@ GameEngine::GameEngine() { // SDLAxisDirectionToAxisDirectionMappings - use built-in LUS defaults std::unordered_map>>>() ); - auto controlDeck = std::make_shared(std::vector(), defaultMappings); + std::unordered_map names; + auto controlDeck = std::make_shared(); + + context->InitControlDeck(controlDeck); + context->InitResourceManager(archiveFiles, {}, 3); + context->InitConsole(); + + auto window = std::make_shared(std::vector>({ + std::make_shared("gInputEditorWindow", "Input Editor"), + std::make_shared("gGfxDebuggerEnabled", "Gfx Debugger"), + })); + context->InitWindow(window); + context->InitEventSystem(); + +#if (_DEBUG) + auto defaultLogLevel = spdlog::level::debug; +#else + auto defaultLogLevel = spdlog::level::info; +#endif + auto logLevel = + static_cast(CVarGetInteger(CVAR_DEVELOPER_TOOLS("LogLevel"), defaultLogLevel)); + context->InitLogging(logLevel, logLevel); + Ship::Context::GetInstance()->GetLogger()->set_pattern("[%H:%M:%S.%e] [%s:%#] [%l] %v"); + SPDLOG_INFO("Starting Starship version {} (Branch: {} | Commit: {})", (char*)gBuildVersion, (char*)gGitBranch, + (char*)gGitCommitHash); - this->context->InitResourceManager(archiveFiles, {}, 3); // without this line InitWindow fails in Gui::Init() - this->context->InitConsole(); // without this line the GuiWindow constructor fails in ConsoleWindow::InitElement() + context->InitFileDropMgr(); + context->InitCrashHandler(); - auto window = std::make_shared(std::vector>({})); +#ifndef __SWITCH__ + constexpr int codeVersion = 1; + std::unordered_map defines = { + { "VERSION_US", "1" }, + { "ENABLE_RUMBLE", "1" }, + { "F3DEX_GBI", "1" }, + { "_LANGUAGE_C", "1" }, + { "_USE_MATH_DEFINES", "1" }, + { "NON_MATCHING", "1" }, + { "NON_EQUIVALENT", "1" }, + { "AVOID_UB", "1" } + }; - auto audioChannelsSetting = Ship::Context::GetInstance()->GetConfig()->GetCurrentAudioChannelsSetting(); - this->context->Init(archiveFiles, {}, 3, { 32000, 1024, 1680, audioChannelsSetting }, window, controlDeck); +#ifdef _WIN32 + const std::string tccBase = Ship::Context::GetAppBundlePath() + "/.tcc"; + std::vector includePaths = { + tccBase + "/include", + tccBase + "/include/tcc", + tccBase + "/include/winapi", + tccBase + "/include/sys", + tccBase + "/include/sec_api", + }; + std::vector libraryPaths = { tccBase + "/lib" }; + context->InitScriptLoader(defines, codeVersion, "-g -rdynamic", includePaths, libraryPaths, { "Starship" }); +#else + std::vector includePaths = { + Ship::Context::GetPathRelativeToAppDirectory(".tcc/include"), + }; -#ifndef __SWITCH__ - Ship::Context::GetInstance()->GetLogger()->set_level( - (spdlog::level::level_enum) CVarGetInteger("gDeveloperTools.LogLevel", 1)); - Ship::Context::GetInstance()->GetLogger()->set_pattern("[%H:%M:%S.%e] [%s:%#] [%l] %v"); +#ifdef __APPLE__ + { + FILE* fp = popen("xcrun --show-sdk-path 2>/dev/null", "r"); + if (fp) { + char buf[4096] = {}; + if (fgets(buf, sizeof(buf), fp)) { + std::string sdkPath(buf); + sdkPath.erase(sdkPath.find_last_not_of("\n\r \t") + 1); + if (!sdkPath.empty()) { + includePaths.push_back(sdkPath + "/usr/include"); + } + } + pclose(fp); + } + } +#endif + + std::vector libraryPaths = { + Ship::Context::GetPathRelativeToAppDirectory(".tcc/lib"), + }; + context->InitScriptLoader(defines, codeVersion, "-g -rdynamic", includePaths, libraryPaths, {}); +#endif + + context->GetResourceManager()->GetArchiveManager()->SetUntrustedArchiveHandler( + [](Ship::Archive& archive, Ship::KeystoreEntry& key) { + const auto info = archive.GetManifest(); + + std::string message = "An archive from an unknown author was detected.\n\n"; + message += "Mod Name: " + info.Name + "\n"; + message += "Author: " + info.Author + "\n\n"; + message += "Do you want to trust this author and load the mod?"; + + constexpr SDL_MessageBoxButtonData buttons[] = { + { SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, 1, "Yes" }, + { SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT, 0, "No" }, + }; + + const SDL_MessageBoxColorScheme colorScheme = { { + /* [SDL_MESSAGEBOX_COLOR_BACKGROUND] */ + { 35, 35, 35 }, // Dark Grey + /* [SDL_MESSAGEBOX_COLOR_TEXT] */ + { 240, 240, 240 }, // Off-White + /* [SDL_MESSAGEBOX_COLOR_BUTTON_BORDER] */ + { 255, 100, 100 }, // Warning Red/Orange + /* [SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND] */ + { 60, 60, 60 }, // Lighter Grey + /* [SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED] */ + { 200, 60, 60 } // Dark Red/Orange when hovered/selected + } }; + + const SDL_MessageBoxData messageboxdata = { SDL_MESSAGEBOX_WARNING, + nullptr, + "Security Warning: Untrusted Author", + message.c_str(), + SDL_arraysize(buttons), + buttons, + &colorScheme }; + + int buttonid; + if (SDL_ShowMessageBox(&messageboxdata, &buttonid) < 0) { + return false; + } + + return buttonid == 1; + }); #endif + context->InitAudio({ .SampleRate = 32000, .SampleLength = 1024, .DesiredBuffered = 1680 }); + auto loader = context->GetResourceManager()->GetResourceLoader(); loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Animation", static_cast(SF64::ResourceType::AnimData), 0); @@ -250,7 +383,10 @@ GameEngine::GameEngine() { loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, "Sample", static_cast(SF64::ResourceType::Sample), 1); - + + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, + "Sample", static_cast(SF64::ResourceType::Sample), 2); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_XML, "Sample", static_cast(SF64::ResourceType::Sample), 0); @@ -260,12 +396,21 @@ GameEngine::GameEngine() { loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_XML, "SoundFont", static_cast(SF64::ResourceType::SoundFont), 0); + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_BINARY, + "Sequence", static_cast(SF64::ResourceType::Sequence), 2); + + loader->RegisterResourceFactory(std::make_shared(), RESOURCE_FORMAT_XML, + "Sequence", static_cast(SF64::ResourceType::Sequence), 0); + prevAltAssets = CVarGetInteger("gEnhancements.Mods.AlternateAssets", 0); gEnableGammaBoost = CVarGetInteger("gGraphics.GammaMode", 0) == 0; context->GetResourceManager()->SetAltAssetsEnabled(prevAltAssets); } bool GameEngine::GenAssetFile(bool exitOnFail) { +#ifdef __SWITCH__ + return true; +#else auto extractor = new GameExtractor(); if (!extractor->SelectGameFromUI()) { @@ -290,6 +435,24 @@ bool GameEngine::GenAssetFile(bool exitOnFail) { ShowMessage(("Starship - Extraction - Found " + game.value()).c_str(), "The extraction process will now begin.\n\nThis may take a few minutes.", SDL_MESSAGEBOX_INFORMATION); return extractor->GenerateOTR(); +#endif +} + +void GameEngine::LoadScripts() { +#ifndef __SWITCH__ + auto scripting = Ship::Context::GetInstance()->GetScriptLoader(); + + try { + scripting->CompileAll(); + scripting->LoadAll(); + Notification::Emit({ .message = "Loaded all scripts", .remainingTime = 7.0f }); + } catch (std::exception& e) { + SPDLOG_ERROR("Failed to load scripts: {}", e.what()); + Notification::Emit({ .message = "Failed to load scripts, check log for details", + .messageColor = ImVec4(1.0f, 0.5f, 0.5f, 1.0f), + .remainingTime = 7.0f }); + } +#endif } void GameEngine::Create() { @@ -302,6 +465,8 @@ void GameEngine::Create() { osSetTime(0); #endif PortEnhancements_Init(); + LoadScripts(); + ShipInit::InitAll(); } void GameEngine::Destroy() { @@ -318,8 +483,8 @@ void GameEngine::Destroy() { void GameEngine::StartFrame() const { using Ship::KbScancode; - const int32_t dwScancode = this->context->GetWindow()->GetLastScancode(); - this->context->GetWindow()->SetLastScancode(-1); + const int32_t dwScancode = context->GetWindow()->GetLastScancode(); + context->GetWindow()->SetLastScancode(-1); switch (dwScancode) { case KbScancode::LUS_KB_TAB: { @@ -359,10 +524,14 @@ extern "C" int countermin = 0; extern "C" unsigned short samples_high = SAMPLES_HIGH; extern "C" unsigned short samples_low = SAMPLES_LOW; +#define AUDIO_FRAMES_PER_UPDATE (gVIsPerFrame > 0 ? gVIsPerFrame : 1) +#define MAX_AUDIO_FRAMES_PER_UPDATE 5 // Compile-time constant with max value of gVIsPerFrame + void GameEngine::HandleAudioThread() { -#ifdef PIPE_DEBUG - std::ofstream outfile("audio.bin", std::ios::binary | std::ios::app); -#endif + // Runtime PCM capture state — lives entirely on the audio thread. + std::ofstream recFile; + uint64_t recBytes = 0; + while (audio.running) { { std::unique_lock Lock(audio.mutex); @@ -374,11 +543,6 @@ void GameEngine::HandleAudioThread() { } } - // gVIsPerFrame = 2; - -#define AUDIO_FRAMES_PER_UPDATE (gVIsPerFrame > 0 ? gVIsPerFrame : 1) -#define MAX_AUDIO_FRAMES_PER_UPDATE 5 // Compile-time constant with max value of gVIsPerFrame - std::unique_lock Lock(audio.mutex); int samples_left = AudioPlayerBuffered(); u32 num_audio_samples = samples_left < AudioPlayerGetDesiredBuffered() ? (((samples_high))) : (((samples_low))); @@ -392,25 +556,92 @@ void GameEngine::HandleAudioThread() { const int32_t num_audio_channels = GetNumAudioChannels(); s16 audio_buffer[SAMPLES_HIGH * MAX_NUM_AUDIO_CHANNELS * MAX_AUDIO_FRAMES_PER_UPDATE] = { 0 }; - for (int i = 0; i < AUDIO_FRAMES_PER_UPDATE; i++) { - AudioThread_CreateNextAudioBuffer(audio_buffer + i * (num_audio_samples * num_audio_channels), - num_audio_samples); + + // ── Frame-step gate ─────────────────────────────────────────────────── + // When step mode is active, skip synthesis (buffer stays silent zeros). + // gAudioStepOnce fires one frame; gAudioStepN drains across frames. + // The main thread is never blocked. + bool doSynth = true; + if (SF64::gAudioStepMode.load(std::memory_order_acquire)) { + doSynth = false; + // Check single-step token + bool expected = true; + if (SF64::gAudioStepOnce.compare_exchange_strong( + expected, false, std::memory_order_acq_rel)) { + doSynth = true; + } + // Check N-step counter (decrement if positive) + if (!doSynth) { + int n = SF64::gAudioStepN.load(std::memory_order_acquire); + while (n > 0) { + if (SF64::gAudioStepN.compare_exchange_weak( + n, n - 1, std::memory_order_acq_rel)) { + doSynth = true; + break; + } + } + } + if (doSynth) + SF64::gAudioFrameCount.fetch_add(1, std::memory_order_relaxed); } -#ifdef PIPE_DEBUG - if (outfile.is_open()) { - outfile.write(reinterpret_cast(audio_buffer), - num_audio_samples * (sizeof(int16_t) * num_audio_channels * AUDIO_FRAMES_PER_UPDATE)); + // ───────────────────────────────────────────────────────────────────── + + if (doSynth) { + for (int i = 0; i < AUDIO_FRAMES_PER_UPDATE; i++) { + AudioThread_CreateNextAudioBuffer(audio_buffer + i * (num_audio_samples * num_audio_channels), + num_audio_samples); + } } -#endif + + // ── Runtime PCM capture ─────────────────────────────────────────────── + const size_t frameBytes = num_audio_samples * + (sizeof(int16_t) * num_audio_channels * AUDIO_FRAMES_PER_UPDATE); + + // Open file on first recording frame + if (SF64::gAudioRecording.load(std::memory_order_acquire) && !recFile.is_open()) { + std::string path; + { std::lock_guard lk(SF64::gAudioRecordMutex); path = SF64::gAudioRecordPath; } + recFile.open(path, std::ios::binary | std::ios::trunc); + recBytes = 0; + SF64::gAudioRecordBytes.store(0, std::memory_order_relaxed); + } + + // Write this frame if recording and not paused + if (recFile.is_open() && + SF64::gAudioRecording.load(std::memory_order_acquire) && + !SF64::gAudioRecordPaused.load(std::memory_order_acquire)) { + recFile.write(reinterpret_cast(audio_buffer), frameBytes); + recBytes += frameBytes; + SF64::gAudioRecordBytes.store(recBytes, std::memory_order_relaxed); + } + + // Save-and-stop: flush, close, clear flags + if (SF64::gAudioSaveAndStop.load(std::memory_order_acquire)) { + if (recFile.is_open()) { recFile.flush(); recFile.close(); } + recBytes = 0; + SF64::gAudioRecordBytes.store(0, std::memory_order_relaxed); + SF64::gAudioRecording.store(false, std::memory_order_release); + SF64::gAudioRecordPaused.store(false, std::memory_order_release); + SF64::gAudioSaveAndStop.store(false, std::memory_order_release); + } + + // Also close if recording was stopped without save + if (!SF64::gAudioRecording.load(std::memory_order_acquire) && recFile.is_open()) { + recFile.close(); + recBytes = 0; + SF64::gAudioRecordBytes.store(0, std::memory_order_relaxed); + } + // ───────────────────────────────────────────────────────────────────── + AudioPlayerPlayFrame((u8*) audio_buffer, num_audio_samples * (sizeof(int16_t) * num_audio_channels * AUDIO_FRAMES_PER_UPDATE)); - + audio.processing = false; audio.cv_from_thread.notify_one(); } -#ifdef PIPE_DEBUG - outfile.close(); -#endif + + // Ensure file is closed if thread exits while recording + if (recFile.is_open()) { recFile.flush(); recFile.close(); } } void GameEngine::StartAudioFrame() { @@ -447,7 +678,8 @@ void GameEngine::AudioExit() { audio.thread.join(); } -void GameEngine::RunCommands(Gfx* Commands, const std::vector>& mtx_replacements) { +void GameEngine::RunCommands(Gfx* Commands, const std::vector>& mtx_replacements, + const std::vector& interpolation_fracs) { auto wnd = std::dynamic_pointer_cast(Ship::Context::GetInstance()->GetWindow()); if (wnd == nullptr) { @@ -460,9 +692,14 @@ void GameEngine::RunCommands(Gfx* Commands, const std::vectorHandleEvents(); interpreter->mInterpolationIndex = 0; - - for (const auto& m : mtx_replacements) { - wnd->DrawAndRunGraphicsCommands(Commands, m); + interpreter->mInterpolationTotal = (int)mtx_replacements.size(); + + for (size_t i = 0; i < mtx_replacements.size(); i++) { + // Feed the texture-scroll interpolation the exact same fraction the matrix + // interpolation uses for this sub-frame, so UVs stay in lockstep with vertices. + interpreter->mInterpolationFrac = + i < interpolation_fracs.size() ? interpolation_fracs[i] : (float)(i + 1) / (float)mtx_replacements.size(); + wnd->DrawAndRunGraphicsCommands(Commands, mtx_replacements[i], {}); interpreter->mInterpolationIndex++; } @@ -474,6 +711,43 @@ void GameEngine::RunCommands(Gfx* Commands, const std::vectorGetWindow()->GetWindowBackend()) { + case Fast::WindowBackend::FAST3D_SDL_VULKAN: + return "vulkan"; + case Fast::WindowBackend::FAST3D_SDL_OPENGL: + return "opengl"; + case Fast::WindowBackend::FAST3D_SDL_METAL: + return "metal"; + case Fast::WindowBackend::FAST3D_DXGI_DX11: + return "directx"; + default: + return nullptr; + } +} + +void UpdatePostPasses(Fast::Interpreter* interp) { + static bool sRegistered = false; + static int sSrgbPassId = -1; + + if (!sRegistered) { + const char* dir = PostPassBackendDir(); + if (dir == nullptr) { + return; // backend not initialized yet; retry next frame + } + const std::string base = std::string("shaders/") + dir + "/"; + sSrgbPassId = gfx_register_post_pass((base + "srgb.shader").c_str()); + sRegistered = true; + } + + if (interp == nullptr) { + return; + } + if (sSrgbPassId >= 0) { + interp->SetPostPassEnabled(sSrgbPassId, gEnableGammaBoost); + } +} + void GameEngine::ProcessGfxCommands(Gfx* commands) { auto wnd = std::dynamic_pointer_cast(Ship::Context::GetInstance()->GetWindow()); @@ -481,12 +755,12 @@ void GameEngine::ProcessGfxCommands(Gfx* commands) { return; } - if(gEnableGammaBoost) { - wnd->EnableSRGBMode(); - } + UpdatePostPasses(wnd->GetInterpreterWeak().lock().get()); + wnd->SetRendererUCode(UcodeHandlers::ucode_f3dex); std::vector> mtx_replacements; + std::vector interpolation_fracs; int target_fps = GameEngine::Instance->GetInterpolationFPS(); static int last_fps; static int last_update_rate; @@ -508,9 +782,12 @@ void GameEngine::ProcessGfxCommands(Gfx* commands) { while (time + original_fps <= next_original_frame) { time += original_fps; if (time != next_original_frame) { - mtx_replacements.push_back(FrameInterpolation_Interpolate((float) time / next_original_frame)); + float frac = (float) time / next_original_frame; + mtx_replacements.push_back(FrameInterpolation_Interpolate(frac)); + interpolation_fracs.push_back(frac); } else { mtx_replacements.emplace_back(); + interpolation_fracs.push_back(1.0f); } } @@ -525,9 +802,11 @@ void GameEngine::ProcessGfxCommands(Gfx* commands) { if (GfxDebuggerIsDebugging()) { mtx_replacements.clear(); mtx_replacements.emplace_back(); + interpolation_fracs.clear(); + interpolation_fracs.push_back(1.0f); } - RunCommands(commands, mtx_replacements); + RunCommands(commands, mtx_replacements, interpolation_fracs); last_fps = fps; last_update_rate = gVIsPerFrame; diff --git a/src/port/Engine.h b/src/port/Engine.h index b937e9db0..aa00113a8 100644 --- a/src/port/Engine.h +++ b/src/port/Engine.h @@ -11,10 +11,13 @@ typedef enum { } SF64Version; #ifdef __cplusplus +#pragma push_macro("this") +#undef this #include -#include -#include -#include "libultraship/src/Context.h" +#include +#include +#include +#pragma pop_macro("this") #ifndef IDYES #define IDYES 6 @@ -32,13 +35,15 @@ class GameEngine { GameEngine(); void StartFrame() const; static bool GenAssetFile(bool exitOnFail = true); + static void LoadScripts(); static void Create(); static void HandleAudioThread(); static void StartAudioFrame(); static void EndAudioFrame(); static void AudioInit(); static void AudioExit(); - static void RunCommands(Gfx* Commands, const std::vector>& mtx_replacements); + static void RunCommands(Gfx* Commands, const std::vector>& mtx_replacements, + const std::vector& interpolation_fracs = {}); static void Destroy(); static uint32_t GetInterpolationFPS(); static uint32_t GetInterpolationFrameCount(); @@ -85,6 +90,7 @@ uint32_t OTRGetGameRenderHeight(); void* GameEngine_Malloc(size_t size); void GameEngine_GetTextureInfo(const char* path, int32_t* width, int32_t* height, float* scale, bool* custom); void gDPSetTileSizeInterp(Gfx* pkt, int t, float uls, float ult, float lrs, float lrt); +void gDPSetTileScrollInterp(Gfx* pkt, int t, float uls, float ult, float lrs, float lrt, float delta_uls, float delta_ult); uint32_t GameEngine_GetInterpolationFrameCount(); #ifdef __cplusplus diff --git a/src/port/GBIMiddleware.cpp b/src/port/GBIMiddleware.cpp index 152d0203a..97fce1ec3 100644 --- a/src/port/GBIMiddleware.cpp +++ b/src/port/GBIMiddleware.cpp @@ -1,7 +1,8 @@ #include #include "Engine.h" -#include "DisplayList.h" +#include +#include extern "C" void gSPDisplayList(Gfx* pkt, Gfx* dl) { char* imgData = (char*)dl; @@ -10,15 +11,21 @@ extern "C" void gSPDisplayList(Gfx* pkt, Gfx* dl) { auto resource = Ship::Context::GetInstance()->GetResourceManager()->LoadResource(imgData); auto res = std::static_pointer_cast(resource); dl = &res->Instructions[0]; - // dl->words.trace.file = imgData; - // dl->words.trace.idx = 0; - // dl->words.trace.valid = true; +#ifdef USE_GBI_TRACE + // printf("DisplayList: %s\n", imgData); + for (int i = 0; i < res->Instructions.size(); i++) { + auto gfx = &res->Instructions[i]; + gfx->words.trace.file = imgData; + gfx->words.trace.idx = i; + gfx->words.trace.valid = 0xB00B; + } +#endif } __gSPDisplayList(pkt, dl); } -extern "C" void gDPSetTileSizeInterp(Gfx* pkt, int t, float uls, float ult, float lrs, float lrt) +extern "C" void gDPSetTileSizeInterp(Gfx* pkt, int t, float uls, float ult, float lrs, float lrt) { __gDPSetTileSizeInterp(pkt++, t, 0, 0, 0, 0); memcpy(&pkt[0].words.w0, &uls, sizeof(float)); @@ -27,10 +34,25 @@ extern "C" void gDPSetTileSizeInterp(Gfx* pkt, int t, float uls, float ult, floa memcpy(&pkt[1].words.w1, &lrt, sizeof(float)); } +// Single-command GPU-side tile scroll interpolation. +// Writes 4 Gfx words; caller must advance gMasterDisp by 4. +// The interpreter computes per-sub-frame UV offset from (uls,ult) and (delta_uls,delta_ult). +extern "C" void gDPSetTileScrollInterp(Gfx* pkt, int t, float uls, float ult, float lrs, float lrt, float delta_uls, float delta_ult) +{ + pkt[0].words.w0 = (uint32_t)(G_SETTILESCROLL_INTERP) << 24; + pkt[0].words.w1 = (uint32_t)(t & 0x7) << 24; + memcpy(&pkt[1].words.w0, &uls, sizeof(float)); + memcpy(&pkt[1].words.w1, &ult, sizeof(float)); + memcpy(&pkt[2].words.w0, &lrs, sizeof(float)); + memcpy(&pkt[2].words.w1, &lrt, sizeof(float)); + memcpy(&pkt[3].words.w0, &delta_uls, sizeof(float)); + memcpy(&pkt[3].words.w1, &delta_ult, sizeof(float)); +} + extern "C" void gSPVertex(Gfx* pkt, uintptr_t v, int n, int v0) { if (GameEngine_OTRSigCheck((char*)v) == 1) { - v = (uintptr_t) ResourceGetDataByName((char *) v); + v = (uintptr_t)ResourceGetDataByName((char*)v); } __gSPVertex(pkt, v, n, v0); @@ -39,14 +61,14 @@ extern "C" void gSPVertex(Gfx* pkt, uintptr_t v, int n, int v0) { extern "C" void gSPInvalidateTexCache(Gfx* pkt, uintptr_t texAddr) { char* imgData = (char*)texAddr; - if (texAddr != 0 && GameEngine_OTRSigCheck(imgData) == 1) { + if (texAddr != 0 && GameEngine_OTRSigCheck(imgData)) { auto res = Ship::Context::GetInstance()->GetResourceManager()->LoadResource(imgData); - if (res->GetInitData()->Type == (uint32_t) Fast::ResourceType::DisplayList) - texAddr = (uintptr_t)&((std::static_pointer_cast(res))->Instructions[0]); + if (res->GetInitData()->Type == (uint32_t)Fast::ResourceType::DisplayList) + texAddr = (uintptr_t) & ((std::static_pointer_cast(res))->Instructions[0]); else { - texAddr = (uintptr_t) res->GetRawPointer(); + texAddr = (uintptr_t)res->GetRawPointer(); } } - __gSPInvalidateTexCache(pkt, texAddr); + __gSPInvalidateTexCache(pkt, texAddr); } \ No newline at end of file diff --git a/src/port/Game.cpp b/src/port/Game.cpp index ef7894bed..e287f32cf 100644 --- a/src/port/Game.cpp +++ b/src/port/Game.cpp @@ -1,6 +1,6 @@ #include -#include +#include #include "Engine.h" extern "C" { diff --git a/src/port/ShipInit.h b/src/port/ShipInit.h new file mode 100644 index 000000000..232a4f2b9 --- /dev/null +++ b/src/port/ShipInit.h @@ -0,0 +1,44 @@ +#ifndef SHIP_INIT_HPP +#define SHIP_INIT_HPP + +#ifdef __cplusplus + +#include +#include +#include +#include +#include + +struct ShipInit { + static std::unordered_map>>& GetAll() { + static std::unordered_map>> shipInitFuncs; + return shipInitFuncs; + } + + static void InitAll() { + ShipInit::Init("*"); + } + + static void Init(const std::string& path) { + auto& shipInitFuncs = ShipInit::GetAll(); + for (const auto& initFunc : shipInitFuncs[path]) { + initFunc(); + } + } +}; + +struct RegisterShipInitFunc { + RegisterShipInitFunc(std::function initFunc, const std::set& updatePaths = {}) { + auto& shipInitFuncs = ShipInit::GetAll(); + + shipInitFuncs["*"].push_back(initFunc); + + for (const auto& path : updatePaths) { + shipInitFuncs[path].push_back(initFunc); + } + } +}; + +#endif // __cplusplus + +#endif // SHIP_INIT_HPP \ No newline at end of file diff --git a/src/port/api/UIWidgets_Bridge.cpp b/src/port/api/UIWidgets_Bridge.cpp new file mode 100644 index 000000000..f9461c347 --- /dev/null +++ b/src/port/api/UIWidgets_Bridge.cpp @@ -0,0 +1,448 @@ +#include "UIWidgets_Bridge.h" +#include "port/ui/UIWidgets.h" + +#include + +/* ========================================================================= + * Helpers: convert flat C color/enum fields to C++ types + * ====================================================================== */ + +static inline ImVec4 MakeColor(float r, float g, float b, float a) { + return ImVec4(r, g, b, a); +} + +static inline UIWidgets::LabelPosition ToLabelPosition(int v) { + switch (v) { + case UIWIDGETS_LABEL_FAR: + return UIWidgets::LabelPosition::Far; + case UIWIDGETS_LABEL_ABOVE: + return UIWidgets::LabelPosition::Above; + case UIWIDGETS_LABEL_NONE: + return UIWidgets::LabelPosition::None; + case UIWIDGETS_LABEL_WITHIN: + return UIWidgets::LabelPosition::Within; + default: + return UIWidgets::LabelPosition::Near; + } +} + +static inline UIWidgets::ComponentAlignment ToAlignment(int v) { + return (v == UIWIDGETS_ALIGN_RIGHT) ? UIWidgets::ComponentAlignment::Right : UIWidgets::ComponentAlignment::Left; +} + +static inline UIWidgets::CheckboxGraphics ToCheckboxGraphics(int v) { + switch (v) { + case UIWIDGETS_CHECKBOX_CHECKMARK: + return UIWidgets::CheckboxGraphics::Checkmark; + case UIWIDGETS_CHECKBOX_NONE: + return UIWidgets::CheckboxGraphics::None; + default: + return UIWidgets::CheckboxGraphics::Cross; + } +} + +/* Convert C options structs to C++ options structs */ + +static UIWidgets::ButtonOptions ToButtonOptions(const UIWidgets_ButtonOptions* opts) { + if (!opts) + return {}; + return { + .color = MakeColor(opts->color_r, opts->color_g, opts->color_b, opts->color_a), + .size = ImVec2(opts->size_x, opts->size_y), + .tooltip = opts->tooltip ? opts->tooltip : "", + .disabled = (bool) opts->disabled, + .disabledTooltip = opts->disabledTooltip ? opts->disabledTooltip : "", + }; +} + +static UIWidgets::CheckboxOptions ToCheckboxOptions(const UIWidgets_CheckboxOptions* opts) { + if (!opts) + return {}; + return { + .color = MakeColor(opts->color_r, opts->color_g, opts->color_b, opts->color_a), + .tooltip = opts->tooltip ? opts->tooltip : "", + .disabled = (bool) opts->disabled, + .disabledTooltip = opts->disabledTooltip ? opts->disabledTooltip : "", + .defaultValue = (bool) opts->defaultValue, + .alignment = ToAlignment(opts->alignment), + .labelPosition = ToLabelPosition(opts->labelPosition), + }; +} + +static UIWidgets::ComboboxOptions ToComboboxOptions(const UIWidgets_ComboboxOptions* opts) { + if (!opts) + return {}; + return { + .color = MakeColor(opts->color_r, opts->color_g, opts->color_b, opts->color_a), + .tooltip = opts->tooltip ? opts->tooltip : "", + .disabled = (bool) opts->disabled, + .disabledTooltip = opts->disabledTooltip ? opts->disabledTooltip : "", + .defaultIndex = opts->defaultIndex, + .alignment = ToAlignment(opts->alignment), + .labelPosition = ToLabelPosition(opts->labelPosition), + .flags = (ImGuiComboFlags) opts->flags, + }; +} + +static UIWidgets::IntSliderOptions ToIntSliderOptions(const UIWidgets_IntSliderOptions* opts) { + if (!opts) + return {}; + return { + .color = MakeColor(opts->color_r, opts->color_g, opts->color_b, opts->color_a), + .tooltip = opts->tooltip ? opts->tooltip : "", + .disabled = (bool) opts->disabled, + .disabledTooltip = opts->disabledTooltip ? opts->disabledTooltip : "", + .showButtons = (bool) opts->showButtons, + .flags = (ImGuiSliderFlags) opts->flags, + .format = opts->format ? opts->format : "%d", + .step = opts->step, + .alignment = ToAlignment(opts->alignment), + .labelPosition = ToLabelPosition(opts->labelPosition), + }; +} + +static UIWidgets::FloatSliderOptions ToFloatSliderOptions(const UIWidgets_FloatSliderOptions* opts) { + if (!opts) + return {}; + return { + .color = MakeColor(opts->color_r, opts->color_g, opts->color_b, opts->color_a), + .tooltip = opts->tooltip ? opts->tooltip : "", + .disabled = (bool) opts->disabled, + .disabledTooltip = opts->disabledTooltip ? opts->disabledTooltip : "", + .showButtons = (bool) opts->showButtons, + .flags = (ImGuiSliderFlags) opts->flags, + .format = opts->format ? opts->format : "%f", + .step = opts->step, + .isPercentage = (bool) opts->isPercentage, + .alignment = ToAlignment(opts->alignment), + .labelPosition = ToLabelPosition(opts->labelPosition), + }; +} + +/* ========================================================================= + * extern "C" implementations + * ====================================================================== */ + +extern "C" { + +/* ------------------------------------------------------------------------- + * Default option initializers + * ---------------------------------------------------------------------- */ + +UIWidgets_ButtonOptions UIWidgets_DefaultButtonOptions(void) { + UIWidgets::ButtonOptions cpp = {}; + UIWidgets_ButtonOptions c = {}; + c.color_r = cpp.color.x; + c.color_g = cpp.color.y; + c.color_b = cpp.color.z; + c.color_a = cpp.color.w; + c.size_x = cpp.size.x; + c.size_y = cpp.size.y; + c.tooltip = cpp.tooltip; + c.disabled = (int) cpp.disabled; + c.disabledTooltip = cpp.disabledTooltip; + return c; +} + +UIWidgets_CheckboxOptions UIWidgets_DefaultCheckboxOptions(void) { + UIWidgets::CheckboxOptions cpp = {}; + UIWidgets_CheckboxOptions c = {}; + c.color_r = cpp.color.x; + c.color_g = cpp.color.y; + c.color_b = cpp.color.z; + c.color_a = cpp.color.w; + c.tooltip = cpp.tooltip; + c.disabled = (int) cpp.disabled; + c.disabledTooltip = cpp.disabledTooltip; + c.defaultValue = (int) cpp.defaultValue; + c.alignment = (int) cpp.alignment; + c.labelPosition = (int) cpp.labelPosition; + return c; +} + +UIWidgets_ComboboxOptions UIWidgets_DefaultComboboxOptions(void) { + UIWidgets::ComboboxOptions cpp = {}; + UIWidgets_ComboboxOptions c = {}; + c.color_r = cpp.color.x; + c.color_g = cpp.color.y; + c.color_b = cpp.color.z; + c.color_a = cpp.color.w; + c.tooltip = cpp.tooltip; + c.disabled = (int) cpp.disabled; + c.disabledTooltip = cpp.disabledTooltip; + c.defaultIndex = cpp.defaultIndex; + c.alignment = (int) cpp.alignment; + c.labelPosition = (int) cpp.labelPosition; + c.flags = (int) cpp.flags; + return c; +} + +UIWidgets_IntSliderOptions UIWidgets_DefaultIntSliderOptions(void) { + UIWidgets::IntSliderOptions cpp = {}; + UIWidgets_IntSliderOptions c = {}; + c.color_r = cpp.color.x; + c.color_g = cpp.color.y; + c.color_b = cpp.color.z; + c.color_a = cpp.color.w; + c.tooltip = cpp.tooltip; + c.disabled = (int) cpp.disabled; + c.disabledTooltip = cpp.disabledTooltip; + c.showButtons = (int) cpp.showButtons; + c.flags = (int) cpp.flags; + c.format = cpp.format; + c.step = cpp.step; + c.alignment = (int) cpp.alignment; + c.labelPosition = (int) cpp.labelPosition; + return c; +} + +UIWidgets_FloatSliderOptions UIWidgets_DefaultFloatSliderOptions(void) { + UIWidgets::FloatSliderOptions cpp = {}; + UIWidgets_FloatSliderOptions c = {}; + c.color_r = cpp.color.x; + c.color_g = cpp.color.y; + c.color_b = cpp.color.z; + c.color_a = cpp.color.w; + c.tooltip = cpp.tooltip; + c.disabled = (int) cpp.disabled; + c.disabledTooltip = cpp.disabledTooltip; + c.showButtons = (int) cpp.showButtons; + c.flags = (int) cpp.flags; + c.format = cpp.format; + c.step = cpp.step; + c.isPercentage = (int) cpp.isPercentage; + c.alignment = (int) cpp.alignment; + c.labelPosition = (int) cpp.labelPosition; + return c; +} + +/* ------------------------------------------------------------------------- + * Layout helpers + * ---------------------------------------------------------------------- */ + +char* UIWidgets_WrappedText(const char* text, unsigned int charactersPerLine) { + return UIWidgets::WrappedText(text, charactersPerLine); +} + +void UIWidgets_SetLastItemHoverText(const char* text) { + UIWidgets::SetLastItemHoverText(text); +} + +void UIWidgets_InsertHelpHoverText(const char* text) { + UIWidgets::InsertHelpHoverText(text); +} + +void UIWidgets_Tooltip(const char* text) { + UIWidgets::Tooltip(text); +} + +void UIWidgets_Spacer(float height) { + UIWidgets::Spacer(height); +} + +void UIWidgets_PaddedSeparator(int padTop, int padBottom, float extraTop, float extraBottom) { + UIWidgets::PaddedSeparator((bool) padTop, (bool) padBottom, extraTop, extraBottom); +} + +void UIWidgets_DisableComponent(float alpha) { + UIWidgets::DisableComponent(alpha); +} + +void UIWidgets_ReEnableComponent(const char* disabledTooltipText) { + UIWidgets::ReEnableComponent(disabledTooltipText); +} + +/* ------------------------------------------------------------------------- + * Menu / MenuBar + * ---------------------------------------------------------------------- */ + +void UIWidgets_PushStyleMenu(float r, float g, float b, float a) { + UIWidgets::PushStyleMenu(MakeColor(r, g, b, a)); +} + +void UIWidgets_PopStyleMenu(void) { + UIWidgets::PopStyleMenu(); +} + +int UIWidgets_BeginMenu(const char* label, float r, float g, float b, float a) { + return (int) UIWidgets::BeginMenu(label, MakeColor(r, g, b, a)); +} + +void UIWidgets_PushStyleMenuItem(float r, float g, float b, float a) { + UIWidgets::PushStyleMenuItem(MakeColor(r, g, b, a)); +} + +void UIWidgets_PopStyleMenuItem(void) { + UIWidgets::PopStyleMenuItem(); +} + +int UIWidgets_MenuItem(const char* label, const char* shortcut, float r, float g, float b, float a) { + return (int) UIWidgets::MenuItem(label, shortcut, MakeColor(r, g, b, a)); +} + +/* ------------------------------------------------------------------------- + * Button + * ---------------------------------------------------------------------- */ + +void UIWidgets_PushStyleButton(float r, float g, float b, float a) { + UIWidgets::PushStyleButton(MakeColor(r, g, b, a)); +} + +void UIWidgets_PopStyleButton(void) { + UIWidgets::PopStyleButton(); +} + +int UIWidgets_Button(const char* label, const UIWidgets_ButtonOptions* options) { + return (int) UIWidgets::Button(label, ToButtonOptions(options)); +} + +/* ------------------------------------------------------------------------- + * Checkbox + * ---------------------------------------------------------------------- */ + +void UIWidgets_PushStyleCheckbox(float r, float g, float b, float a) { + UIWidgets::PushStyleCheckbox(MakeColor(r, g, b, a)); +} + +void UIWidgets_PopStyleCheckbox(void) { + UIWidgets::PopStyleCheckbox(); +} + +int UIWidgets_Checkbox(const char* label, int* value, const UIWidgets_CheckboxOptions* options) { + bool bValue = (bool) *value; + bool changed = UIWidgets::Checkbox(label, &bValue, ToCheckboxOptions(options)); + *value = (int) bValue; + return (int) changed; +} + +int UIWidgets_CVarCheckbox(const char* label, const char* cvarName, const UIWidgets_CheckboxOptions* options) { + return (int) UIWidgets::CVarCheckbox(label, cvarName, ToCheckboxOptions(options)); +} + +/* ------------------------------------------------------------------------- + * Combobox + * ---------------------------------------------------------------------- */ + +void UIWidgets_PushStyleCombobox(float r, float g, float b, float a) { + UIWidgets::PushStyleCombobox(MakeColor(r, g, b, a)); +} + +void UIWidgets_PopStyleCombobox(void) { + UIWidgets::PopStyleCombobox(); +} + +int UIWidgets_Combobox(const char* label, uint8_t* value, const char** comboArray, int count, + const UIWidgets_ComboboxOptions* options) { + std::span span(comboArray, (size_t) count); + return (int) UIWidgets::Combobox(label, value, span, ToComboboxOptions(options)); +} + +int UIWidgets_CVarCombobox(const char* label, const char* cvarName, const char** comboArray, int count, + const UIWidgets_ComboboxOptions* options) { + std::span span(comboArray, (size_t) count); + return (int) UIWidgets::CVarCombobox(label, cvarName, span, ToComboboxOptions(options)); +} + +/* ------------------------------------------------------------------------- + * Integer slider + * ---------------------------------------------------------------------- */ + +void UIWidgets_PushStyleSlider(float r, float g, float b, float a) { + UIWidgets::PushStyleSlider(MakeColor(r, g, b, a)); +} + +void UIWidgets_PopStyleSlider(void) { + UIWidgets::PopStyleSlider(); +} + +int UIWidgets_SliderInt(const char* label, int32_t* value, int32_t min, int32_t max, + const UIWidgets_IntSliderOptions* options) { + return (int) UIWidgets::SliderInt(label, value, min, max, ToIntSliderOptions(options)); +} + +int UIWidgets_CVarSliderInt(const char* label, const char* cvarName, int32_t min, int32_t max, int32_t defaultValue, + const UIWidgets_IntSliderOptions* options) { + return (int) UIWidgets::CVarSliderInt(label, cvarName, min, max, defaultValue, ToIntSliderOptions(options)); +} + +/* ------------------------------------------------------------------------- + * Float slider + * ---------------------------------------------------------------------- */ + +int UIWidgets_SliderFloat(const char* label, float* value, float min, float max, + const UIWidgets_FloatSliderOptions* options) { + return (int) UIWidgets::SliderFloat(label, value, min, max, ToFloatSliderOptions(options)); +} + +int UIWidgets_CVarSliderFloat(const char* label, const char* cvarName, float min, float max, float defaultValue, + const UIWidgets_FloatSliderOptions* options) { + return (int) UIWidgets::CVarSliderFloat(label, cvarName, min, max, defaultValue, ToFloatSliderOptions(options)); +} + +/* ------------------------------------------------------------------------- + * Legacy / V1 wrappers + * ---------------------------------------------------------------------- */ + +int UIWidgets_EnhancementCheckbox(const char* text, const char* cvarName, int disabled, const char* disabledTooltipText, + int disabledGraphic, int defaultValue) { + return (int) UIWidgets::EnhancementCheckbox(text, cvarName, (bool) disabled, + disabledTooltipText ? disabledTooltipText : "", + ToCheckboxGraphics(disabledGraphic), (bool) defaultValue); +} + +int UIWidgets_PaddedEnhancementCheckbox(const char* text, const char* cvarName, int padTop, int padBottom, int disabled, + const char* disabledTooltipText, int disabledGraphic, int defaultValue) { + return (int) UIWidgets::PaddedEnhancementCheckbox(text, cvarName, (bool) padTop, (bool) padBottom, (bool) disabled, + disabledTooltipText ? disabledTooltipText : "", + ToCheckboxGraphics(disabledGraphic), (bool) defaultValue); +} + +int UIWidgets_EnhancementCombobox(const char* cvarName, const char** comboArray, int count, uint8_t defaultIndex, + int disabled, const char* disabledTooltipText, uint8_t disabledValue) { + std::span span(comboArray, (size_t) count); + return (int) UIWidgets::EnhancementCombobox(cvarName, span, defaultIndex, (bool) disabled, + disabledTooltipText ? disabledTooltipText : "", disabledValue); +} + +void UIWidgets_PaddedText(const char* text, int padTop, int padBottom) { + UIWidgets::PaddedText(text, (bool) padTop, (bool) padBottom); +} + +int UIWidgets_EnhancementSliderInt(const char* text, const char* id, const char* cvarName, int min, int max, + const char* format, int defaultValue, int plusMinusButton, int disabled, + const char* disabledTooltipText) { + return (int) UIWidgets::EnhancementSliderInt(text, id, cvarName, min, max, format ? format : "%d", defaultValue, + (bool) plusMinusButton, (bool) disabled, + disabledTooltipText ? disabledTooltipText : ""); +} + +int UIWidgets_PaddedEnhancementSliderInt(const char* text, const char* id, const char* cvarName, int min, int max, + const char* format, int defaultValue, int plusMinusButton, int padTop, + int padBottom, int disabled, const char* disabledTooltipText) { + return (int) UIWidgets::PaddedEnhancementSliderInt( + text, id, cvarName, min, max, format ? format : "%d", defaultValue, (bool) plusMinusButton, (bool) padTop, + (bool) padBottom, (bool) disabled, disabledTooltipText ? disabledTooltipText : ""); +} + +int UIWidgets_EnhancementSliderFloat(const char* text, const char* id, const char* cvarName, float min, float max, + const char* format, float defaultValue, int isPercentage, int plusMinusButton, + int disabled, const char* disabledTooltipText) { + return (int) UIWidgets::EnhancementSliderFloat(text, id, cvarName, min, max, format ? format : "%f", defaultValue, + (bool) isPercentage, (bool) plusMinusButton, (bool) disabled, + disabledTooltipText ? disabledTooltipText : ""); +} + +int UIWidgets_PaddedEnhancementSliderFloat(const char* text, const char* id, const char* cvarName, float min, float max, + const char* format, float defaultValue, int isPercentage, + int plusMinusButton, int padTop, int padBottom, int disabled, + const char* disabledTooltipText) { + return (int) UIWidgets::PaddedEnhancementSliderFloat( + text, id, cvarName, min, max, format ? format : "%f", defaultValue, (bool) isPercentage, (bool) plusMinusButton, + (bool) padTop, (bool) padBottom, (bool) disabled, disabledTooltipText ? disabledTooltipText : ""); +} + +int UIWidgets_EnhancementRadioButton(const char* text, const char* cvarName, int id) { + return (int) UIWidgets::EnhancementRadioButton(text, cvarName, id); +} + +} // extern "C" diff --git a/src/port/api/UIWidgets_Bridge.h b/src/port/api/UIWidgets_Bridge.h new file mode 100644 index 000000000..1c0293925 --- /dev/null +++ b/src/port/api/UIWidgets_Bridge.h @@ -0,0 +1,319 @@ +#pragma once + +/** + * UIWidgets_Bridge.h + * + * C bridge for the UIWidgets C++ namespace. + * All functions are callable from C translation units. + * + * Naming convention: UIWidgets_ + * + * C-compatible replacements for C++ types: + * - bool -> int (0 = false, non-zero = true) + * - ImVec4 (color) -> four floats (r, g, b, a) + * - std::span -> const char** + int count + * - enum class -> int + */ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------------------------------------------------------------- + * Enumerations (mirrors UIWidgets enums as plain int constants) + * ---------------------------------------------------------------------- */ + +/* UIWidgets::CheckboxGraphics */ +#define UIWIDGETS_CHECKBOX_CROSS 0 +#define UIWIDGETS_CHECKBOX_CHECKMARK 1 +#define UIWIDGETS_CHECKBOX_NONE 2 + +/* UIWidgets::LabelPosition */ +#define UIWIDGETS_LABEL_NEAR 0 +#define UIWIDGETS_LABEL_FAR 1 +#define UIWIDGETS_LABEL_ABOVE 2 +#define UIWIDGETS_LABEL_NONE 3 +#define UIWIDGETS_LABEL_WITHIN 4 + +/* UIWidgets::ComponentAlignment */ +#define UIWIDGETS_ALIGN_LEFT 0 +#define UIWIDGETS_ALIGN_RIGHT 1 + +/* ------------------------------------------------------------------------- + * Options structs + * All color fields are RGBA floats in [0,1]. + * ---------------------------------------------------------------------- */ + +typedef struct { + float color_r, color_g, color_b, color_a; /**< Button color (default: Gray) */ + float size_x, size_y; /**< Button size (0,0 = inline, -1,0 = fill) */ + const char* tooltip; + int disabled; + const char* disabledTooltip; +} UIWidgets_ButtonOptions; + +typedef struct { + float color_r, color_g, color_b, color_a; /**< Checkbox accent color (default: Indigo) */ + const char* tooltip; + int disabled; + const char* disabledTooltip; + int defaultValue; /**< Only used by CVarCheckbox */ + int alignment; /**< UIWidgets_ComponentAlignment */ + int labelPosition; /**< UIWidgets_LabelPosition */ +} UIWidgets_CheckboxOptions; + +typedef struct { + float color_r, color_g, color_b, color_a; /**< Combobox accent color (default: Indigo) */ + const char* tooltip; + int disabled; + const char* disabledTooltip; + uint32_t defaultIndex; /**< Only used by CVarCombobox */ + int alignment; /**< UIWidgets_ComponentAlignment */ + int labelPosition; /**< UIWidgets_LabelPosition */ + int flags; /**< ImGuiComboFlags */ +} UIWidgets_ComboboxOptions; + +typedef struct { + float color_r, color_g, color_b, color_a; /**< Slider color (default: Gray) */ + const char* tooltip; + int disabled; + const char* disabledTooltip; + int showButtons; + int flags; /**< ImGuiSliderFlags */ + const char* format; /**< printf format, e.g. "%d" */ + uint32_t step; + int alignment; /**< UIWidgets_ComponentAlignment */ + int labelPosition; /**< UIWidgets_LabelPosition */ +} UIWidgets_IntSliderOptions; + +typedef struct { + float color_r, color_g, color_b, color_a; /**< Slider color (default: Gray) */ + const char* tooltip; + int disabled; + const char* disabledTooltip; + int showButtons; + int flags; /**< ImGuiSliderFlags */ + const char* format; /**< printf format, e.g. "%f" */ + float step; + int isPercentage; /**< Multiply displayed value by 100 */ + int alignment; /**< UIWidgets_ComponentAlignment */ + int labelPosition; /**< UIWidgets_LabelPosition */ +} UIWidgets_FloatSliderOptions; + +/* ------------------------------------------------------------------------- + * Default option initializers + * ---------------------------------------------------------------------- */ + +/** Returns a UIWidgets_ButtonOptions pre-filled with the C++ defaults. */ +UIWidgets_ButtonOptions UIWidgets_DefaultButtonOptions(void); + +/** Returns a UIWidgets_CheckboxOptions pre-filled with the C++ defaults. */ +UIWidgets_CheckboxOptions UIWidgets_DefaultCheckboxOptions(void); + +/** Returns a UIWidgets_ComboboxOptions pre-filled with the C++ defaults. */ +UIWidgets_ComboboxOptions UIWidgets_DefaultComboboxOptions(void); + +/** Returns a UIWidgets_IntSliderOptions pre-filled with the C++ defaults. */ +UIWidgets_IntSliderOptions UIWidgets_DefaultIntSliderOptions(void); + +/** Returns a UIWidgets_FloatSliderOptions pre-filled with the C++ defaults. */ +UIWidgets_FloatSliderOptions UIWidgets_DefaultFloatSliderOptions(void); + +/* ------------------------------------------------------------------------- + * Layout helpers + * ---------------------------------------------------------------------- */ + +/** + * Returns a heap-allocated string with automatic line-wrapping inserted. + * Caller is responsible for freeing the returned pointer with free(). + */ +char* UIWidgets_WrappedText(const char* text, unsigned int charactersPerLine); + +void UIWidgets_SetLastItemHoverText(const char* text); +void UIWidgets_InsertHelpHoverText(const char* text); +void UIWidgets_Tooltip(const char* text); +void UIWidgets_Spacer(float height); + +/** + * Renders a separator with optional vertical padding above and below. + * + * @param padTop Non-zero to add space above the separator. + * @param padBottom Non-zero to add space below the separator. + * @param extraTop Extra top padding in pixels. + * @param extraBottom Extra bottom padding in pixels. + */ +void UIWidgets_PaddedSeparator(int padTop, int padBottom, float extraTop, float extraBottom); + +void UIWidgets_DisableComponent(float alpha); +void UIWidgets_ReEnableComponent(const char* disabledTooltipText); + +/* ------------------------------------------------------------------------- + * Menu / MenuBar + * ---------------------------------------------------------------------- */ + +/** Push/pop menu style independently (color as RGBA floats). */ +void UIWidgets_PushStyleMenu(float r, float g, float b, float a); +void UIWidgets_PopStyleMenu(void); + +/** + * Begin a styled ImGui menu. + * @return Non-zero if the menu is open and items should be rendered. + */ +int UIWidgets_BeginMenu(const char* label, float r, float g, float b, float a); + +void UIWidgets_PushStyleMenuItem(float r, float g, float b, float a); +void UIWidgets_PopStyleMenuItem(void); + +/** + * Render a styled menu item. + * @return Non-zero if the item was activated. + */ +int UIWidgets_MenuItem(const char* label, const char* shortcut, float r, float g, float b, float a); + +/* ------------------------------------------------------------------------- + * Button + * ---------------------------------------------------------------------- */ + +void UIWidgets_PushStyleButton(float r, float g, float b, float a); +void UIWidgets_PopStyleButton(void); + +/** + * Render a styled button. + * @param options Pointer to options struct, or NULL to use defaults. + * @return Non-zero if clicked. + */ +int UIWidgets_Button(const char* label, const UIWidgets_ButtonOptions* options); + +/* ------------------------------------------------------------------------- + * Checkbox + * ---------------------------------------------------------------------- */ + +void UIWidgets_PushStyleCheckbox(float r, float g, float b, float a); +void UIWidgets_PopStyleCheckbox(void); + +/** + * Render a styled checkbox backed by a raw bool pointer. + * @param options Pointer to options struct, or NULL to use defaults. + * @return Non-zero if the value changed. + */ +int UIWidgets_Checkbox(const char* label, int* value, const UIWidgets_CheckboxOptions* options); + +/** + * Render a CVar-bound checkbox. Reads/writes the named CVar automatically. + * @param options Pointer to options struct, or NULL to use defaults. + * @return Non-zero if the CVar changed. + */ +int UIWidgets_CVarCheckbox(const char* label, const char* cvarName, const UIWidgets_CheckboxOptions* options); + +/* ------------------------------------------------------------------------- + * Combobox + * ---------------------------------------------------------------------- */ + +void UIWidgets_PushStyleCombobox(float r, float g, float b, float a); +void UIWidgets_PopStyleCombobox(void); + +/** + * Render a styled combobox backed by a raw uint8 pointer. + * @param comboArray Array of string pointers. + * @param count Number of entries in comboArray. + * @param options Pointer to options struct, or NULL to use defaults. + * @return Non-zero if the value changed. + */ +int UIWidgets_Combobox(const char* label, uint8_t* value, const char** comboArray, int count, + const UIWidgets_ComboboxOptions* options); + +/** + * Render a CVar-bound combobox. + * @param comboArray Array of string pointers. + * @param count Number of entries in comboArray. + * @param options Pointer to options struct, or NULL to use defaults. + * @return Non-zero if the CVar changed. + */ +int UIWidgets_CVarCombobox(const char* label, const char* cvarName, const char** comboArray, int count, + const UIWidgets_ComboboxOptions* options); + +/* ------------------------------------------------------------------------- + * Integer slider + * ---------------------------------------------------------------------- */ + +void UIWidgets_PushStyleSlider(float r, float g, float b, float a); +void UIWidgets_PopStyleSlider(void); + +/** + * Render a styled integer slider backed by a raw int32 pointer. + * @param options Pointer to options struct, or NULL to use defaults. + * @return Non-zero if the value changed. + */ +int UIWidgets_SliderInt(const char* label, int32_t* value, int32_t min, int32_t max, + const UIWidgets_IntSliderOptions* options); + +/** + * Render a CVar-bound integer slider. + * @param options Pointer to options struct, or NULL to use defaults. + * @return Non-zero if the CVar changed. + */ +int UIWidgets_CVarSliderInt(const char* label, const char* cvarName, int32_t min, int32_t max, int32_t defaultValue, + const UIWidgets_IntSliderOptions* options); + +/* ------------------------------------------------------------------------- + * Float slider + * ---------------------------------------------------------------------- */ + +/** + * Render a styled float slider backed by a raw float pointer. + * @param options Pointer to options struct, or NULL to use defaults. + * @return Non-zero if the value changed. + */ +int UIWidgets_SliderFloat(const char* label, float* value, float min, float max, + const UIWidgets_FloatSliderOptions* options); + +/** + * Render a CVar-bound float slider. + * @param options Pointer to options struct, or NULL to use defaults. + * @return Non-zero if the CVar changed. + */ +int UIWidgets_CVarSliderFloat(const char* label, const char* cvarName, float min, float max, float defaultValue, + const UIWidgets_FloatSliderOptions* options); + +/* ------------------------------------------------------------------------- + * Legacy / V1 wrappers + * ---------------------------------------------------------------------- */ + +int UIWidgets_EnhancementCheckbox(const char* text, const char* cvarName, int disabled, const char* disabledTooltipText, + int disabledGraphic, int defaultValue); + +int UIWidgets_PaddedEnhancementCheckbox(const char* text, const char* cvarName, int padTop, int padBottom, int disabled, + const char* disabledTooltipText, int disabledGraphic, int defaultValue); + +/** + * @param comboArray NULL-terminated array of strings (no count needed). + */ +int UIWidgets_EnhancementCombobox(const char* cvarName, const char** comboArray, int count, uint8_t defaultIndex, + int disabled, const char* disabledTooltipText, uint8_t disabledValue); + +void UIWidgets_PaddedText(const char* text, int padTop, int padBottom); + +int UIWidgets_EnhancementSliderInt(const char* text, const char* id, const char* cvarName, int min, int max, + const char* format, int defaultValue, int plusMinusButton, int disabled, + const char* disabledTooltipText); + +int UIWidgets_PaddedEnhancementSliderInt(const char* text, const char* id, const char* cvarName, int min, int max, + const char* format, int defaultValue, int plusMinusButton, int padTop, + int padBottom, int disabled, const char* disabledTooltipText); + +int UIWidgets_EnhancementSliderFloat(const char* text, const char* id, const char* cvarName, float min, float max, + const char* format, float defaultValue, int isPercentage, int plusMinusButton, + int disabled, const char* disabledTooltipText); + +int UIWidgets_PaddedEnhancementSliderFloat(const char* text, const char* id, const char* cvarName, float min, float max, + const char* format, float defaultValue, int isPercentage, + int plusMinusButton, int padTop, int padBottom, int disabled, + const char* disabledTooltipText); + +int UIWidgets_EnhancementRadioButton(const char* text, const char* cvarName, int id); + +#ifdef __cplusplus +} +#endif diff --git a/src/port/audio/AudioDebug.cpp b/src/port/audio/AudioDebug.cpp new file mode 100644 index 000000000..3494e2d31 --- /dev/null +++ b/src/port/audio/AudioDebug.cpp @@ -0,0 +1,90 @@ +#include "AudioDebug.h" + +namespace SF64 { + +std::unordered_map gSamplePathMap; +std::mutex gSamplePathMapMutex; + +std::unordered_map gSeqPathMap; +std::mutex gSeqPathMapMutex; + +AudioDebugSnapshot gSnapshot; +std::mutex gSnapshotMutex; +std::atomic gSnapshotReady{ false }; + +// All channels unmuted by default. +std::atomic gMutedChannels[kNumSeqChannels] = {}; + +// Frame-step controls — all inactive by default. +std::atomic gAudioStepMode{ false }; +std::atomic gAudioStepOnce{ false }; +std::atomic gAudioStepN{ 0 }; +std::atomic gAudioFrameCount{ 0 }; + +// Capture / record controls. +std::atomic gAudioRecording{ false }; +std::atomic gAudioRecordPaused{ false }; +std::atomic gAudioSaveAndStop{ false }; +std::atomic gAudioRecordBytes{ 0 }; +std::string gAudioRecordPath; +std::mutex gAudioRecordMutex; + +void AudioDebug_RegisterSample(SampleData* sample, const std::string& path) { + if (sample == nullptr) return; + std::lock_guard lk(gSamplePathMapMutex); + gSamplePathMap[sample] = path; +} + +void AudioDebug_RegisterSequence(uint8_t seqNumber, const std::string& path) { + std::lock_guard lk(gSeqPathMapMutex); + gSeqPathMap[seqNumber] = path; +} + +const std::string& AudioDebug_GetSeqPath(uint8_t seqNumber) { + static const std::string sEmpty; + std::lock_guard lk(gSeqPathMapMutex); + auto it = gSeqPathMap.find(seqNumber); + return (it != gSeqPathMap.end()) ? it->second : sEmpty; +} + +const std::string& AudioDebug_GetSamplePath(SampleData* sample) { + static const std::string sEmpty; + if (sample == nullptr) return sEmpty; + std::lock_guard lk(gSamplePathMapMutex); + auto it = gSamplePathMap.find(sample); + return (it != gSamplePathMap.end()) ? it->second : sEmpty; +} + +AudioDebugSnapshot AudioDebug_GetSnapshot() { + std::lock_guard lk(gSnapshotMutex); + return gSnapshot; +} + +} // namespace SF64 + +extern "C" void AudioDebug_SetLastPlayed(void* sample, int samplePosInt, unsigned int endPos, + int loopStart, int loopEnd, unsigned int loopCount, + unsigned short resampleRate, int codec, + unsigned int sampleSize) { + SF64::AudioDebugSnapshot snap; + snap.sample = reinterpret_cast(sample); + snap.samplePos = samplePosInt; + snap.endPos = endPos; + snap.loopStart = loopStart; + snap.loopEnd = loopEnd; + snap.loopCount = loopCount; + snap.resampleRate = resampleRate; + snap.codec = codec; + snap.sampleSize = sampleSize; + + { + std::lock_guard lk(SF64::gSnapshotMutex); + SF64::gSnapshot = snap; + } + SF64::gSnapshotReady.store(true, std::memory_order_release); +} + +extern "C" int AudioDebug_IsChannelMuted(int channelIndex) { + if (channelIndex < 0 || channelIndex >= SF64::kNumSeqChannels) return 0; + return SF64::gMutedChannels[channelIndex].load(std::memory_order_relaxed) ? 1 : 0; +} diff --git a/src/port/audio/AudioDebug.h b/src/port/audio/AudioDebug.h new file mode 100644 index 000000000..1d096b81a --- /dev/null +++ b/src/port/audio/AudioDebug.h @@ -0,0 +1,102 @@ +#pragma once + +// ── C-visible section ──────────────────────────────────────────────────────── +// AudioDebug_SetLastPlayed is called from audio_synthesis.c (pure C). +// Takes void* to avoid conflicting with the C-side "Sample" typedef. +#ifdef __cplusplus +extern "C" { +#endif + +// Called from audio_synthesis.c each time a non-synthetic note is processed. +// Captures a full snapshot of the sample + synthesis state for display. +void AudioDebug_SetLastPlayed(void* sample, int samplePosInt, unsigned int endPos, + int loopStart, int loopEnd, unsigned int loopCount, + unsigned short resampleRate, int codec, unsigned int sampleSize); + +// Called from audio_seqplayer.c inside the channel processing loop. +// Returns 1 if the channel should be skipped (muted), 0 if it should run. +int AudioDebug_IsChannelMuted(int channelIndex); + +#ifdef __cplusplus +} + +// ── C++-only section ───────────────────────────────────────────────────────── +#include +#include +#include +#include +#include +#include "port/resource/type/audio/Sample.h" + +namespace SF64 { + +// Snapshot of one note's playback state, written by the audio thread. +struct AudioDebugSnapshot { + SampleData* sample = nullptr; + int samplePos = 0; // samplePosInt at time of call + uint32_t endPos = 0; // loopInfo->end + uint32_t loopStart = 0; // loopInfo->start + uint32_t loopEnd = 0; // loopInfo->end (alias, same as endPos) + uint32_t loopCount = 0; // loopInfo->count (0=no loop, 0xFFFFFFFF=infinite) + uint16_t resampleRate = 0; // noteSub->resampleRate (fixed-point) + int codec = 0; // bookSample->codec + uint32_t sampleSize = 0; // bookSample->size (bytes) +}; + +// Per-channel mute flags — written by the render/UI thread, read by the audio thread. +// Index matches seqPlayer->channels[i]. 16 channels per SEQ_NUM_CHANNELS. +static constexpr int kNumSeqChannels = 16; +extern std::atomic gMutedChannels[kNumSeqChannels]; + +// ── Audio frame-step controls ───────────────────────────────────────────────── +// gAudioStepMode: when true the audio thread outputs silence each frame instead +// of running synthesis. Game loop is never blocked. +// gAudioStepOnce: set by UI; consumed by the audio thread to run synthesis for +// exactly one frame, then return to silence. +// gAudioStepN: set by UI to N; audio thread decrements and runs synthesis +// until it reaches zero, then returns to silence. +// gAudioFrameCount: incremented each time a synthesis frame is actually run. +extern std::atomic gAudioStepMode; +extern std::atomic gAudioStepOnce; +extern std::atomic gAudioStepN; +extern std::atomic gAudioFrameCount; + +// ── Audio capture / record controls ────────────────────────────────────────── +// gAudioRecording: true while the audio thread should append PCM to the file. +// gAudioRecordPaused: true to temporarily stop writing without closing the file. +// gAudioSaveAndStop: set to true by the UI to flush and close the current file. +// gAudioRecordPath: desired output path (set before starting; read by audio thread). +// gAudioRecordBytes: running byte count written so far (for display). +extern std::atomic gAudioRecording; +extern std::atomic gAudioRecordPaused; +extern std::atomic gAudioSaveAndStop; +extern std::atomic gAudioRecordBytes; +extern std::string gAudioRecordPath; // written by UI thread before start +extern std::mutex gAudioRecordMutex; // protects gAudioRecordPath + +// Populated at sample-factory load time. +extern std::unordered_map gSamplePathMap; +extern std::mutex gSamplePathMapMutex; + +// Populated at sequence-factory load time: seqNumber → archive path. +extern std::unordered_map gSeqPathMap; +extern std::mutex gSeqPathMapMutex; + +// Written lock-free by the audio thread; read by the render thread. +// Access via AudioDebug_GetSnapshot() for a consistent copy. +extern std::atomic gSnapshotReady; +extern AudioDebugSnapshot gSnapshot; // written by audio thread +extern std::mutex gSnapshotMutex; + +void AudioDebug_RegisterSample(SampleData* sample, const std::string& path); +const std::string& AudioDebug_GetSamplePath(SampleData* sample); + +void AudioDebug_RegisterSequence(uint8_t seqNumber, const std::string& path); +const std::string& AudioDebug_GetSeqPath(uint8_t seqNumber); + +// Returns a safe copy of the latest snapshot for the render thread. +AudioDebugSnapshot AudioDebug_GetSnapshot(); + +} // namespace SF64 + +#endif // __cplusplus diff --git a/src/port/build.c.in b/src/port/build.c.in new file mode 100644 index 000000000..afd8f0b60 --- /dev/null +++ b/src/port/build.c.in @@ -0,0 +1,15 @@ +#include + +// Lighthouse Version information +const char gBuildVersion[] = "@PROJECT_BUILD_NAME@ (@CMAKE_PROJECT_VERSION_MAJOR@.@CMAKE_PROJECT_VERSION_MINOR@.@CMAKE_PROJECT_VERSION_PATCH@)"; +const u16 gBuildVersionMajor = @CMAKE_PROJECT_VERSION_MAJOR@; +const u16 gBuildVersionMinor = @CMAKE_PROJECT_VERSION_MINOR@; +const u16 gBuildVersionPatch = @CMAKE_PROJECT_VERSION_PATCH@; + +const char gGitBranch[] = "@CMAKE_PROJECT_GIT_BRANCH@"; +const char gGitCommitHash[] = "@CMAKE_PROJECT_GIT_COMMIT_HASH@"; +const char gGitCommitTag[] = "@CMAKE_PROJECT_GIT_COMMIT_TAG@"; + +const char gBuildTeam[] = "@PROJECT_TEAM@"; +const char gBuildDate[] = __DATE__ " " __TIME__; +const char gBuildMakeOption[] = ""; diff --git a/src/port/build.h b/src/port/build.h new file mode 100644 index 000000000..66833dcc3 --- /dev/null +++ b/src/port/build.h @@ -0,0 +1,20 @@ +#ifndef BUILD_H +#define BUILD_H + +#include +#include "macros.h" + +// Version information +extern_s char gBuildVersion[]; +extern_s u16 gBuildVersionMajor; +extern_s u16 gBuildVersionMinor; +extern_s u16 gBuildVersionPatch; + +extern_s char gGitBranch[]; +extern_s char gGitCommitHash[]; +extern_s char gGitCommitTag[]; +extern_s char gBuildTeam[]; +extern_s char gBuildDate[]; +extern_s char gBuildMakeOption[]; + +#endif diff --git a/src/port/extractor/GameExtractor.cpp b/src/port/extractor/GameExtractor.cpp index 9be7f4b7d..2ef16718b 100644 --- a/src/port/extractor/GameExtractor.cpp +++ b/src/port/extractor/GameExtractor.cpp @@ -1,8 +1,10 @@ #include "GameExtractor.h" +#ifndef __SWITCH__ + #include -#include "Context.h" +#include #include "spdlog/spdlog.h" #include #if !defined(__IOS__) && !defined(__ANDROID__) && !defined(__SWITCH__) @@ -68,3 +70,5 @@ bool GameExtractor::GenerateOTR() const { return true; } + +#endif // __SWITCH__ diff --git a/src/port/extractor/GameExtractor.h b/src/port/extractor/GameExtractor.h index a64234953..a20c5b369 100644 --- a/src/port/extractor/GameExtractor.h +++ b/src/port/extractor/GameExtractor.h @@ -1,5 +1,7 @@ #pragma once +#ifndef __SWITCH__ + #include "Companion.h" #include #include @@ -14,4 +16,6 @@ class GameExtractor { private: fs::path mGamePath; std::vector mGameData; -}; \ No newline at end of file +}; + +#endif // __SWITCH__ \ No newline at end of file diff --git a/src/port/hooks/Events.h b/src/port/hooks/Events.h index 3f53a7d17..9848ed950 100644 --- a/src/port/hooks/Events.h +++ b/src/port/hooks/Events.h @@ -1,6 +1,15 @@ #pragma once +#ifdef __cplusplus +#pragma push_macro("this") +#undef this +#endif + #include "list/EngineEvent.h" #include "list/ActorEvent.h" #include "list/ItemEvent.h" -#include "list/ActionEvent.h" \ No newline at end of file +#include "list/ActionEvent.h" + +#ifdef __cplusplus +#pragma pop_macro("this") +#endif \ No newline at end of file diff --git a/src/port/hooks/impl/EventSystem.cpp b/src/port/hooks/impl/EventSystem.cpp deleted file mode 100644 index 3418b6efb..000000000 --- a/src/port/hooks/impl/EventSystem.cpp +++ /dev/null @@ -1,62 +0,0 @@ -#include "EventSystem.h" -#include -#include - -EventSystem* EventSystem::Instance = new EventSystem(); - -EventID EventSystem::RegisterEvent() { - return this->mInternalEventID++; -} - -ListenerID EventSystem::RegisterListener(EventID id, EventCallback callback, EventPriority priority) { - if(id == -1) { - throw std::runtime_error("Trying to register listener for unregistered event"); - } - - auto& listeners = this->mEventListeners[id]; - - if(std::find_if(listeners.begin(), listeners.end(), [callback](EventListener listener) { - return listener.function == callback; - }) != listeners.end()) { - throw std::runtime_error("Listener already registered"); - } - - listeners.push_back({ priority, callback }); - - // Sort by priority - std::sort(listeners.begin(), listeners.end(), [](EventListener a, EventListener b) { - return a.priority < b.priority; - }); - - return listeners.size() - 1; -} - -void EventSystem::UnregisterListener(EventID id, ListenerID listenerId) { - auto& listeners = this->mEventListeners[id]; - - listeners.erase(listeners.begin() + listenerId); -} - -void EventSystem::CallEvent(EventID id, IEvent* event) { - auto& listeners = this->mEventListeners[id]; - - for (auto& listener : listeners) { - listener.function(event); - } -} - -extern "C" EventID EventSystem_RegisterEvent() { - return EventSystem::Instance->RegisterEvent(); -} - -extern "C" size_t EventSystem_RegisterListener(EventID id, EventCallback callback, EventPriority priority) { - return EventSystem::Instance->RegisterListener(id, callback, priority); -} - -extern "C" void EventSystem_UnregisterListener(EventID ev, size_t id) { - EventSystem::Instance->UnregisterListener(ev, id); -} - -extern "C" void EventSystem_CallEvent(EventID id, void* event) { - EventSystem::Instance->CallEvent(id, static_cast(event)); -} \ No newline at end of file diff --git a/src/port/hooks/impl/EventSystem.h b/src/port/hooks/impl/EventSystem.h deleted file mode 100644 index bd6a25695..000000000 --- a/src/port/hooks/impl/EventSystem.h +++ /dev/null @@ -1,89 +0,0 @@ -#pragma once - -#include -#include -#include - -typedef uint32_t EventID; -typedef uint32_t ListenerID; - -typedef enum { - EVENT_PRIORITY_LOW, - EVENT_PRIORITY_NORMAL, - EVENT_PRIORITY_HIGH, -} EventPriority; - -typedef struct { - bool cancelled; -} IEvent; - -typedef void (*EventCallback)(IEvent*); - -typedef struct { - EventPriority priority; - EventCallback function; -} EventListener; - -#ifdef INIT_EVENT_IDS -#define DECLARE_EVENT(eventName) \ - uint32_t eventName##ID = -1; -#else -#define DECLARE_EVENT(eventName) \ - extern uint32_t eventName##ID; -#endif - -#define DEFINE_EVENT(eventName, ...) \ - typedef struct { \ - IEvent event; \ - __VA_ARGS__ \ - } eventName; \ - \ - DECLARE_EVENT(eventName) - -#define CALL_EVENT(eventType, ...) \ - eventType eventType##_ = { {false}, __VA_ARGS__ }; \ - EventSystem_CallEvent(eventType##ID, &eventType##_); - -#define CALL_CANCELLABLE_EVENT(eventType, ...) \ - eventType eventType##_ = { {false}, __VA_ARGS__ }; \ - EventSystem_CallEvent(eventType##ID, &eventType##_); \ - if (!eventType##_.event.cancelled) - -#define CHECK_IF_NOT_CANCELLED(eventType) \ - if (!eventType##_.event.cancelled) - -#define CALL_CANCELLABLE_RETURN_EVENT(eventType, ...) \ - eventType eventType##_ = { {false}, __VA_ARGS__ }; \ - EventSystem_CallEvent(eventType##ID, &eventType##_); \ - if (eventType##_.event.cancelled) { \ - return; \ - } - -#define REGISTER_EVENT(eventType) \ - eventType##ID = EventSystem_RegisterEvent(); - -#define REGISTER_LISTENER(eventType, callback, priority) \ - EventSystem_RegisterListener(eventType##ID, callback, priority); - -#ifdef __cplusplus -#include -#include -#include - -class EventSystem { -public: - static EventSystem* Instance; - EventID RegisterEvent(); - ListenerID RegisterListener(EventID id, EventCallback callback, EventPriority priority = EVENT_PRIORITY_NORMAL); - void UnregisterListener(EventID ev, ListenerID id); - void CallEvent(EventID id, IEvent* event); -private: - std::unordered_map> mEventListeners; - EventID mInternalEventID = 0; -}; -#else -extern EventID EventSystem_RegisterEvent(); -extern ListenerID EventSystem_RegisterListener(EventID id, EventCallback callback, EventPriority priority); -extern void EventSystem_UnregisterListener(EventID ev, ListenerID id); -extern void EventSystem_CallEvent(EventID id, void* event); -#endif \ No newline at end of file diff --git a/src/port/hooks/list/ActionEvent.h b/src/port/hooks/list/ActionEvent.h index 57c49644d..a3d508374 100644 --- a/src/port/hooks/list/ActionEvent.h +++ b/src/port/hooks/list/ActionEvent.h @@ -1,17 +1,73 @@ #pragma once #include "sf64player.h" -#include "port/hooks/impl/EventSystem.h" -DEFINE_EVENT(PlayerActionBoostEvent, Player* player;); +// ──────────────────────────────────────────────────────────────────────────── +// Player action events — game thread +// All events in this file fire on the game thread during player input +// processing. Cancellable events block the corresponding default action when +// event->Event.Cancelled is set to true by a listener. +// ──────────────────────────────────────────────────────────────────────────── -DEFINE_EVENT(PlayerActionBrakeEvent, Player* player;); +// Fires when the player activates boost. Cancellable. +// Cancel to suppress the boost input (e.g. to implement a custom boost system +// or to disable boost in a specific game mode). +// player — the player who triggered the boost +DEFINE_EVENT(PlayerActionBoostEvent, + Player* player; +); -DEFINE_EVENT(PlayerActionPreShootEvent, Player* player; LaserStrength laser;); -DEFINE_EVENT(PlayerActionPostShootEvent, Player* player; PlayerShot* shot;); +// Fires when the player activates brake. Cancellable. +// Cancel to suppress the brake input. +// player — the player who triggered the brake +DEFINE_EVENT(PlayerActionBrakeEvent, + Player* player; +); -DEFINE_EVENT(PlayerActionPreShootChargedEvent, Player* player;); -DEFINE_EVENT(PlayerActionPostShootChargedEvent, Player* player;); +// Fires before a laser shot is created. Cancellable. +// Cancel to suppress the shot entirely (no ProjectileShot is spawned). +// Fires for both single and twin-laser modes. +// player — the player who is shooting +// laser — the laser strength / type being fired (LASER_SINGLE, LASER_TWIN, …) +DEFINE_EVENT(PlayerActionPreShootEvent, + Player* player; + LaserStrength laser; +); -DEFINE_EVENT(PlayerActionPreBombEvent, Player* player;); -DEFINE_EVENT(PlayerActionPostBombEvent, Player* player;); \ No newline at end of file +// Fires after a laser shot has been created and added to the shot pool. +// Not cancellable — the shot already exists at this point. +// player — the player who fired +// shot — pointer to the newly created PlayerShot in the shot pool +DEFINE_EVENT(PlayerActionPostShootEvent, + Player* player; + PlayerShot* shot; +); + +// Fires before a charged shot is released. Cancellable. +// Cancel to suppress the charged shot (charge energy is still consumed). +// player — the player releasing the charged shot +DEFINE_EVENT(PlayerActionPreShootChargedEvent, + Player* player; +); + +// Fires after a charged shot has been created and added to the shot pool. +// Not cancellable. +// player — the player who released the charged shot +DEFINE_EVENT(PlayerActionPostShootChargedEvent, + Player* player; +); + +// Fires before a bomb is deployed. Cancellable. +// Cancel to suppress the bomb launch (the bomb count is not decremented). +// Fires for Arwing, Landmaster, and Blue Marine bomb types. +// player — the player deploying the bomb +DEFINE_EVENT(PlayerActionPreBombEvent, + Player* player; +); + +// Fires after a bomb has been successfully deployed. +// Not cancellable — the bomb entity already exists at this point. +// player — the player who deployed the bomb +DEFINE_EVENT(PlayerActionPostBombEvent, + Player* player; +); diff --git a/src/port/hooks/list/ActorEvent.h b/src/port/hooks/list/ActorEvent.h index e93fefe68..d8ad627f5 100644 --- a/src/port/hooks/list/ActorEvent.h +++ b/src/port/hooks/list/ActorEvent.h @@ -2,40 +2,80 @@ #include "gfx.h" #include "sf64object.h" -#include "port/hooks/impl/EventSystem.h" + +// ──────────────────────────────────────────────────────────────────────────── +// Object type discriminator +// Passed as the `type` field on every object event so listeners can quickly +// filter for the entity category they care about without casting `object`. +// ──────────────────────────────────────────────────────────────────────────── typedef enum { - OBJECT_TYPE_ACTOR, - OBJECT_TYPE_ACTOR_EVENT, - OBJECT_TYPE_BOSS, - OBJECT_TYPE_SCENERY, - OBJECT_TYPE_SCENERY360, - OBJECT_TYPE_SPRITE, - OBJECT_TYPE_ITEM, - OBJECT_TYPE_EFFECT, + OBJECT_TYPE_ACTOR, // standard enemy / NPC actor (Actor*) + OBJECT_TYPE_ACTOR_EVENT, // scripted event actor (ActorEvent* / similar) + OBJECT_TYPE_BOSS, // boss entity (Boss*) + OBJECT_TYPE_SCENERY, // static scenery object (Scenery*) + OBJECT_TYPE_SCENERY360, // 360-mode scenery (Scenery360*) + OBJECT_TYPE_SPRITE, // billboard sprite (Sprite*) + OBJECT_TYPE_ITEM, // collectable item (Item*) + OBJECT_TYPE_EFFECT, // visual effect (Effect*) } ObjectEventType; +// ──────────────────────────────────────────────────────────────────────────── +// Object lifecycle events — game thread +// All events fire on the game thread inside the main entity update loop. +// `object` is always cast to void* to avoid forcing a dependency on every +// entity header; cast to the concrete type using `type` as the discriminator. +// Cancellable events block the corresponding default engine behaviour when +// event->Event.Cancelled is set to true by a listener. +// ──────────────────────────────────────────────────────────────────────────── + +// Fires when an object is initialised for the first time (spawned / allocated). +// Cancellable — cancel to suppress the default initialisation routine and take +// full control of the object's state from the listener. +// type — category of the object (use to select the correct cast) +// object — void* pointer to the entity; cast based on `type` DEFINE_EVENT(ObjectInitEvent, ObjectEventType type; - void* object; + void* object; ); +// Fires each game frame when an object's update function runs. +// Cancellable — cancel to suppress the default update logic for this frame, +// allowing a listener to fully replace or pause object behaviour. +// type — category of the object +// object — void* pointer to the entity; cast based on `type` DEFINE_EVENT(ObjectUpdateEvent, ObjectEventType type; - void* object; + void* object; ); +// Fires before an object's display-list setup (matrix push, material bind, etc.). +// Cancellable — cancel to suppress the default draw setup and draw call, +// allowing a listener to render a custom mesh or skip rendering entirely. +// type — category of the object +// object — void* pointer to the entity; cast based on `type` DEFINE_EVENT(ObjectDrawPreSetupEvent, ObjectEventType type; - void* object; + void* object; ); +// Fires immediately after an object's display-list setup has completed and +// the default draw call has been issued. Not cancellable — use this to append +// additional draw calls (overlays, outlines, debug shapes) to the same matrix +// context before it is popped. +// type — category of the object +// object — void* pointer to the entity; cast based on `type` DEFINE_EVENT(ObjectDrawPostSetupEvent, ObjectEventType type; - void* object; + void* object; ); +// Fires when an object is destroyed / removed from the active object pool. +// Cancellable — cancel to suppress the default destruction logic (e.g. to +// keep the object alive or to handle cleanup yourself). +// type — category of the object +// object — void* pointer to the entity; cast based on `type` DEFINE_EVENT(ObjectDestroyEvent, ObjectEventType type; - void* object; -); \ No newline at end of file + void* object; +); diff --git a/src/port/hooks/list/EngineEvent.h b/src/port/hooks/list/EngineEvent.h index df4115cd4..65c29aa3c 100644 --- a/src/port/hooks/list/EngineEvent.h +++ b/src/port/hooks/list/EngineEvent.h @@ -1,31 +1,283 @@ #pragma once #include "global.h" -#include "port/hooks/impl/EventSystem.h" +#include "sf64audio_provisional.h" +// ──────────────────────────────────────────────────────────────────────────── +// Display events — game thread +// ──────────────────────────────────────────────────────────────────────────── + +// Fires at the very start of the display update, before any game logic runs. DEFINE_EVENT(DisplayPreUpdateEvent); + +// Fires at the very end of the display update, after all game logic has run. DEFINE_EVENT(DisplayPostUpdateEvent); +// ──────────────────────────────────────────────────────────────────────────── +// Game loop events — game thread +// ──────────────────────────────────────────────────────────────────────────── + +// Fires at the start of the main game update tick. DEFINE_EVENT(GamePreUpdateEvent); + +// Fires at the end of the main game update tick. DEFINE_EVENT(GamePostUpdateEvent); +// Fires during the play-state update (active gameplay, not menus). DEFINE_EVENT(PlayUpdateEvent); -DEFINE_EVENT(PlayerPreUpdateEvent, Player* player;); -DEFINE_EVENT(PlayerPostUpdateEvent, Player* player;); +// ──────────────────────────────────────────────────────────────────────────── +// Player events — game thread +// ──────────────────────────────────────────────────────────────────────────── + +// Fires before the player entity is updated. +// player — the player being updated +DEFINE_EVENT(PlayerPreUpdateEvent, + Player* player; +); + +// Fires after the player entity is updated. +// player — the player that was updated +DEFINE_EVENT(PlayerPostUpdateEvent, + Player* player; +); +// ──────────────────────────────────────────────────────────────────────────── +// HUD / radar draw events — game thread +// ──────────────────────────────────────────────────────────────────────────── + +// Fires before the radar HUD element is drawn. Cancel to suppress default drawing. DEFINE_EVENT(DrawRadarHUDEvent); -DEFINE_EVENT(DrawRadarMarkArwingEvent, s32 colorIdx;); + +// Fires before an Arwing blip is drawn on the radar. +// colorIdx — palette index used for this blip +DEFINE_EVENT(DrawRadarMarkArwingEvent, + s32 colorIdx; +); + +// Fires before a Wolfen blip is drawn on the radar. Cancel to suppress. DEFINE_EVENT(DrawRadarMarkWolfenEvent); + +// Fires before the boost gauge is drawn. Cancel to suppress default drawing. DEFINE_EVENT(DrawBoostGaugeHUDEvent); + +// Fires before the bomb counter is drawn. Cancel to suppress default drawing. DEFINE_EVENT(DrawBombCounterHUDEvent); + +// Fires before the incoming-message indicator is drawn. Cancel to suppress. DEFINE_EVENT(DrawIncomingMsgHUDEvent); -DEFINE_EVENT(PreSetupRadioMsgEvent, s32* radioRedBox;); + +// Fires before the radio message box is set up. +// radioRedBox — pointer to the red-box flag; write to force a specific style +DEFINE_EVENT(PreSetupRadioMsgEvent, + s32* radioRedBox; +); + +// Fires before the gold rings counter is drawn. Cancel to suppress. DEFINE_EVENT(DrawGoldRingsHUDEvent); + +// Fires before the lives counter is drawn. Cancel to suppress. DEFINE_EVENT(DrawLivesCounterHUDEvent); + +// Fires before the training ring pass counter is drawn. Cancel to suppress. DEFINE_EVENT(DrawTrainingRingPassCountHUDEvent); + +// Fires before the edge-direction arrows are drawn. Cancel to suppress. DEFINE_EVENT(DrawEdgeArrowsHUDEvent); + +// Fires before the boss health bar is drawn. Cancel to suppress. DEFINE_EVENT(DrawBossHealthHUDEvent); +// Fires before the global HUD layer is drawn (outermost pre-draw hook). DEFINE_EVENT(DrawGlobalHUDPreEvent); -DEFINE_EVENT(DrawGlobalHUDPostEvent); \ No newline at end of file + +// Fires after the global HUD layer has been drawn (outermost post-draw hook). +DEFINE_EVENT(DrawGlobalHUDPostEvent); + +// ──────────────────────────────────────────────────────────────────────────── +// Engine UI events — render thread +// ──────────────────────────────────────────────────────────────────────────── + +// Fires when the engine renders its ImGui menubar. Add custom menu items here. +DEFINE_EVENT(EngineRenderMenubarEvent); + +// Fires when the engine renders the mods panel. Add custom ImGui widgets here. +DEFINE_EVENT(EngineRenderModsEvent); + +// ──────────────────────────────────────────────────────────────────────────── +// Audio — voice events +// These fire on the GAME THREAD (PlayVoiceEvent, ClearVoiceEvent) or the +// AUDIO THREAD (UpdateVoiceEvent, GetCurrentVoiceEvent, GetVoiceStatusEvent). +// Do not access non-thread-safe state from the wrong thread. +// ──────────────────────────────────────────────────────────────────────────── + +// Fires when a voice line is requested. GAME THREAD. +// The VoiceEnhancements mod listens here to load a replacement PCM sample. +// msgId — the voice message ID (matches ast_radio/gMsg_ID_XXXX resource names) +DEFINE_EVENT(PlayVoiceEvent, + s32 msgId; +); + +// Fires once per audio frame while a voice line is active. AUDIO THREAD. +// Set *finished = true to signal that custom playback has completed so the +// engine restores BGM volume and clears the voice state. +// finished — write true to mark the override as done +DEFINE_EVENT(UpdateVoiceEvent); + +// Fires when the engine queries the currently playing voice ID. AUDIO THREAD. +// Write the current msgId into *result to override the default channel-scan +// logic (used for mouth animation and BGM-restore gating). +// result — write the active msgId here, or leave at -1 for default behaviour +DEFINE_EVENT(GetCurrentVoiceEvent, + s32* result; +); + +// Fires when the engine queries the voice playback status for mouth animation. +// AUDIO THREAD. Write one of: 0 = silent, 1 = speaking, 2 = finished. +// result — write the desired mouth-animation state, or leave at -1 for default +DEFINE_EVENT(GetVoiceStatusEvent, + s32* result; +); + +// Fires when voice playback is cleared (e.g. on scene transition). GAME THREAD. +// Use to reset any per-voice override state. +DEFINE_EVENT(ClearVoiceEvent); + +// ──────────────────────────────────────────────────────────────────────────── +// Audio — sequence / BGM events — GAME THREAD +// Cancellable: set event->Event.Cancelled = true to block the operation. +// Mutable fields (pointers): write through them to change the value that the +// engine will use before the SEQCMD is dispatched. +// ──────────────────────────────────────────────────────────────────────────── + +// Fires inside Audio_PlaySequence before the SEQCMD is queued. Cancellable. +// Write *seqId to redirect playback to a different sequence. +// Cancel to suppress playback entirely (e.g. when substituting custom audio). +// seqPlayId — which sequence player (SEQ_PLAYER_BGM, SEQ_PLAYER_FANFARE, …) +// seqId — mutable pointer to the sequence ID; write to remap +// fadeinTime — fade-in duration in audio frames +// bgmParam — extra BGM parameter passed via SEQCMD_SET_SEQPLAYER_IO +DEFINE_EVENT(PlaySequenceEvent, + u8 seqPlayId; + u16* seqId; + u8 fadeinTime; + u8 bgmParam; +); + +// Fires inside Audio_PlayFanfare before the SEQCMD is queued. Cancellable. +// Write *seqId to redirect playback to a different fanfare sequence. +// seqId — mutable pointer to the fanfare sequence ID; write to remap +// bgmVolume — BGM volume level during fanfare playback +// bgmFadeoutTime — frames to fade the BGM out before the fanfare starts +// bgmFadeinTime — frames to restore BGM volume after the fanfare ends +DEFINE_EVENT(PlayFanfareEvent, + u16* seqId; + u8 bgmVolume; + u8 bgmFadeoutTime; + u8 bgmFadeinTime; +); + +// Fires inside Audio_StopSequence before the player is disabled. Cancellable. +// Cancel to keep the sequence running (e.g. when a custom music system owns +// the player and handles stopping itself). +// seqPlayId — which sequence player is being stopped +// fadeOutTime — fade-out duration in audio frames +DEFINE_EVENT(StopSequenceEvent, + u8 seqPlayId; + u16 fadeOutTime; +); + +// Fires inside Audio_SetSequenceFade before the fade values are committed. +// Cancellable. Modify *fadeMod or *fadeTime to alter the fade curve. +// seqPlayId — which sequence player is being faded +// fadeModId — which fade-mod slot is being written (0 = primary volume) +// fadeMod — mutable target volume level [0, 127] +// fadeTime — mutable fade duration in audio frames +DEFINE_EVENT(SetSequenceFadeEvent, + u8 seqPlayId; + u8 fadeModId; + u8* fadeMod; + u8* fadeTime; +); + +// ──────────────────────────────────────────────────────────────────────────── +// Audio — SFX event — GAME THREAD — Cancellable +// ──────────────────────────────────────────────────────────────────────────── + +// Fires inside Audio_PlaySfx before the request is enqueued. Cancellable. +// Write *sfxId to remap to a different sound effect. +// freqMod / volMod / reverbAdd are double-pointers: you may point them at your +// own variables to fully replace the modulator without copying values. +// Cancel to suppress the sound entirely. +// sfxId — mutable sound effect ID; write to remap +// sfxSource — 3-float world-space position of the sound source +// token — bank slot / token used for kill-by-source operations +// freqMod — pointer-to-pointer to the pitch multiplier (1.0 = normal) +// volMod — pointer-to-pointer to the volume multiplier (1.0 = full) +// reverbAdd — pointer-to-pointer to the reverb addend (signed byte) +DEFINE_EVENT(PlaySfxEvent, + u32* sfxId; + f32* sfxSource; + u8 token; + f32** freqMod; + f32** volMod; + s8** reverbAdd; +); + +// ──────────────────────────────────────────────────────────────────────────── +// Audio — volume / spec events — GAME THREAD +// ──────────────────────────────────────────────────────────────────────────── + +// Fires inside Audio_SetVolume after the [0, 99] clamp, before the value is +// stored. Cancellable. Write *volume to apply a different final value. +// audioType — AUDIO_TYPE_MUSIC, AUDIO_TYPE_SFX, or AUDIO_TYPE_VOICE +// volume — mutable volume in [0, 99] +DEFINE_EVENT(SetVolumeEvent, + u8 audioType; + u8* volume; +); + +// Fires inside Audio_SetAudioSpec before SEQCMD_RESET_AUDIO_HEAP is issued. +// Not cancellable — the spec change must proceed to keep audio in sync. +// Write *specId or *sfxChannelLayout to redirect the engine to a different +// audio spec (e.g. to load a custom instrument bank for a modded level). +// sfxChannelLayout — mutable SFX channel layout byte (high byte of specParam) +// specId — mutable audio spec ID (low byte of specParam) +DEFINE_EVENT(SetAudioSpecEvent, + u8* sfxChannelLayout; + u8* specId; +); + +// ──────────────────────────────────────────────────────────────────────────── +// Audio — per-frame tick — GAME THREAD +// ──────────────────────────────────────────────────────────────────────────── + +// Fires at the end of Audio_Update every frame, after SFX, sequences, voice, +// and the audio thread command queue have all been processed. +// Use for per-frame audio mod work that must run in lockstep with the game. +// Not cancellable. +DEFINE_EVENT(AudioUpdateEvent); + +// ──────────────────────────────────────────────────────────────────────────── +// Audio — note-level hooks — AUDIO THREAD +// These fire deep inside the sequence player on the audio thread. +// Do not call any game-thread APIs or take game-thread locks here. +// ──────────────────────────────────────────────────────────────────────────── + +// Fires just before a note is allocated for a sequence layer. +// Used by VoiceEnhancements to swap layer->tunedSample for a custom PCM buffer +// and to adjust layer->freqMod for sample-rate matching. +// layer — the sequence layer that is about to trigger a note +// channel — the channel that owns this layer +DEFINE_EVENT(SeqLayerPreNoteEvent, + SequenceLayer* layer; + SequenceChannel* channel; +); + +// Fires immediately after a note has been allocated for a sequence layer. +// Used by VoiceEnhancements to pin delay/gateDelay so the engine does not +// cut the custom sample short. +// layer — the layer whose note was just allocated +DEFINE_EVENT(SeqLayerPostNoteEvent, + SequenceLayer* layer; +); diff --git a/src/port/hooks/list/ItemEvent.h b/src/port/hooks/list/ItemEvent.h index f5296a34a..846918dbf 100644 --- a/src/port/hooks/list/ItemEvent.h +++ b/src/port/hooks/list/ItemEvent.h @@ -2,8 +2,19 @@ #include "gfx.h" #include "sf64object.h" -#include "port/hooks/impl/EventSystem.h" +// ──────────────────────────────────────────────────────────────────────────── +// Item events — game thread +// ──────────────────────────────────────────────────────────────────────────── + +// Fires when an item is about to be spawned as a world drop. +// Cancellable — cancel to suppress the spawn entirely (e.g. to replace the +// drop with a custom item, or to remove drops in a no-item game mode). +// Fires in multiple contexts: enemy death drops, scripted demo drops, and +// forced drops from the enemy manager. +// item — pointer to the Item struct that was just populated; the item has +// been configured (type, position, etc.) but not yet added to the +// active item list — modifying fields here takes effect immediately DEFINE_EVENT(ItemDropEvent, Item* item; -); \ No newline at end of file +); diff --git a/src/port/interpolation/FrameInterpolation.cpp b/src/port/interpolation/FrameInterpolation.cpp index 8d6c31ceb..f06cd339a 100644 --- a/src/port/interpolation/FrameInterpolation.cpp +++ b/src/port/interpolation/FrameInterpolation.cpp @@ -2,6 +2,8 @@ #include #include +#include +#include #include #include #include "port/Engine.h" @@ -42,6 +44,9 @@ given a specific interpolation factor (0=old frame, 0.5=average of frames, static bool invert_matrix(const float m[16], float invOut[16]); +extern "C" Matrix sInterpolationMatrixStack[0x1000]; +static constexpr size_t kInterpolationMatrixStackSize = 0x1000; + using namespace std; namespace { @@ -66,6 +71,9 @@ enum class Op { SkinMatrixMtxFToMtx }; +constexpr size_t kOpCount = (size_t)Op::SkinMatrixMtxFToMtx + 1; +constexpr int kMaxInterpolationDepth = 1024; + typedef pair label; union Data { @@ -154,19 +162,47 @@ union Data { }; struct Path { - map> children; - map> ops; + map> children; + array, kOpCount> ops; vector> items; + + void reset() { + items.clear(); + for (auto& v : ops) { + v.clear(); + } + children.clear(); + } +}; + +struct NodePool { + deque nodes; + size_t used = 0; + + Path* alloc() { + if (used == nodes.size()) { + nodes.emplace_back(); + } + Path* p = &nodes[used++]; + p->reset(); + return p; + } + + void rewind() { + used = 0; + } }; struct Recording { - Path root_path; + Path* root_path = nullptr; }; bool is_recording; vector current_path; uint32_t camera_epoch; uint32_t previous_camera_epoch; +NodePool node_pools[2]; +int current_pool = 0; Recording current_recording; Recording previous_recording; @@ -176,15 +212,11 @@ MtxF inv_actor_mtx; size_t inv_actor_mtx_path_index; Data& append(Op op) { - auto& m = current_path.back()->ops[op]; + auto& m = current_path.back()->ops[(size_t)op]; current_path.back()->items.emplace_back(op, m.size()); return m.emplace_back(); } -MtxF* Matrix_GetCurrent(){ - return (MtxF*) gInterpolationMatrix; -} - struct InterpolateCtx { float step; float w; @@ -264,9 +296,6 @@ struct InterpolateCtx { } res = (u16)(w * o + step * n); } - if (os / 327 == ns / 327 && (s16)res / 327 != os / 327) { - int bp = 0; - } return res; } @@ -282,25 +311,32 @@ struct InterpolateCtx { res->z = interpolate_angle(o->z, n->z); } - void interpolate_branch(Path* old_path, Path* new_path) { + void interpolate_branch(Path* old_path, Path* new_path, int depth = 0) { + if (depth > kMaxInterpolationDepth) { + return; + } for (auto& item : new_path->items) { - Data& new_op = new_path->ops[item.first][item.second]; + Data& new_op = new_path->ops[(size_t)item.first][item.second]; if (item.first == Op::OpenChild) { + auto new_it = new_path->children.find(new_op.open_child.key); + if (new_it == new_path->children.end() || new_op.open_child.idx >= new_it->second.size()) { + continue; + } + Path* new_child = new_it->second[new_op.open_child.idx]; + Path* old_child = new_child; if (auto it = old_path->children.find(new_op.open_child.key); it != old_path->children.end() && new_op.open_child.idx < it->second.size()) { - interpolate_branch(&it->second[new_op.open_child.idx], - &new_path->children.find(new_op.open_child.key)->second[new_op.open_child.idx]); - } else { - interpolate_branch(&new_path->children.find(new_op.open_child.key)->second[new_op.open_child.idx], - &new_path->children.find(new_op.open_child.key)->second[new_op.open_child.idx]); + old_child = it->second[new_op.open_child.idx]; } + interpolate_branch(old_child, new_child, depth + 1); continue; } - if (auto it = old_path->ops.find(item.first); it != old_path->ops.end()) { - if (item.second < it->second.size()) { - Data& old_op = it->second[item.second]; + { + auto& old_vec = old_path->ops[(size_t)item.first]; + if (item.second < old_vec.size()) { + Data& old_op = old_vec[item.second]; switch (item.first) { case Op::OpenChild: case Op::CloseChild: @@ -308,11 +344,15 @@ struct InterpolateCtx { break; case Op::MatrixPush: - Matrix_Push(&gInterpolationMatrix); + if (gInterpolationMatrix < &sInterpolationMatrixStack[kInterpolationMatrixStackSize - 1]) { + Matrix_Push(&gInterpolationMatrix); + } break; case Op::MatrixPop: - Matrix_Pop(&gInterpolationMatrix); + if (gInterpolationMatrix > &sInterpolationMatrixStack[0]) { + Matrix_Pop(&gInterpolationMatrix); + } break; // Unused on SF64 @@ -408,7 +448,11 @@ unordered_map FrameInterpolation_Interpolate(float step) { InterpolateCtx ctx; ctx.step = step; ctx.w = 1.0f - step; - ctx.interpolate_branch(&previous_recording.root_path, ¤t_recording.root_path); + if (previous_recording.root_path == nullptr || current_recording.root_path == nullptr) { + return ctx.mtx_replacements; + } + gInterpolationMatrix = &sInterpolationMatrixStack[0]; + ctx.interpolate_branch(previous_recording.root_path, current_recording.root_path); return ctx.mtx_replacements; } @@ -420,10 +464,12 @@ void FrameInterpolation_ShouldInterpolateFrame(bool shouldInterpolate) { } void FrameInterpolation_StartRecord(void) { - previous_recording = move(current_recording); - current_recording = {}; + previous_recording = current_recording; + current_pool ^= 1; + node_pools[current_pool].rewind(); + current_recording.root_path = node_pools[current_pool].alloc(); current_path.clear(); - current_path.push_back(¤t_recording.root_path); + current_path.push_back(current_recording.root_path); if (!camera_interpolation) { // default to interpolating camera_interpolation = true; @@ -446,7 +492,9 @@ void FrameInterpolation_RecordOpenChild(const void* a, int b) { label key = { a, b }; auto& m = current_path.back()->children[key]; append(Op::OpenChild).open_child = { key, m.size() }; - current_path.push_back(&m.emplace_back()); + Path* child = node_pools[current_pool].alloc(); + m.push_back(child); + current_path.push_back(child); } void FrameInterpolation_RecordCloseChild(void) { @@ -541,18 +589,6 @@ void FrameInterpolation_RecordMatrixMtxFToMtx(MtxF* src, Mtx* dest) { append(Op::MatrixMtxFToMtx).matrix_mtxf_to_mtx = { *src, dest }; } -void FrameInterpolation_RecordMatrixToMtx(Mtx* dest, char* file, s32 line) { - if (!is_recording) - return; - auto& d = append(Op::MatrixToMtx).matrix_to_mtx = { dest }; - if (has_inv_actor_mtx) { - d.has_adjusted = true; - Matrix_MtxFMtxFMult(&inv_actor_mtx, Matrix_GetCurrent(), &d.src); - } else { - d.src = *Matrix_GetCurrent(); - } -} - void FrameInterpolation_RecordMatrixRotateAxis(f32 angle, Vec3f* axis, u8 mode) { if (!is_recording) return; diff --git a/src/port/interpolation/FrameInterpolation.h b/src/port/interpolation/FrameInterpolation.h index 7ba8c62a3..86431914d 100644 --- a/src/port/interpolation/FrameInterpolation.h +++ b/src/port/interpolation/FrameInterpolation.h @@ -45,8 +45,6 @@ void FrameInterpolation_RecordMatrixRotate1Coord(Matrix* matrix, u32 coord, f32 void FrameInterpolation_RecordMatrixMtxFToMtx(MtxF* src, Mtx* dest); -void FrameInterpolation_RecordMatrixToMtx(Mtx* dest, char* file, s32 line); - void FrameInterpolation_RecordMatrixReplaceRotation(MtxF* mf); void FrameInterpolation_RecordMatrixRotateAxis(f32 angle, Vec3f* axis, u8 mode); diff --git a/src/port/mods/PortEnhancements.c b/src/port/mods/PortEnhancements.c index c74f07210..534320469 100644 --- a/src/port/mods/PortEnhancements.c +++ b/src/port/mods/PortEnhancements.c @@ -1,11 +1,12 @@ +#define INIT_EVENT_IDS + #include "PortEnhancements.h" #include "global.h" #include "hit64.h" #include "mods.h" #include "hud.h" #include "assets/ast_star_wolf.h" - -#define INIT_EVENT_IDS +#include "port/api/UIWidgets_Bridge.h" #include "port/hooks/Events.h" bool gBackToMap = false; @@ -181,7 +182,7 @@ void OnPlayUpdateEvent(IEvent* event) { CVarSetInteger("gDebugPause", 0); // Unpause if we disable the shortcut } - event->cancelled = CVarGetInteger("gDebugPause", 0); + event->Cancelled = CVarGetInteger("gDebugPause", 0); if (shouldRepause) { CVarSetInteger("gDebugPause", 1); } @@ -228,7 +229,7 @@ void OnItemGoldRingDraw(ObjectDrawPostSetupEvent* event) { return; } - event->event.cancelled = true; + event->Event.Cancelled = true; RCP_SetupDL(&gMasterDisp, SETUPDL_29_OPTIONAL); Graphics_SetScaleMtx(item->width * 2.0f); gSPDisplayList(gMasterDisp++, D_101D870); @@ -290,7 +291,7 @@ void OnBoostGaugeDraw(IEvent* event) { return; } - event->cancelled = true; + event->Cancelled = true; u8 step = MIN(8, (u8) ((gPlayer[0].boostMeter / 90.0f) * ARRAY_COUNT(sBoostGaugeArrow))); f32 x = 70; f32 y = 30; @@ -311,7 +312,7 @@ void OnBombCounterDraw(IEvent* ev) { return; } - ev->cancelled = true; + ev->Cancelled = true; HUD_BombCounter_Draw(253.0f, 18.0f); } @@ -337,7 +338,7 @@ void OnRadarMarkArwingDraw(DrawRadarMarkArwingEvent* ev) { return; } - ev->event.cancelled = true; + ev->Event.Cancelled = true; s32 arwingMarkColor[][4] = { { 177, 242, 12, 255 }, { 89, 121, 6, 128 }, { 90, 90, 255, 255 }, { 45, 45, 128, 128 }, @@ -373,7 +374,7 @@ void OnRadarMarkWolfenDraw(IEvent* ev) { if (!outlines) { return; } - ev->cancelled = true; + ev->Cancelled = true; RCP_SetupDL(&gMasterDisp, SETUPDL_62); gDPSetPrimColor(gMasterDisp++, 0, 0, 255, 255, 255, 255); @@ -393,7 +394,7 @@ void OnLivesCounterDraw(IEvent* ev) { if (!restore) { return; } - ev->cancelled = true; + ev->Cancelled = true; HUD_LivesCount2_Draw(258.0f, SCREEN_HEIGHT - 20, gLifeCount[gPlayerNum]); } @@ -408,25 +409,25 @@ void PortEnhancements_Init() { PortEnhancements_Register(); // Register event listeners - REGISTER_LISTENER(DisplayPostUpdateEvent, OnDisplayUpdatePost, EVENT_PRIORITY_NORMAL); - REGISTER_LISTENER(GamePostUpdateEvent, OnGameUpdatePost, EVENT_PRIORITY_NORMAL); - REGISTER_LISTENER(PlayUpdateEvent, OnPlayUpdateEvent, EVENT_PRIORITY_NORMAL); - REGISTER_LISTENER(PlayerPostUpdateEvent, OnPlayerUpdatePost, EVENT_PRIORITY_NORMAL); - REGISTER_LISTENER(DrawBoostGaugeHUDEvent, OnBoostGaugeDraw, EVENT_PRIORITY_NORMAL); - REGISTER_LISTENER(DrawLivesCounterHUDEvent, OnLivesCounterDraw, EVENT_PRIORITY_NORMAL); - REGISTER_LISTENER(DrawBombCounterHUDEvent, OnBombCounterDraw, EVENT_PRIORITY_NORMAL); - REGISTER_LISTENER(PreSetupRadioMsgEvent, OnPreSetupRadioMsgEvent, EVENT_PRIORITY_NORMAL); - REGISTER_LISTENER(DrawRadarMarkArwingEvent, OnRadarMarkArwingDraw, EVENT_PRIORITY_NORMAL); - REGISTER_LISTENER(DrawRadarMarkWolfenEvent, OnRadarMarkWolfenDraw, EVENT_PRIORITY_NORMAL); - - REGISTER_LISTENER(ObjectUpdateEvent, OnItemGoldRingUpdate, EVENT_PRIORITY_NORMAL); - REGISTER_LISTENER(ObjectDrawPostSetupEvent, OnItemGoldRingDraw, EVENT_PRIORITY_NORMAL); + REGISTER_LISTENER(DisplayPostUpdateEvent, EVENT_PRIORITY_LOW, OnDisplayUpdatePost); + REGISTER_LISTENER(GamePostUpdateEvent, EVENT_PRIORITY_LOW, OnGameUpdatePost); + REGISTER_LISTENER(PlayUpdateEvent, EVENT_PRIORITY_LOW, OnPlayUpdateEvent); + REGISTER_LISTENER(PlayerPostUpdateEvent, EVENT_PRIORITY_LOW, OnPlayerUpdatePost); + REGISTER_LISTENER(DrawBoostGaugeHUDEvent, EVENT_PRIORITY_LOW, OnBoostGaugeDraw); + REGISTER_LISTENER(DrawLivesCounterHUDEvent, EVENT_PRIORITY_LOW, OnLivesCounterDraw); + REGISTER_LISTENER(DrawBombCounterHUDEvent, EVENT_PRIORITY_LOW, OnBombCounterDraw); + REGISTER_LISTENER(PreSetupRadioMsgEvent, EVENT_PRIORITY_LOW, OnPreSetupRadioMsgEvent); + REGISTER_LISTENER(DrawRadarMarkArwingEvent, EVENT_PRIORITY_LOW, OnRadarMarkArwingDraw); + REGISTER_LISTENER(DrawRadarMarkWolfenEvent, EVENT_PRIORITY_LOW, OnRadarMarkWolfenDraw); + + REGISTER_LISTENER(ObjectUpdateEvent, EVENT_PRIORITY_LOW, OnItemGoldRingUpdate); + REGISTER_LISTENER(ObjectDrawPostSetupEvent, EVENT_PRIORITY_LOW, OnItemGoldRingDraw); // Register Action listeners - REGISTER_LISTENER(PlayerActionBoostEvent, OnPlayerBoost, EVENT_PRIORITY_NORMAL); - REGISTER_LISTENER(PlayerActionBrakeEvent, OnPlayerBrake, EVENT_PRIORITY_NORMAL); - REGISTER_LISTENER(PlayerActionPostShootEvent, OnPlayerShootPost, EVENT_PRIORITY_NORMAL); - REGISTER_LISTENER(PlayerActionPreShootChargedEvent, OnPlayerShootChargedPre, EVENT_PRIORITY_NORMAL); + REGISTER_LISTENER(PlayerActionBoostEvent, EVENT_PRIORITY_LOW, OnPlayerBoost); + REGISTER_LISTENER(PlayerActionBrakeEvent, EVENT_PRIORITY_LOW, OnPlayerBrake); + REGISTER_LISTENER(PlayerActionPostShootEvent, EVENT_PRIORITY_LOW, OnPlayerShootPost); + REGISTER_LISTENER(PlayerActionPreShootChargedEvent, EVENT_PRIORITY_LOW, OnPlayerShootChargedPre); // If we close the game while debug pause is active, we want it to be deactivated when we run again. CVarSetInteger("gDebugPause", 0); @@ -434,6 +435,8 @@ void PortEnhancements_Init() { void PortEnhancements_Register() { // Register engine events + REGISTER_EVENT(DisplayPreUpdateEvent); + REGISTER_EVENT(DisplayPreUpdateEvent); REGISTER_EVENT(DisplayPostUpdateEvent); @@ -459,6 +462,25 @@ void PortEnhancements_Register() { REGISTER_EVENT(DrawBossHealthHUDEvent); REGISTER_EVENT(DrawGlobalHUDPreEvent); REGISTER_EVENT(DrawGlobalHUDPostEvent); + REGISTER_EVENT(EngineRenderMenubarEvent); + REGISTER_EVENT(EngineRenderModsEvent); + + // Register audio events + REGISTER_EVENT(PlayVoiceEvent); + REGISTER_EVENT(UpdateVoiceEvent); + REGISTER_EVENT(GetCurrentVoiceEvent); + REGISTER_EVENT(GetVoiceStatusEvent); + REGISTER_EVENT(ClearVoiceEvent); + REGISTER_EVENT(PlaySequenceEvent); + REGISTER_EVENT(PlayFanfareEvent); + REGISTER_EVENT(StopSequenceEvent); + REGISTER_EVENT(SetSequenceFadeEvent); + REGISTER_EVENT(PlaySfxEvent); + REGISTER_EVENT(SetVolumeEvent); + REGISTER_EVENT(SetAudioSpecEvent); + REGISTER_EVENT(AudioUpdateEvent); + REGISTER_EVENT(SeqLayerPreNoteEvent); + REGISTER_EVENT(SeqLayerPostNoteEvent); // Register item events REGISTER_EVENT(ItemDropEvent); diff --git a/src/port/mods/SequenceHooks.cpp b/src/port/mods/SequenceHooks.cpp new file mode 100644 index 000000000..e3ee5ec6d --- /dev/null +++ b/src/port/mods/SequenceHooks.cpp @@ -0,0 +1,77 @@ +#include +#include + +#include + +#include "port/ShipInit.h" +#include "port/mods/SequenceHooks.h" + +#include "port/hooks/Events.h" + +#include "sf64audio_provisional.h" +#include "audioseq_cmd.h" +#include "bgm.h" + +static std::mutex sRemapMtx; +static std::unordered_map sSeqRemap; +static uint16_t sCurrentSeqId[SEQ_PLAYER_MAX]; + +static uint16_t ApplyRemap(uint16_t seqId) { + std::lock_guard lock(sRemapMtx); + auto it = sSeqRemap.find(seqId); + return (it != sSeqRemap.end()) ? it->second : seqId; +} + +static void OnPlaySequence(IEvent* ev) { + auto* event = reinterpret_cast(ev); + *event->seqId = ApplyRemap(*event->seqId); + if (event->seqPlayId < SEQ_PLAYER_MAX) { + sCurrentSeqId[event->seqPlayId] = *event->seqId; + } +} + +static void OnPlayFanfare(IEvent* ev) { + auto* event = reinterpret_cast(ev); + *event->seqId = ApplyRemap(*event->seqId); + sCurrentSeqId[SEQ_PLAYER_FANFARE] = *event->seqId; +} + +static void OnStopSequence(IEvent* ev) { + auto* event = reinterpret_cast(ev); + if (event->seqPlayId < SEQ_PLAYER_MAX) { + sCurrentSeqId[event->seqPlayId] = SEQ_ID_NONE; + } +} + +void Sequence_AddRemap(uint16_t from, uint16_t to) { + std::lock_guard lock(sRemapMtx); + sSeqRemap[from] = to; +} + +void Sequence_RemoveRemap(uint16_t from) { + std::lock_guard lock(sRemapMtx); + sSeqRemap.erase(from); +} + +uint16_t Sequence_GetCurrentSeqId(uint8_t seqPlayId) { + if (seqPlayId >= SEQ_PLAYER_MAX) { + return SEQ_ID_NONE; + } + return sCurrentSeqId[seqPlayId]; +} + +bool Sequence_IsMapped(uint16_t seqId) { + std::lock_guard lock(sRemapMtx); + return sSeqRemap.find(seqId) != sSeqRemap.end(); +} + +extern "C" void SequenceHooks_Init() { + for (int i = 0; i < SEQ_PLAYER_MAX; i++) { + sCurrentSeqId[i] = SEQ_ID_NONE; + } + REGISTER_LISTENER(PlaySequenceEvent, EVENT_PRIORITY_HIGH, OnPlaySequence); + REGISTER_LISTENER(PlayFanfareEvent, EVENT_PRIORITY_HIGH, OnPlayFanfare); + REGISTER_LISTENER(StopSequenceEvent, EVENT_PRIORITY_NORMAL, OnStopSequence); +} + +static RegisterShipInitFunc sInitFunc(SequenceHooks_Init); diff --git a/src/port/mods/SequenceHooks.h b/src/port/mods/SequenceHooks.h new file mode 100644 index 000000000..99d040b6f --- /dev/null +++ b/src/port/mods/SequenceHooks.h @@ -0,0 +1,16 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +void Sequence_AddRemap(uint16_t from, uint16_t to); +void Sequence_RemoveRemap(uint16_t from); +uint16_t Sequence_GetCurrentSeqId(uint8_t seqPlayId); +bool Sequence_IsMapped(uint16_t seqId); + +#ifdef __cplusplus +} +#endif diff --git a/src/port/mods/VoiceEnhancements.cpp b/src/port/mods/VoiceEnhancements.cpp new file mode 100644 index 000000000..2cc5549e7 --- /dev/null +++ b/src/port/mods/VoiceEnhancements.cpp @@ -0,0 +1,482 @@ +#include + +#include +#include +#include +#include "port/ShipInit.h" +#include "port/hooks/Events.h" +#include "port/resource/importers/ResourceUtil.h" + +#include "sf64audio_provisional.h" +#include "audioseq_cmd.h" +#include "audiothread_cmd.h" + +// Pending override request — written by game thread, read by audio thread +// -1 = no request, -2 = clear request, >=0 = msgId to activate +static volatile s32 sPendingVoiceMsgId = -1; + +// Audio-thread-only state +static bool sDirectVoiceActive = false; +static u32 sDirectVoiceMsgId = 0; +static u32 sDirectVoiceNumSamples = 0; +static u32 sDirectVoiceSampleRate = 0; +static u32 sDirectVoiceChannels = 0; +static Sample* sDirectVoiceData = nullptr; +static std::chrono::steady_clock::time_point sVoiceStartTime; +static bool sLoggedNoteCreated = false; +static s32 sMouthState = 0; +static s32 sMouthHoldFrames = 0; + +static TunedSample* gVoiceOverrideTunedSample = nullptr; +static TunedSample* gVoiceOverrideCommSample = nullptr; +static float gVoiceOverrideFreqMod = 1.0f; +static s32 gVoiceOverrideArmed = 0; +static s32 gVoiceOverrideSilencing = 0; +static s32 gVoiceOverrideActiveNote = 0; +static s32 gVoiceOverrideNotesToSkip = 0; +static s32 gVoiceOverrideStarted = 0; + +static Sample sDirectVoiceSample; +static AdpcmLoop sDirectVoiceLoop; +static TunedSample sDirectVoiceTunedSample; +static Instrument sDirectVoiceInstrument; +static EnvelopePoint sDirectVoiceEnvelope[3]; + +static s16 sSilentSampleData = 0; +static Sample sSilentSample; +static AdpcmLoop sSilentLoop; +static TunedSample sSilentTunedSample; +static bool sSilentSampleInitialized = false; + +extern "C" uint8_t sSetNextVoiceId; +extern "C" uint32_t sNextVoiceId; +extern "C" uint8_t sMuteBgmForVoice; +extern "C" void Audio_SetSequenceFade(uint8_t seqPlayId, uint8_t fadeModId, uint8_t fadeMod, uint8_t fadeTime); + +static void InitSilentSample() { + if (sSilentSampleInitialized) + return; + sSilentLoop.start = 0; + sSilentLoop.end = 1; + sSilentLoop.count = 0; + sSilentSample.codec = CODEC_S16; + sSilentSample.medium = MEDIUM_RAM; + sSilentSample.unk_bit26 = 0; + sSilentSample.isRelocated = true; + sSilentSample.size = 2; + sSilentSample.sampleAddr = (u8*) &sSilentSampleData; + sSilentSample.loop = &sSilentLoop; + sSilentSample.book = nullptr; + sSilentTunedSample.sample = &sSilentSample; + sSilentTunedSample.tuning = 1.0f; + sSilentSampleInitialized = true; +} + +static SequenceChannel* Voice_GetChannel15() { + if (!IS_SEQUENCE_CHANNEL_VALID(gSeqPlayers[SEQ_PLAYER_VOICE].channels[15])) { + return nullptr; + } + return gSeqPlayers[SEQ_PLAYER_VOICE].channels[15]; +} + +static void SetupDirectVoiceInstrument(Sample* voiceData) { + sDirectVoiceLoop.start = 0; + sDirectVoiceLoop.end = voiceData->numFrames * voiceData->channels; + sDirectVoiceLoop.count = 0; + + sDirectVoiceSample.codec = CODEC_S16; + sDirectVoiceSample.medium = MEDIUM_RAM; + sDirectVoiceSample.unk_bit26 = 0; + sDirectVoiceSample.isRelocated = true; + sDirectVoiceSample.size = voiceData->size; + sDirectVoiceSample.sampleAddr = voiceData->sampleAddr; + sDirectVoiceSample.loop = &sDirectVoiceLoop; + sDirectVoiceSample.book = nullptr; + + sDirectVoiceTunedSample.sample = &sDirectVoiceSample; + sDirectVoiceTunedSample.tuning = 1.0f; + + sDirectVoiceEnvelope[0] = { 1, 32000 }; + sDirectVoiceEnvelope[1] = { -2, 32000 }; + sDirectVoiceEnvelope[2] = { -1, 0 }; + + sDirectVoiceInstrument.isRelocated = true; + sDirectVoiceInstrument.normalRangeLo = 0; + sDirectVoiceInstrument.normalRangeHi = 127; + sDirectVoiceInstrument.adsrDecayIndex = 0; + sDirectVoiceInstrument.envelope = sDirectVoiceEnvelope; + sDirectVoiceInstrument.lowPitchTunedSample = sDirectVoiceTunedSample; + sDirectVoiceInstrument.normalPitchTunedSample = sDirectVoiceTunedSample; + sDirectVoiceInstrument.highPitchTunedSample = sDirectVoiceTunedSample; + + SPDLOG_INFO("[VoiceHook] Setup: loop [{}, {}), size={}, codec=S16", sDirectVoiceLoop.start, sDirectVoiceLoop.end, + voiceData->size); + SPDLOG_INFO("[VoiceHook] Expected duration: {:.3f}s ({} samples / {} rate / {}ch)", + (float) voiceData->numFrames / (float) voiceData->sampleRate, voiceData->numFrames, + voiceData->sampleRate, voiceData->channels); + SPDLOG_INFO("[VoiceHook] freqMod={:.4f} ({}Hz * {}ch / 32000)", gVoiceOverrideFreqMod, voiceData->sampleRate, + voiceData->channels); +} + +static void VoiceOverride_Finish() { + SPDLOG_INFO("[VoiceHook] VoiceOverride_Finish called (was active={}, msgId={})", sDirectVoiceActive, + sDirectVoiceMsgId); + InitSilentSample(); + if (sDirectVoiceActive) { + gVoiceOverrideSilencing = 1; + } + gVoiceOverrideArmed = 0; + gVoiceOverrideStarted = 0; + gVoiceOverrideActiveNote = 0; + gVoiceOverrideNotesToSkip = 0; + gVoiceOverrideTunedSample = &sSilentTunedSample; + gVoiceOverrideFreqMod = 1.0f; + sDirectVoiceActive = false; + sDirectVoiceData = nullptr; + sLoggedNoteCreated = false; + sMouthState = 0; + sMouthHoldFrames = 0; +} + +// Called from GAME THREAD — only write sPendingVoiceMsgId +static void OnPlayVoice(IEvent* ev) { + auto* event = reinterpret_cast(ev); + + const std::string path = StringHelper::Sprintf("ast_radio/gMsg_ID_%d_Voice", (u32) event->msgId); + Sample* sample = LoadChild(path.c_str()); + + SPDLOG_INFO("[VoiceHook] PlayVoice msgId={}, hasOverride={}, active={}, pending={}, activeMsg={}", event->msgId, + sample != nullptr, sDirectVoiceActive, (s32) sPendingVoiceMsgId, + sDirectVoiceMsgId); + + if (sample == nullptr) { + // No override — signal audio thread to clear if needed + if (sDirectVoiceActive || sPendingVoiceMsgId >= 0 || gVoiceOverrideSilencing) { + sPendingVoiceMsgId = -2; + } + return; + } + + // Don't re-request if already active for the same message + if (sDirectVoiceActive && sDirectVoiceMsgId == (u32) event->msgId) { + SPDLOG_INFO("[VoiceHook] PlayVoice msgId={} — already active, skipping", event->msgId); + return; + } + + sPendingVoiceMsgId = event->msgId; + SPDLOG_INFO("[VoiceHook] PlayVoice msgId={} — set pending", event->msgId); +} + +// Called from AUDIO THREAD — all state mutations happen here +static void OnUpdateVoice(IEvent* ev) { + if (sSetNextVoiceId) { + int8_t voiceBank = sNextVoiceId / 1000; + uint16_t voiceId = sNextVoiceId % 1000; + uint8_t voiceIdHi = voiceId / 256; + uint8_t voiceIdLo = voiceId % 256; + + AUDIOCMD_CHANNEL_SET_IO(SEQ_PLAYER_VOICE, 15, 0, 1); + AUDIOCMD_CHANNEL_SET_IO(SEQ_PLAYER_VOICE, 15, 4, voiceBank); + AUDIOCMD_CHANNEL_SET_IO(SEQ_PLAYER_VOICE, 15, 5, voiceIdHi); + AUDIOCMD_CHANNEL_SET_IO(SEQ_PLAYER_VOICE, 15, 6, voiceIdLo); + sSetNextVoiceId = false; + } + + bool finished = false; + + [&]() { + // Process pending request from game thread + s32 pending = sPendingVoiceMsgId; + if (pending >= 0) { + sPendingVoiceMsgId = -1; + SPDLOG_INFO("[VoiceHook] Processing pending msgId={}", pending); + + // Unfreeze channel for new message + { + SequenceChannel* ch = Voice_GetChannel15(); + if (ch != nullptr) { + SPDLOG_INFO("[VoiceHook] Before unfreeze: stopScript={}, delay={}, layerNote={}", (int) ch->stopScript, + (ch->layers[0] != nullptr ? (int) ch->layers[0]->delay : -1), + (ch->layers[0] != nullptr && ch->layers[0]->note != nullptr ? 1 : 0)); + ch->stopScript = false; + if (ch->layers[0] != nullptr) { + ch->layers[0]->delay = 1; + } + } else { + SPDLOG_INFO("[VoiceHook] Channel15 is NULL during unfreeze!"); + } + } + if (sDirectVoiceActive) { + VoiceOverride_Finish(); + } + + // Load and activate override + const std::string path = StringHelper::Sprintf("ast_radio/gMsg_ID_%d_Voice", pending); + Sample* sample = LoadChild(path.c_str()); + + if (sample != nullptr) { + sDirectVoiceMsgId = (u32) pending; + sDirectVoiceNumSamples = sample->numFrames; + sDirectVoiceSampleRate = sample->sampleRate; + sDirectVoiceChannels = sample->channels; + sDirectVoiceData = sample; + SetupDirectVoiceInstrument(sample); + + gVoiceOverrideFreqMod = (float) (sample->sampleRate * sample->channels) / 32000.0f; + gVoiceOverrideTunedSample = &sDirectVoiceTunedSample; + gVoiceOverrideArmed = 1; + gVoiceOverrideCommSample = nullptr; + gVoiceOverrideSilencing = 0; + gVoiceOverrideNotesToSkip = (pending >= 2000) ? 1 : 0; + gVoiceOverrideStarted = 0; + sDirectVoiceActive = true; + sVoiceStartTime = std::chrono::steady_clock::now(); + + SequenceChannel* ch = Voice_GetChannel15(); + SequenceLayer* layer = (ch != nullptr && ch->layers[0] != nullptr) ? ch->layers[0] : nullptr; + SPDLOG_INFO("[VoiceHook] Activated msgId={}, ch={}, stopScript={}, delay={}, layer={}, note={}", pending, + (void*) ch, (ch ? (int) ch->stopScript : -1), (layer ? (int) layer->delay : -1), (void*) layer, + (layer && layer->note ? (void*) layer->note : nullptr)); + } + } else if (pending == -2) { + sPendingVoiceMsgId = -1; + gVoiceOverrideSilencing = 0; + gVoiceOverrideTunedSample = nullptr; + gVoiceOverrideCommSample = nullptr; + if (sDirectVoiceActive) { + SequenceChannel* ch = Voice_GetChannel15(); + if (ch != nullptr) { + ch->stopScript = false; + if (ch->layers[0] != nullptr) { + ch->layers[0]->delay = 1; + } + } + VoiceOverride_Finish(); + SPDLOG_INFO("[VoiceHook] Cleared override (no override for new message)"); + } + return; + } + + if (!sDirectVoiceActive) { + return; + } + + SequenceChannel* ch = Voice_GetChannel15(); + if (ch == nullptr) { + SPDLOG_INFO("[VoiceHook] UpdateVoice: channel15 is null, finishing"); + VoiceOverride_Finish(); + gVoiceOverrideSilencing = 0; + finished = true; + return; + } + + // Safety net: if gVoiceOverrideStarted never set within 2x expected duration, force finish + auto elapsed = std::chrono::steady_clock::now() - sVoiceStartTime; + float elapsedSec = std::chrono::duration(elapsed).count(); + float expectedDuration = + sDirectVoiceSampleRate > 0 ? (float) sDirectVoiceNumSamples / (float) sDirectVoiceSampleRate : 0.0f; + + if (gVoiceOverrideStarted == 0) { + if (expectedDuration > 0 && elapsedSec > expectedDuration * 2.0f) { + SPDLOG_INFO("[VoiceHook] Safety net: override never started for msgId={} ({:.3f}s > {:.3f}s)", + sDirectVoiceMsgId, elapsedSec, expectedDuration * 2.0f); + ch->seqScriptIO[1] = 0; + ch->stopScript = false; + SequenceLayer* layer = ch->layers[0]; + if (layer != nullptr) { + layer->delay = 1; + } + VoiceOverride_Finish(); + gVoiceOverrideSilencing = 0; + finished = true; + } + return; + } + + // Only check noteFinished/timer after gVoiceOverrideStarted == 1 + SequenceLayer* layer = ch->layers[0]; + + bool noteFinished = false; + if (layer != nullptr && layer->note != nullptr) { + noteFinished = (layer->note->noteSubEu.bitField0.finished != 0); + if (!sLoggedNoteCreated) { + sVoiceStartTime = std::chrono::steady_clock::now(); + SPDLOG_INFO("[VoiceHook] Note detected for msgId={}, noteFinished={}, delay={}, elapsed={:.3f}s", + sDirectVoiceMsgId, (int) noteFinished, (int) layer->delay, elapsedSec); + sLoggedNoteCreated = true; + } + } else if (elapsedSec > 0.5f && !sLoggedNoteCreated) { + sLoggedNoteCreated = true; + SPDLOG_INFO("[VoiceHook] WARNING: No note for msgId={} after {:.3f}s, layer={}, delay={}", sDirectVoiceMsgId, + elapsedSec, (layer ? "exists" : "NULL"), (layer ? (int) layer->delay : -1)); + } + + if (!noteFinished && expectedDuration > 0 && elapsedSec > expectedDuration * 1.5f) { + SPDLOG_INFO("[VoiceHook] Timer backup finish for msgId={} ({:.3f}s > {:.3f}s)", sDirectVoiceMsgId, elapsedSec, + expectedDuration); + noteFinished = true; + } + + if (noteFinished) { + SPDLOG_INFO("[VoiceHook] Finish msgId={}, stopScript={}, delay={}", sDirectVoiceMsgId, (int) ch->stopScript, + (layer ? (int) layer->delay : -1)); + ch->seqScriptIO[1] = 0; + ch->stopScript = false; + if (layer != nullptr) { + layer->delay = 1; + } + VoiceOverride_Finish(); + finished = true; + } + }(); + + if (finished && sMuteBgmForVoice) { + Audio_SetSequenceFade(SEQ_PLAYER_BGM, 2, 127, 15); + sMuteBgmForVoice = false; + } + + if (!sSetNextVoiceId && !finished && (sMuteBgmForVoice) && (Audio_GetCurrentVoice() == 0)) { + Audio_SetSequenceFade(SEQ_PLAYER_BGM, 2, 127, 15); + sMuteBgmForVoice = false; + } +} + +static void OnGetCurrentVoice(IEvent* ev) { + auto* event = reinterpret_cast(ev); + if (sDirectVoiceActive) { + *event->result = (s32) sDirectVoiceMsgId; + } +} + +static void OnGetVoiceStatus(IEvent* ev) { + auto* event = reinterpret_cast(ev); + if (!sDirectVoiceActive || sDirectVoiceData == nullptr || gVoiceOverrideStarted == 0) { + return; + } + + // Compute elapsed playback position + auto elapsed = std::chrono::steady_clock::now() - sVoiceStartTime; + float elapsedSec = std::chrono::duration(elapsed).count(); + u32 sampleIndex = (u32) (elapsedSec * (float) sDirectVoiceSampleRate) * sDirectVoiceChannels; + + // Compute RMS amplitude in a window around current position + const u32 WINDOW = 256; + const s16* pcm = (const s16*) sDirectVoiceData->sampleAddr; + u32 totalSamples = sDirectVoiceData->numFrames * sDirectVoiceData->channels; + + if (sampleIndex >= totalSamples || pcm == nullptr) { + *event->result = 0; + sMouthState = 0; + return; + } + + u32 windowStart = (sampleIndex >= WINDOW / 2) ? sampleIndex - WINDOW / 2 : 0; + u32 windowEnd = windowStart + WINDOW; + if (windowEnd > totalSamples) + windowEnd = totalSamples; + + double sumSq = 0.0; + u32 count = windowEnd - windowStart; + for (u32 i = windowStart; i < windowEnd; i++) { + double s = (double) pcm[i]; + sumSq += s * s; + } + double rms = (count > 0) ? sqrt(sumSq / (double) count) : 0.0; + + // Threshold: ~5% of max 16-bit value + const double THRESHOLD = 1600.0; + s32 desired = (rms > THRESHOLD) ? 1 : 0; + + // Hysteresis: hold mouth state for at least 3 frames to prevent flicker + if (desired != sMouthState) { + sMouthHoldFrames++; + if (sMouthHoldFrames >= 3) { + sMouthState = desired; + sMouthHoldFrames = 0; + } + } else { + sMouthHoldFrames = 0; + } + + *event->result = sMouthState; +} + +static void OnClearVoice(IEvent* ev) { + if (sDirectVoiceActive) { + SequenceChannel* ch = Voice_GetChannel15(); + if (ch != nullptr) { + ch->stopScript = false; + if (ch->layers[0] != nullptr) { + ch->layers[0]->delay = 1; + } + } + } + VoiceOverride_Finish(); + gVoiceOverrideSilencing = 0; + gVoiceOverrideCommSample = nullptr; + gVoiceOverrideTunedSample = nullptr; + gVoiceOverrideNotesToSkip = 0; + gVoiceOverrideStarted = 0; + sDirectVoiceMsgId = 0; + sPendingVoiceMsgId = -1; +} + +static void OnPreNote(IEvent* ev) { + gVoiceOverrideActiveNote = 0; + + auto* event = reinterpret_cast(ev); + auto* layer = event->layer; + auto* channel = event->channel; + + if ((gVoiceOverrideArmed || gVoiceOverrideSilencing) && + layer->channel == gSeqPlayers[SEQ_PLAYER_VOICE].channels[15] && channel->seqScriptIO[1] == 1) { + if (gVoiceOverrideNotesToSkip > 0) { + gVoiceOverrideNotesToSkip--; + gVoiceOverrideCommSample = layer->tunedSample; + return; + } + layer->portamento.mode = 0; + layer->portamento.extent = 0.0f; + if (gVoiceOverrideArmed) { + gVoiceOverrideActiveNote = 1; + gVoiceOverrideStarted = 1; + } + layer->tunedSample = gVoiceOverrideTunedSample; + layer->freqMod = gVoiceOverrideFreqMod; + return; + } + + if (gVoiceOverrideSilencing && layer->channel == gSeqPlayers[SEQ_PLAYER_VOICE].channels[15] && + layer->tunedSample != gVoiceOverrideCommSample) { + if (channel->instOrWave == 126) { + gVoiceOverrideSilencing = 0; + } else { + layer->tunedSample = gVoiceOverrideTunedSample; + } + } +} + +static void OnPostNote(IEvent* ev) { + if (!gVoiceOverrideActiveNote) { + return; + } + + auto* event = reinterpret_cast(ev); + event->layer->delay = 0x7FFF; + event->layer->gateDelay = 0; + event->layer->note->playbackState.portamento.mode = 0; + event->layer->note->playbackState.portamento.extent = 0.0f; +} + +extern "C" void VoiceHooks_Init() { + REGISTER_LISTENER(PlayVoiceEvent, EVENT_PRIORITY_HIGH, OnPlayVoice); + REGISTER_LISTENER(ClearVoiceEvent, EVENT_PRIORITY_HIGH, OnClearVoice); + REGISTER_LISTENER(UpdateVoiceEvent, EVENT_PRIORITY_HIGH, OnUpdateVoice); + REGISTER_LISTENER(GetVoiceStatusEvent, EVENT_PRIORITY_HIGH, OnGetVoiceStatus); + REGISTER_LISTENER(GetCurrentVoiceEvent, EVENT_PRIORITY_HIGH, OnGetCurrentVoice); + + REGISTER_LISTENER(SeqLayerPreNoteEvent, EVENT_PRIORITY_HIGH, OnPreNote); + REGISTER_LISTENER(SeqLayerPostNoteEvent, EVENT_PRIORITY_HIGH, OnPostNote); +} + +static RegisterShipInitFunc initFunc(VoiceHooks_Init); \ No newline at end of file diff --git a/src/port/notification/notification.cpp b/src/port/notification/notification.cpp index f40d0c82a..a7f829f63 100644 --- a/src/port/notification/notification.cpp +++ b/src/port/notification/notification.cpp @@ -1,12 +1,18 @@ - #include "notification.h" -#include "macros.h" + +#include +#include + #include +#include + +#define MAX(a, b) ((a) > (b) ? (a) : (b)) namespace Notification { static uint32_t nextId = 0; static std::vector notifications = {}; +static std::map notificationHeights = {}; // Cache actual heights by notification ID void Window::Draw() { auto vp = ImGui::GetMainViewport(); @@ -14,14 +20,14 @@ void Window::Draw() { const float margin = 30.0f; const float padding = 10.0f; - int position = CVarGetInteger("gNotifications.Position", 0); + int position = CVarGetInteger("gNotifications.Position", 3); - // Top Left + // Calculate base position exactly as in legacy code. ImVec2 basePosition; switch (position) { case 0: // Top Left basePosition = ImVec2(vp->Pos.x + margin, vp->Pos.y + margin); - break; + break; case 1: // Top Right basePosition = ImVec2(vp->Pos.x + vp->Size.x - margin, vp->Pos.y + margin); break; @@ -35,86 +41,242 @@ void Window::Draw() { return; } + // Process each notification + for (int index = 0; index < notifications.size(); ++index) { + auto& notification = notifications[index]; + int count = static_cast(notifications.size()); + int inverseIndex = -(count - 1 - index); + + if (index != 0) { + auto it = notificationHeights.find(notification.id); + if (it != notificationHeights.end()) { + basePosition.y -= it->second + padding; + } else { + basePosition.y -= (notification.isAchievement ? 100.0f : 60.0f) + padding; + } + } + + if (notification.isAchievement) { + // Enhanced layout for achievements + DrawEnhancedNotification(notification, basePosition, position, padding, index); + } else { + // Original simple layout for regular notifications + DrawRegularNotification(notification, basePosition, inverseIndex, position, padding, vp, index); + } + } +} + +void Window::DrawRegularNotification(const Options& notification, ImVec2 basePosition, int inverseIndex, int position, + float padding, ImGuiViewport* vp, int index) { ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0, 0, 0, CVarGetFloat("gNotifications.BgOpacity", 0.5f))); ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(0, 0, 0, 0)); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 4.0f); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(8.0f * CVarGetFloat("gNotifications.Size", 1.8f), 6.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8.0f * CVarGetFloat("gNotifications.Size", 1.8f), 8.0f)); - for (int index = 0; index < notifications.size(); ++index) { - auto& notification = notifications[index]; - int inverseIndex = -ABS(index - (notifications.size() - 1)); + ImGui::SetNextWindowViewport(vp->ID); + if (notification.remainingTime < 4.0f) { + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, (notification.remainingTime - 1) / 3.0f); + } else { + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 1.0f); + } - ImGui::SetNextWindowViewport(vp->ID); - if (notification.remainingTime < 4.0f) { - ImGui::PushStyleVar(ImGuiStyleVar_Alpha, (notification.remainingTime - 1) / 3.0f); - } else { - ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 1.0f); + std::string windowName = "notification#" + std::to_string(notification.id); + ImGui::Begin(windowName.c_str(), nullptr, + ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoFocusOnAppearing | + ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | + ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoScrollbar); + + ImGui::SetWindowFontScale(CVarGetFloat("gNotifications.Size", 1.8f)); + + ImVec2 currentWinSize = ImGui::GetWindowSize(); + ImVec2 notificationPos; + + switch (position) { + case 0: // Top Left + notificationPos = ImVec2(basePosition.x, basePosition.y); + break; + case 1: // Top Right + notificationPos = ImVec2(basePosition.x - currentWinSize.x, basePosition.y); + break; + case 2: // Bottom Left + notificationPos = ImVec2(basePosition.x, basePosition.y - currentWinSize.y); + break; + case 3: // Bottom Right + notificationPos = ImVec2(basePosition.x - currentWinSize.x, basePosition.y - currentWinSize.y); + break; + } + + ImGui::SetWindowPos(notificationPos); + ImGui::AlignTextToFramePadding(); + + if (notification.itemIcon != nullptr) { + float iconSize = 22 * CVarGetFloat("gNotifications.Size", 1.8f); + ImGui::Image(std::static_pointer_cast(Ship::Context::GetInstance()->GetWindow()->GetGui())->GetTextureByName(notification.itemIcon), + ImVec2(iconSize, iconSize)); + ImGui::SameLine(); + } + if (!notification.prefix.empty()) { + ImGui::TextColored(notification.prefixColor, "%s", notification.prefix.c_str()); + ImGui::SameLine(); + } + ImGui::TextColored(notification.messageColor, "%s", notification.message.c_str()); + if (!notification.suffix.empty()) { + ImGui::SameLine(); + ImGui::TextColored(notification.suffixColor, "%s", notification.suffix.c_str()); + } + + // Store actual height in cache for future positioning calculations + notificationHeights[notification.id] = currentWinSize.y; + + ImGui::End(); + ImGui::PopStyleVar(4); + ImGui::PopStyleColor(2); +} + +void Window::DrawEnhancedNotification(const Options& notification, ImVec2 basePosition, int position, float padding, + int index) { + const float enhancedWidth = 380.0f; + const float iconSize = 54.0f; + const float textAreaWidth = enhancedWidth - iconSize - 30.0f; // Account for padding and spacing + + // Enhanced styling + ImGui::SetNextWindowViewport(ImGui::GetMainViewport()->ID); + + float alpha = 1.0f; + if (notification.remainingTime < 4.0f) { + alpha = (notification.remainingTime - 1) / 3.0f; + } + + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, alpha); + ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.08f, 0.08f, 0.12f, 0.95f)); // Darker, more opaque + ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(1.0f, 0.85f, 0.0f, 1.0f)); // Gold border + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 2.0f); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 10.0f); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(16.0f, 12.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(12.0f, 4.0f)); + + ImGui::SetNextWindowSize(ImVec2(enhancedWidth, 0)); // Auto-height with fixed width + + std::string windowName = "enhanced_notification#" + std::to_string(notification.id); + ImGui::Begin(windowName.c_str(), nullptr, + ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoScrollWithMouse | + ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar); + + // Layout with proper vertical centering + if (notification.itemIcon != nullptr) { + // Calculate estimated text content height for centering + float lineHeight = ImGui::GetTextLineHeight(); + float largeLineHeight = lineHeight * 1.3f; // Approximate larger font height + float spacing = ImGui::GetStyle().ItemSpacing.y; + + float totalTextHeight = 0; + if (!notification.prefix.empty()) { + totalTextHeight += largeLineHeight + spacing; + } + totalTextHeight += lineHeight; // Message line + if (!notification.suffix.empty()) { + totalTextHeight += spacing + lineHeight; } - ImGui::Begin(("notification#" + std::to_string(notification.id)).c_str(), nullptr, - ImGuiWindowFlags_AlwaysAutoResize | - ImGuiWindowFlags_NoNav | - ImGuiWindowFlags_NoFocusOnAppearing | - ImGuiWindowFlags_NoResize | - ImGuiWindowFlags_NoDocking | - ImGuiWindowFlags_NoTitleBar | - ImGuiWindowFlags_NoScrollWithMouse | - ImGuiWindowFlags_NoInputs | - ImGuiWindowFlags_NoMove | - ImGuiWindowFlags_NoScrollbar - ); - - ImGui::SetWindowFontScale(CVarGetFloat("gNotifications.Size", 1.8f)); // Make this adjustable - - ImVec2 notificationPos; - switch (position) { - case 0: // Top Left - notificationPos = ImVec2(basePosition.x, basePosition.y + ((ImGui::GetWindowSize().y + padding) * inverseIndex)); - break; - case 1: // Top Right - notificationPos = ImVec2(basePosition.x - ImGui::GetWindowSize().x, basePosition.y + ((ImGui::GetWindowSize().y + padding) * inverseIndex)); - break; - case 2: // Bottom Left - notificationPos = ImVec2(basePosition.x, basePosition.y - ((ImGui::GetWindowSize().y + padding) * (inverseIndex + 1))); - break; - case 3: // Bottom Right - notificationPos = ImVec2(basePosition.x - ImGui::GetWindowSize().x, basePosition.y - ((ImGui::GetWindowSize().y + padding) * (inverseIndex + 1))); - break; + // Calculate vertical offset to center icon with text content + float contentStartY = ImGui::GetCursorPosY(); + float iconOffsetY = MAX(0.0f, (totalTextHeight - iconSize) * 0.5f); + + // Position and draw icon + ImGui::SetCursorPos(ImVec2(ImGui::GetCursorPosX(), contentStartY + iconOffsetY)); + ImGui::Image(std::static_pointer_cast(Ship::Context::GetInstance()->GetWindow()->GetGui())->GetTextureByName(notification.itemIcon), + ImVec2(iconSize, iconSize)); + + // Position text content next to icon + ImGui::SameLine(0, 12.0f); + ImGui::SetCursorPosY(contentStartY); + + ImGui::BeginGroup(); + if (!notification.prefix.empty()) { + ImGui::PushFont(ImGui::GetIO().Fonts->Fonts[1]); // Larger font for prefix + ImGui::TextColored(notification.prefixColor, "%s", notification.prefix.c_str()); + ImGui::PopFont(); + ImGui::Spacing(); // Small gap between prefix and message } - ImGui::SetWindowPos(notificationPos); + // Wrap text to fit in the available space + ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + textAreaWidth); + ImGui::TextColored(notification.messageColor, "%s", notification.message.c_str()); + ImGui::PopTextWrapPos(); - if (notification.itemIcon != nullptr) { - ImGui::Image(Ship::Context::GetInstance()->GetWindow()->GetGui()->GetTextureByName(notification.itemIcon), ImVec2(24, 24)); - ImGui::SameLine(); + if (!notification.suffix.empty()) { + ImGui::Spacing(); // Small gap before suffix + ImGui::TextColored(notification.suffixColor, "%s", notification.suffix.c_str()); } + ImGui::EndGroup(); + + } else { + // No icon, just text with better spacing if (!notification.prefix.empty()) { + ImGui::PushFont(ImGui::GetIO().Fonts->Fonts[1]); ImGui::TextColored(notification.prefixColor, "%s", notification.prefix.c_str()); - ImGui::SameLine(); + ImGui::PopFont(); + ImGui::Spacing(); } + + ImGui::PushTextWrapPos(ImGui::GetContentRegionAvail().x); ImGui::TextColored(notification.messageColor, "%s", notification.message.c_str()); + ImGui::PopTextWrapPos(); + if (!notification.suffix.empty()) { - ImGui::SameLine(); + ImGui::Spacing(); ImGui::TextColored(notification.suffixColor, "%s", notification.suffix.c_str()); } + } - ImGui::End(); - ImGui::PopStyleVar(); + // Get actual window size after content layout + ImVec2 currentWinSize = ImGui::GetWindowSize(); + + ImVec2 notificationPos; + + switch (position) { + case 0: // Top Left + notificationPos = ImVec2(basePosition.x, basePosition.y); + break; + case 1: // Top Right + notificationPos = ImVec2(basePosition.x - currentWinSize.x, basePosition.y); + break; + case 2: // Bottom Left + notificationPos = ImVec2(basePosition.x, basePosition.y - currentWinSize.y); + break; + case 3: // Bottom Right + notificationPos = ImVec2(basePosition.x - currentWinSize.x, basePosition.y - currentWinSize.y); + break; } - ImGui::PopStyleVar(); + ImGui::SetWindowPos(notificationPos); + + // Store actual height in cache for future positioning calculations + notificationHeights[notification.id] = currentWinSize.y; + + ImGui::End(); + + // Restore style settings + ImGui::PopStyleVar(5); ImGui::PopStyleColor(2); } - void Window::UpdateElement() { + float deltaTime = ImGui::GetIO().DeltaTime; + for (int index = 0; index < notifications.size(); ++index) { auto& notification = notifications[index]; - // decrement remainingTime - notification.remainingTime -= ImGui::GetIO().DeltaTime; + // Decrement remaining time. + notification.remainingTime -= deltaTime; - // remove notification if it has expired + // Remove expired notifications. if (notification.remainingTime <= 0) { + // Clear cached height for removed notification + notificationHeights.erase(notification.id); notifications.erase(notifications.begin() + index); --index; } @@ -127,7 +289,71 @@ void Emit(Options notification) { notification.remainingTime = CVarGetFloat("gNotifications.Duration", 10.0f); } notifications.push_back(notification); - // Audio_PlaySoundGeneral(NA_SE_SY_METRONOME, &D_801333D4, 4, &D_801333E0, &D_801333E0, &D_801333E8); + if (!notification.mute) { + // play_sound(SOUND_MENU_READ_A_SIGN, gGlobalSoundSource); + } +} + +void EmitAchievement(const char* iconPath, const std::string& achievementName, int harbourMastery) { + Options notification; + notification.id = nextId++; + notification.itemIcon = iconPath; + notification.prefix = "Achievement Unlocked"; + notification.prefixColor = ImVec4(1.0f, 0.85f, 0.0f, 1.0f); // Gold + notification.message = achievementName; + notification.messageColor = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // White + + if (harbourMastery > 0) { + notification.suffix = std::to_string(harbourMastery) + " HM"; + notification.suffixColor = ImVec4(1.0f, 0.85f, 0.0f, 1.0f); // Gold + } + + notification.remainingTime = CVarGetFloat("gNotifications.Duration", 10.0f); + notification.isAchievement = true; + + notifications.push_back(notification); + // play_sound(SOUND_GENERAL_COIN, gGlobalSoundSource); +} + +void EmitAchievementProgress(const char* iconPath, const char* name, int current, int target) { + char progressText[128]; + snprintf(progressText, sizeof(progressText), "%s: %d / %d", name, current, target); + + Options notification; + notification.id = nextId++; + notification.itemIcon = iconPath; + notification.prefix = "Progress Update"; + notification.prefixColor = ImVec4(0.8f, 0.8f, 0.8f, 1.0f); // Gray + notification.message = progressText; + notification.messageColor = ImVec4(0.8f, 0.8f, 0.8f, 1.0f); // Gray + notification.remainingTime = CVarGetFloat("gNotifications.Duration", 10.0f); + notification.isAchievement = true; // Get achievement styling + + notifications.push_back(notification); + // play_sound(SOUND_GENERAL_COIN, gGlobalSoundSource); +} + +void EmitAchievementProgressWithEvent(const char* iconPath, const char* eventName, const char* achievementName, + int current, int target) { + char progressText[128]; + snprintf(progressText, sizeof(progressText), "%s\n%s: %d / %d", eventName, achievementName, current, target); + + Options notification; + notification.id = nextId++; + notification.itemIcon = iconPath; + notification.prefix = "Event Completed"; + notification.prefixColor = ImVec4(0.4f, 0.8f, 1.0f, 1.0f); // Light blue + notification.message = progressText; + notification.messageColor = ImVec4(0.9f, 0.9f, 0.9f, 1.0f); // Light gray + notification.remainingTime = CVarGetFloat("gNotifications.Duration", 10.0f); + notification.isAchievement = true; // Get achievement styling + + notifications.push_back(notification); + // play_sound(SOUND_GENERAL_COIN, gGlobalSoundSource); +} + +bool IsNotificationActive() { + return !notifications.empty(); } -} // namespace Notification +} // namespace Notification \ No newline at end of file diff --git a/src/port/notification/notification.h b/src/port/notification/notification.h index dbcece01f..d3ffb109a 100644 --- a/src/port/notification/notification.h +++ b/src/port/notification/notification.h @@ -1,10 +1,10 @@ -#pragma once - +#ifndef NOTIFICATION_H +#define NOTIFICATION_H #ifdef __cplusplus #include -#include - +#include +#include namespace Notification { struct Options { @@ -17,19 +17,34 @@ struct Options { std::string suffix = ""; ImVec4 suffixColor = ImVec4(1.0f, 0.5f, 0.5f, 1.0f); float remainingTime = 0.0f; // Seconds + bool mute = false; + bool isAchievement = false; // Simple flag for achievement notifications }; class Window : public Ship::GuiWindow { public: using GuiWindow::GuiWindow; - void InitElement() override {}; - void DrawElement() override {}; + void InitElement() override{}; + void DrawElement() override{}; void Draw() override; void UpdateElement() override; + + private: + void DrawRegularNotification(const Options& notification, ImVec2 basePosition, int inverseIndex, int position, + float padding, ImGuiViewport* vp, int index); + void DrawEnhancedNotification(const Options& notification, ImVec2 basePosition, int position, float padding, + int index); }; void Emit(Options notification); +void EmitAchievement(const char* iconPath, const std::string& achievementName, int harbourMastery); +void EmitAchievementProgress(const char* iconPath, const char* name, int current, int target); +void EmitAchievementProgressWithEvent(const char* iconPath, const char* eventName, const char* achievementName, + int current, int target); +bool IsNotificationActive(); } // namespace Notification + #endif // __cplusplus +#endif // NOTIFICATION_H \ No newline at end of file diff --git a/src/port/resource/importers/AnimFactory.h b/src/port/resource/importers/AnimFactory.h index b6eae2994..53f0c996a 100644 --- a/src/port/resource/importers/AnimFactory.h +++ b/src/port/resource/importers/AnimFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinaryAnimV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/ColPolyFactory.h b/src/port/resource/importers/ColPolyFactory.h index 625356dff..bddefcc10 100644 --- a/src/port/resource/importers/ColPolyFactory.h +++ b/src/port/resource/importers/ColPolyFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinaryColPolyV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/EnvSettingsFactory.cpp b/src/port/resource/importers/EnvSettingsFactory.cpp index b76d85238..db4a33a33 100644 --- a/src/port/resource/importers/EnvSettingsFactory.cpp +++ b/src/port/resource/importers/EnvSettingsFactory.cpp @@ -1,7 +1,7 @@ #include "EnvSettingsFactory.h" -#include "Context.h" -#include "resourcebridge.h" +#include +#include #include "../type/EnvSettings.h" namespace SF64 { diff --git a/src/port/resource/importers/EnvSettingsFactory.h b/src/port/resource/importers/EnvSettingsFactory.h index 2a040c62c..787380ed9 100644 --- a/src/port/resource/importers/EnvSettingsFactory.h +++ b/src/port/resource/importers/EnvSettingsFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinaryEnvSettingsV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/GenericArrayFactory.h b/src/port/resource/importers/GenericArrayFactory.h index e545e0314..0b9a02a0d 100644 --- a/src/port/resource/importers/GenericArrayFactory.h +++ b/src/port/resource/importers/GenericArrayFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinaryGenericArrayV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/HitboxFactory.h b/src/port/resource/importers/HitboxFactory.h index 9da9f894e..7f122a097 100644 --- a/src/port/resource/importers/HitboxFactory.h +++ b/src/port/resource/importers/HitboxFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinaryHitboxV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/LimbFactory.cpp b/src/port/resource/importers/LimbFactory.cpp index e9216c94b..4cf89051e 100644 --- a/src/port/resource/importers/LimbFactory.cpp +++ b/src/port/resource/importers/LimbFactory.cpp @@ -1,7 +1,7 @@ #include "LimbFactory.h" -#include "Context.h" -#include "resourcebridge.h" +#include +#include #include "../type/Limb.h" #include "ResourceUtil.h" diff --git a/src/port/resource/importers/LimbFactory.h b/src/port/resource/importers/LimbFactory.h index 7a8749829..ead3c594f 100644 --- a/src/port/resource/importers/LimbFactory.h +++ b/src/port/resource/importers/LimbFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinaryLimbV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/MessageFactory.h b/src/port/resource/importers/MessageFactory.h index 0a89395e3..69690bdd5 100644 --- a/src/port/resource/importers/MessageFactory.h +++ b/src/port/resource/importers/MessageFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinaryMessageV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/MessageLookupFactory.cpp b/src/port/resource/importers/MessageLookupFactory.cpp index 3fa01480e..f184bd515 100644 --- a/src/port/resource/importers/MessageLookupFactory.cpp +++ b/src/port/resource/importers/MessageLookupFactory.cpp @@ -1,7 +1,7 @@ #include "MessageLookupFactory.h" #include "../type/Message.h" #include "spdlog/spdlog.h" -#include "resourcebridge.h" +#include #include "ResourceUtil.h" namespace SF64 { diff --git a/src/port/resource/importers/MessageLookupFactory.h b/src/port/resource/importers/MessageLookupFactory.h index fd17c22cd..714b831f3 100644 --- a/src/port/resource/importers/MessageLookupFactory.h +++ b/src/port/resource/importers/MessageLookupFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinaryMessageLookupV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/ObjectInitFactory.cpp b/src/port/resource/importers/ObjectInitFactory.cpp index b8965b8d8..171bd7e42 100644 --- a/src/port/resource/importers/ObjectInitFactory.cpp +++ b/src/port/resource/importers/ObjectInitFactory.cpp @@ -1,7 +1,7 @@ #include "ObjectInitFactory.h" -#include "Context.h" -#include "resourcebridge.h" +#include +#include #include "../type/ObjectInit.h" namespace SF64 { diff --git a/src/port/resource/importers/ObjectInitFactory.h b/src/port/resource/importers/ObjectInitFactory.h index 583c56150..ee7e8b6fe 100644 --- a/src/port/resource/importers/ObjectInitFactory.h +++ b/src/port/resource/importers/ObjectInitFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinaryObjectInitV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/ResourceUtil.h b/src/port/resource/importers/ResourceUtil.h index 67ed936ac..3340911db 100644 --- a/src/port/resource/importers/ResourceUtil.h +++ b/src/port/resource/importers/ResourceUtil.h @@ -1,19 +1,21 @@ #pragma once -#include "resourcebridge.h" -#include "ResourceManager.h" -#include "Context.h" +#include +#include +#include -namespace SF64 { template T LoadChild(uint64_t crc) { - if (crc == 0) { - return nullptr; - } auto path = ResourceGetNameByCrc(crc); if (path == nullptr) { return nullptr; } auto asset = Ship::Context::GetInstance()->GetResourceManager()->LoadResourceProcess(path); - return asset != nullptr ? static_cast(asset->GetRawPointer()) : nullptr; + return asset ? static_cast(asset->GetRawPointer()) : nullptr; } +template T LoadChild(const char* path) { + if (path == nullptr) { + return nullptr; + } + auto asset = Ship::Context::GetInstance()->GetResourceManager()->LoadResourceProcess(path); + return asset ? static_cast(asset->GetRawPointer()) : nullptr; } \ No newline at end of file diff --git a/src/port/resource/importers/ScriptCommandFactory.h b/src/port/resource/importers/ScriptCommandFactory.h index 0b38712ca..c2c3d4523 100644 --- a/src/port/resource/importers/ScriptCommandFactory.h +++ b/src/port/resource/importers/ScriptCommandFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinaryScriptCMDV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/ScriptFactory.h b/src/port/resource/importers/ScriptFactory.h index deef1fb22..0c0e8fc1f 100644 --- a/src/port/resource/importers/ScriptFactory.h +++ b/src/port/resource/importers/ScriptFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinaryScriptV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/SkeletonFactory.h b/src/port/resource/importers/SkeletonFactory.h index b0a460d07..bc2cb2058 100644 --- a/src/port/resource/importers/SkeletonFactory.h +++ b/src/port/resource/importers/SkeletonFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinarySkeletonV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/Vec3fFactory.h b/src/port/resource/importers/Vec3fFactory.h index 1116aa55d..52c0bc4b1 100644 --- a/src/port/resource/importers/Vec3fFactory.h +++ b/src/port/resource/importers/Vec3fFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinaryVec3fV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/Vec3sFactory.h b/src/port/resource/importers/Vec3sFactory.h index 2182e498a..f12d37c6a 100644 --- a/src/port/resource/importers/Vec3sFactory.h +++ b/src/port/resource/importers/Vec3sFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinaryVec3sV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/audio/AudioTableFactory.h b/src/port/resource/importers/audio/AudioTableFactory.h index a046131c8..19159bdbf 100644 --- a/src/port/resource/importers/audio/AudioTableFactory.h +++ b/src/port/resource/importers/audio/AudioTableFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinaryAudioTableV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/audio/BookFactory.h b/src/port/resource/importers/audio/BookFactory.h index d7de8c994..87a2a81ea 100644 --- a/src/port/resource/importers/audio/BookFactory.h +++ b/src/port/resource/importers/audio/BookFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinaryAdpcmBookV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/audio/DrumFactory.cpp b/src/port/resource/importers/audio/DrumFactory.cpp index d93fb0f9f..7d75a6acd 100644 --- a/src/port/resource/importers/audio/DrumFactory.cpp +++ b/src/port/resource/importers/audio/DrumFactory.cpp @@ -16,8 +16,9 @@ std::shared_ptr ResourceFactoryBinaryDrumV0::ReadResource(std:: drum->mDrum.pan = reader->ReadUByte(); drum->mDrum.isRelocated = reader->ReadUByte(); auto sample = LoadChild(reader->ReadUInt64()); + float streamTuning = reader->ReadFloat(); drum->mDrum.tunedSample.sample = sample; - drum->mDrum.tunedSample.tuning = sample->tuning != 0.0f ? sample->tuning : reader->ReadFloat(); + drum->mDrum.tunedSample.tuning = (sample != nullptr && sample->tuning != 0.0f) ? sample->tuning : streamTuning; drum->mDrum.envelope = LoadChild(reader->ReadUInt64()); drum->mDrum.isRelocated = 1; diff --git a/src/port/resource/importers/audio/DrumFactory.h b/src/port/resource/importers/audio/DrumFactory.h index c618bb08a..35100e81e 100644 --- a/src/port/resource/importers/audio/DrumFactory.h +++ b/src/port/resource/importers/audio/DrumFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinaryDrumV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/audio/EnvelopeFactory.h b/src/port/resource/importers/audio/EnvelopeFactory.h index af2ac2627..d7bf6670c 100644 --- a/src/port/resource/importers/audio/EnvelopeFactory.h +++ b/src/port/resource/importers/audio/EnvelopeFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinaryEnvelopeV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/audio/InstrumentFactory.cpp b/src/port/resource/importers/audio/InstrumentFactory.cpp index 5bda4ecdb..e2b4a4567 100644 --- a/src/port/resource/importers/audio/InstrumentFactory.cpp +++ b/src/port/resource/importers/audio/InstrumentFactory.cpp @@ -18,19 +18,22 @@ std::shared_ptr ResourceFactoryBinaryInstrumentV0::ReadResource instrument->mInstrument.adsrDecayIndex = reader->ReadUByte(); instrument->mInstrument.envelope = LoadChild(reader->ReadUInt64()); auto lowSample = LoadChild(reader->ReadUInt64()); + float lowTuning = reader->ReadFloat(); instrument->mInstrument.lowPitchTunedSample.sample = lowSample; instrument->mInstrument.lowPitchTunedSample.tuning = - lowSample != nullptr && lowSample->tuning != 0.0f ? lowSample->tuning : reader->ReadFloat(); + lowSample != nullptr && lowSample->tuning != 0.0f ? lowSample->tuning : lowTuning; auto normalSample = LoadChild(reader->ReadUInt64()); + float normalTuning = reader->ReadFloat(); instrument->mInstrument.normalPitchTunedSample.sample = normalSample; instrument->mInstrument.normalPitchTunedSample.tuning = - normalSample != nullptr && normalSample->tuning != 0.0f ? normalSample->tuning : reader->ReadFloat(); + normalSample != nullptr && normalSample->tuning != 0.0f ? normalSample->tuning : normalTuning; auto highSample = LoadChild(reader->ReadUInt64()); + float highTuning = reader->ReadFloat(); instrument->mInstrument.highPitchTunedSample.sample = highSample; instrument->mInstrument.highPitchTunedSample.tuning = - highSample != nullptr && highSample->tuning != 0.0f ? highSample->tuning : reader->ReadFloat(); + highSample != nullptr && highSample->tuning != 0.0f ? highSample->tuning : highTuning; instrument->mInstrument.isRelocated = 1; return instrument; diff --git a/src/port/resource/importers/audio/InstrumentFactory.h b/src/port/resource/importers/audio/InstrumentFactory.h index 643015946..56ff876f8 100644 --- a/src/port/resource/importers/audio/InstrumentFactory.h +++ b/src/port/resource/importers/audio/InstrumentFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinaryInstrumentV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/audio/LoopFactory.h b/src/port/resource/importers/audio/LoopFactory.h index d2e78b10a..47fc66010 100644 --- a/src/port/resource/importers/audio/LoopFactory.h +++ b/src/port/resource/importers/audio/LoopFactory.h @@ -1,7 +1,7 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryBinary.h" +#include +#include namespace SF64 { class ResourceFactoryBinaryAdpcmLoopV0 : public Ship::ResourceFactoryBinary { diff --git a/src/port/resource/importers/audio/SampleFactory.cpp b/src/port/resource/importers/audio/SampleFactory.cpp index d4115cb9b..9993d8b10 100644 --- a/src/port/resource/importers/audio/SampleFactory.cpp +++ b/src/port/resource/importers/audio/SampleFactory.cpp @@ -1,15 +1,17 @@ #include "SampleFactory.h" #include "../ResourceUtil.h" #include "port/resource/type/audio/Sample.h" -#include "sf64audio_provisional.h" +#include "port/audio/AudioDebug.h" +#include "spdlog/spdlog.h" #define DR_WAV_IMPLEMENTATION #include #include #define DR_MP3_IMPLEMENTATION #include - #include "vorbis/vorbisfile.h" +#include "sf64audio_provisional.h" + namespace SF64 { std::shared_ptr ResourceFactoryBinarySampleV1::ReadResource(std::shared_ptr file, std::shared_ptr initData) { @@ -41,6 +43,28 @@ std::shared_ptr ResourceFactoryBinarySampleV1::ReadResource(std sample->mSample.isRelocated = 1; + AudioDebug_RegisterSample(&sample->mSample, initData->Path); + return sample; +} + +std::shared_ptr ResourceFactoryBinarySampleV2::ReadResource(std::shared_ptr file, + std::shared_ptr initData) { + if (!FileHasValidFormatAndReader(file, initData)) { + return nullptr; + } + + auto reader = std::get>(file->Reader); + uint64_t canonical_hash = reader->ReadUInt64(); + + SampleData* canonical = LoadChild(canonical_hash); + if (canonical == nullptr) { + return nullptr; + } + + auto sample = std::make_shared(initData); + sample->mSample = *canonical; + sample->mSample.isRelocated = 1; + AudioDebug_RegisterSample(&sample->mSample, initData->Path); return sample; } @@ -110,7 +134,13 @@ static void Mp3DecoderWorker(std::shared_ptr sample, std::shared_ptrmSample.tuning = (float)(sampleRate * channels) / 32000.0f; sample->mSample.size = numFrames * channels * 2; sample->mSample.sampleAddr = new uint8_t[sample->mSample.size]; + sample->mSample.numFrames = numFrames; + sample->mSample.channels = channels; + sample->mSample.sampleRate = sampleRate; drmp3_read_pcm_frames_s16(&mp3, numFrames, (int16_t*)sample->mSample.sampleAddr); + sample->mSample.codec = CODEC_S16; + sample->mSample.medium = MEDIUM_RAM; + sample->mSample.isRelocated = 1; } static void OggDecoderWorker(std::shared_ptr sample, std::shared_ptr sampleFile) { @@ -134,6 +164,10 @@ static void OggDecoderWorker(std::shared_ptr sample, std::shared_ptrmSample.sampleAddr = new uint8_t[toRead]; + sample->mSample.numFrames = numFrames; + sample->mSample.channels = numChannels; + sample->mSample.sampleRate = sampleRate; + sample->mSample.size = toRead; sample->mSample.tuning = (float)(sampleRate * numChannels) / 32000.0f; do { read = ov_read(&vf, dataBuff, 4096, 0, 2, 1, &bitStream); @@ -141,6 +175,9 @@ static void OggDecoderWorker(std::shared_ptr sample, std::shared_ptrmSample.codec = CODEC_S16; + sample->mSample.medium = MEDIUM_RAM; + sample->mSample.isRelocated = 1; } std::shared_ptr ResourceFactoryXMLSampleV0::ReadResource(std::shared_ptr file, @@ -165,6 +202,11 @@ std::shared_ptr ResourceFactoryXMLSampleV0::ReadResource(std::s sample->mSample.loop->start = loopRoot->UnsignedAttribute("Start"); sample->mSample.loop->end = loopRoot->UnsignedAttribute("End"); sample->mSample.loop->count = loopRoot->UnsignedAttribute("Count"); + SPDLOG_INFO("[SampleFactory] {} loop start={} end={} count={}", + initData->Path, + sample->mSample.loop->start, + sample->mSample.loop->end, + sample->mSample.loop->count); tinyxml2::XMLElement* predictor = loopRoot->FirstChildElement("Predictor"); while (predictor != nullptr) { sample->mSample.loop->predictorState[i++] = predictor->IntAttribute("State"); @@ -195,6 +237,8 @@ std::shared_ptr ResourceFactoryXMLSampleV0::ReadResource(std::s if (customFormatStr != nullptr) { // Compressed files can take a really long time to decode (~250ms per). // This worked when we tested it (09/04/2024) (Works on my machine) + sample->mSample.codec = CODEC_S16; + sample->mSample.medium = MEDIUM_RAM; if (strcmp(customFormatStr, "wav") == 0) { drwav wav; drwav_uint64 numFrames; @@ -207,16 +251,42 @@ std::shared_ptr ResourceFactoryXMLSampleV0::ReadResource(std::s sample->mSample.tuning = (float)(wav.sampleRate * wav.channels) / 32000.0f; sample->mSample.size = numFrames * wav.channels * 2; sample->mSample.sampleAddr = new uint8_t[sample->mSample.size]; + sample->mSample.numFrames = numFrames; + sample->mSample.channels = wav.channels; + sample->mSample.sampleRate = wav.sampleRate; drwav_read_pcm_frames_s16(&wav, numFrames, (int16_t*)sample->mSample.sampleAddr); + sample->mSample.isRelocated = 1; + AudioDebug_RegisterSample(&sample->mSample, initData->Path); return sample; } else if (strcmp(customFormatStr, "ogg") == 0) { + // Read OGG header synchronously so mSample.tuning is set before SoundFontFactory + // checks it (async thread sets it too late — tuning stays 0 → wrong pitch). + OggFileData headerFileData = { + .data = sampleFile->Buffer->data(), + .pos = 0, + .size = sampleFile->Buffer->size(), + }; + OggVorbis_File vf_hdr; + if (ov_open_callbacks(&headerFileData, &vf_hdr, nullptr, 0, vorbisCallbacks) == 0) { + vorbis_info* vi = ov_info(&vf_hdr, -1); + sample->mSample.tuning = (float)(vi->rate * vi->channels) / 32000.0f; + ov_clear(&vf_hdr); + } std::thread fileDecoderThread = std::thread(OggDecoderWorker, sample, sampleFile); fileDecoderThread.detach(); + AudioDebug_RegisterSample(&sample->mSample, initData->Path); return sample; } else if (strcmp(customFormatStr, "mp3") == 0) { + // Read MP3 header synchronously for the same reason. + drmp3 mp3_hdr; + if (drmp3_init_memory(&mp3_hdr, sampleFile->Buffer->data(), sampleFile->Buffer->size(), nullptr)) { + sample->mSample.tuning = (float)(mp3_hdr.sampleRate * mp3_hdr.channels) / 32000.0f; + drmp3_uninit(&mp3_hdr); + } std::thread fileDecoderThread = std::thread(Mp3DecoderWorker, sample, sampleFile); fileDecoderThread.detach(); + AudioDebug_RegisterSample(&sample->mSample, initData->Path); return sample; } } @@ -229,6 +299,7 @@ std::shared_ptr ResourceFactoryXMLSampleV0::ReadResource(std::s sample->mSample.isRelocated = 1; + AudioDebug_RegisterSample(&sample->mSample, initData->Path); return sample; } diff --git a/src/port/resource/importers/audio/SampleFactory.h b/src/port/resource/importers/audio/SampleFactory.h index b3e0b0c01..f6759d240 100644 --- a/src/port/resource/importers/audio/SampleFactory.h +++ b/src/port/resource/importers/audio/SampleFactory.h @@ -1,8 +1,8 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryXML.h" -#include "ResourceFactoryBinary.h" +#include +#include +#include namespace SF64 { struct OggFileData { @@ -17,6 +17,14 @@ class ResourceFactoryBinarySampleV1 : public Ship::ResourceFactoryBinary { std::shared_ptr initData) override; }; +// V2: redirect entry — shares audio data from a canonical V1 sample identified +// by its CRC64 hash. The body is a single uint64 (canonical_hash); no raw bytes. +class ResourceFactoryBinarySampleV2 : public Ship::ResourceFactoryBinary { + public: + std::shared_ptr ReadResource(std::shared_ptr file, + std::shared_ptr initData) override; +}; + class ResourceFactoryXMLSampleV0 : public Ship::ResourceFactoryXML { public: std::shared_ptr ReadResource(std::shared_ptr file, diff --git a/src/port/resource/importers/audio/SequenceFactory.cpp b/src/port/resource/importers/audio/SequenceFactory.cpp new file mode 100644 index 000000000..3c7a3c1d5 --- /dev/null +++ b/src/port/resource/importers/audio/SequenceFactory.cpp @@ -0,0 +1,305 @@ +#include "SequenceFactory.h" +#include "spdlog/spdlog.h" +#include +#include +#include +#include +#include +#include "port/audio/AudioDebug.h" + +namespace SF64 { + +// --------------------------------------------------------------------------- +// Binary V2 reader — mirrors NSequenceBinaryExporter / Shipwright V2 layout: +// u32 seqDataSize +// u8[] seqData[seqDataSize] +// u8 seqNumber +// u8 medium +// u8 cachePolicy +// u32 numFonts +// u8 fonts[16] (always present; numFonts entries are valid) +// --------------------------------------------------------------------------- +std::shared_ptr +ResourceFactoryBinarySequenceV2::ReadResource(std::shared_ptr file, + std::shared_ptr initData) { + if (!FileHasValidFormatAndReader(file, initData)) { + return nullptr; + } + + auto seq = std::make_shared(initData); + auto reader = std::get>(file->Reader); + + seq->mSequence.seqDataSize = reader->ReadUInt32(); + seq->mBuffer.resize(seq->mSequence.seqDataSize); + for (uint32_t i = 0; i < seq->mSequence.seqDataSize; i++) { + seq->mBuffer[i] = reader->ReadChar(); + } + seq->mSequence.seqData = seq->mBuffer.data(); + + seq->mSequence.seqNumber = reader->ReadUByte(); + seq->mSequence.medium = reader->ReadUByte(); + seq->mSequence.cachePolicy = reader->ReadUByte(); + seq->mSequence.numFonts = reader->ReadUInt32(); + + memset(seq->mSequence.fonts, 0, sizeof(seq->mSequence.fonts)); + for (int i = 0; i < 16; i++) { + seq->mSequence.fonts[i] = reader->ReadUByte(); + } + + SF64::AudioDebug_RegisterSequence(seq->mSequence.seqNumber, initData->Path); + return seq; +} + +// --------------------------------------------------------------------------- +// Helpers for bytecode generation (mirrors Shipwright's XML streamed path) +// --------------------------------------------------------------------------- + +static void WriteInsnNoArg(Ship::BinaryWriter* w, uint8_t op) { + w->Write(op); +} + +template +static void WriteInsnOneArg(Ship::BinaryWriter* w, uint8_t op, T arg) { + w->Write(op); + w->Write(arg); +} + +template +static void WriteInsnThreeArg(Ship::BinaryWriter* w, uint8_t op, T1 a, T2 b, T3 c) { + w->Write(op); + w->Write(a); + w->Write(b); + w->Write(c); +} + +static void WriteMuteBhv(Ship::BinaryWriter* w, uint8_t a) { WriteInsnOneArg(w, 0xD3, a); } +static void WriteMuteScale(Ship::BinaryWriter* w, uint8_t a) { WriteInsnOneArg(w, 0xD5, a); } +static void WriteInitchan(Ship::BinaryWriter* w, uint16_t ch) { WriteInsnOneArg(w, 0xD7, ch); } +static void WriteLdchan(Ship::BinaryWriter* w, uint8_t ch, uint16_t off) { + WriteInsnOneArg(w, (uint8_t)(0x90 | ch), off); +} +static void WriteVolSHeader(Ship::BinaryWriter* w, uint8_t v) { WriteInsnOneArg(w, 0xDB, v); } +static void WriteVolCHeader(Ship::BinaryWriter* w, uint8_t v) { WriteInsnOneArg(w, 0xDF, v); } +static void WriteTempo(Ship::BinaryWriter* w, uint8_t t) { WriteInsnOneArg(w, 0xDD, t); } +static void WriteJump(Ship::BinaryWriter* w, uint16_t off) { WriteInsnOneArg(w, 0xFB, off); } +static void WriteDisablecan(Ship::BinaryWriter* w, uint16_t ch){ WriteInsnOneArg(w, 0xD6, ch); } +static void WriteNoshort(Ship::BinaryWriter* w) { WriteInsnNoArg(w, 0xC4); } +static void WriteLdlayer(Ship::BinaryWriter* w, uint8_t l, uint16_t off) { + WriteInsnOneArg(w, (uint8_t)(0x90 | l), off); +} +static void WritePan(Ship::BinaryWriter* w, uint8_t p) { WriteInsnOneArg(w, 0xDD, p); } +static void WriteBend(Ship::BinaryWriter* w, uint8_t b) { WriteInsnOneArg(w, 0xD3, b); } +static void WriteInstrument(Ship::BinaryWriter* w, uint8_t i) { WriteInsnOneArg(w, 0xC1, i); } +static void WriteLegato(Ship::BinaryWriter* w) { WriteInsnNoArg(w, 0xC4); } +static void WriteDelay(Ship::BinaryWriter* w, uint16_t delay) { + if (delay > 0x7F) { + WriteInsnOneArg(w, 0xFD, (uint16_t)(delay | 0x8000)); + } else { + WriteInsnOneArg(w, 0xFD, (uint8_t)delay); + } +} +static void WriteNotedvg(Ship::BinaryWriter* w, uint8_t note, uint16_t delay, uint8_t vel, uint8_t gate) { + if (delay > 0x7F) { + WriteInsnThreeArg(w, note, (uint16_t)(delay | 0x8000), vel, gate); + } else { + WriteInsnThreeArg(w, note, (uint8_t)delay, vel, gate); + } +} + +static void WriteMonoSingleSeq(Ship::BinaryWriter* w, uint16_t delay, uint8_t tempo, bool looped) { + if (looped) delay = 0x7FFF; + + WriteMuteBhv(w, 0x20); + WriteMuteScale(w, 0x32); + WriteInitchan(w, 0b11); + + uint16_t channelPlaceholderOff = w->GetBaseAddress(); + uint16_t loopPoint = w->GetBaseAddress(); + WriteLdchan(w, 0, 0); + WriteVolSHeader(w, 127); + WriteTempo(w, tempo); + WriteDelay(w, delay); + if (looped) WriteJump(w, loopPoint); + WriteDisablecan(w, 0b11); + w->Write((uint8_t)0xFF); + + uint16_t channelStart = w->GetBaseAddress(); + w->Seek(channelPlaceholderOff, Ship::SeekOffsetType::Start); + WriteLdchan(w, 0, channelStart); + w->Seek(channelStart, Ship::SeekOffsetType::Start); + + WriteNoshort(w); + uint16_t layerPlaceholderOff = w->GetBaseAddress(); + WriteLdlayer(w, 0, 0); + WritePan(w, 64); + WriteVolCHeader(w, 127); + WriteBend(w, 0); + WriteInstrument(w, 0); + WriteDelay(w, delay); + w->Write((uint8_t)0xFF); + + uint16_t layerStart = w->GetBaseAddress(); + w->Seek(layerPlaceholderOff, Ship::SeekOffsetType::Start); + WriteLdlayer(w, 0, layerStart); + w->Seek(layerStart, Ship::SeekOffsetType::Start); + + WriteLegato(w); + WriteNotedvg(w, 39, 0x7FFF - 1, 0x7F, 1); + w->Write((uint8_t)0xFF); +} + +static void WriteStereoSingleSeq(Ship::BinaryWriter* w, uint16_t delay, uint8_t tempo, bool looped) { + if (looped) delay = 0x7FFF; + + WriteMuteBhv(w, 0x20); + WriteMuteScale(w, 0x32); + WriteInitchan(w, 0b11); + + uint16_t channelPlaceholderOff = w->GetBaseAddress(); + uint16_t loopPoint = w->GetBaseAddress(); + WriteLdchan(w, 0, 0); + WriteLdchan(w, 1, 0); + WriteVolSHeader(w, 127); + WriteTempo(w, tempo); + WriteDelay(w, delay); + if (looped) WriteJump(w, loopPoint); + WriteDisablecan(w, 0b11); + w->Write((uint8_t)0xFF); + + uint16_t lChannelStart = w->GetBaseAddress(); + WriteNoshort(w); + uint16_t lLayerPlaceholderOff = w->GetBaseAddress(); + WriteLdlayer(w, 0, 0); + WritePan(w, 0); + WriteVolCHeader(w, 127); + WriteBend(w, 0); + WriteInstrument(w, 0); + WriteDelay(w, delay); + w->Write((uint8_t)0xFF); + + uint16_t rChannelStart = w->GetBaseAddress(); + WriteNoshort(w); + uint16_t rLayerPlaceholderOff = w->GetBaseAddress(); + WriteLdlayer(w, 1, 0); + WritePan(w, 127); + WriteVolCHeader(w, 127); + WriteBend(w, 0); + WriteInstrument(w, 1); + WriteDelay(w, delay); + w->Write((uint8_t)0xFF); + + uint16_t placeholder = w->GetBaseAddress(); + w->Seek(channelPlaceholderOff, Ship::SeekOffsetType::Start); + WriteLdchan(w, 0, lChannelStart); + WriteLdchan(w, 1, rChannelStart); + w->Seek(placeholder, Ship::SeekOffsetType::Start); + + uint16_t lLayerOffset = w->GetBaseAddress(); + WriteLegato(w); + WriteNotedvg(w, 39, 0x7FFF - 1, 0x7F, 1); + w->Write((uint8_t)0xFF); + + uint16_t rLayerOffset = w->GetBaseAddress(); + WriteLegato(w); + WriteNotedvg(w, 39, 0x7FFF - 1, 0x7F, 1); + w->Write((uint8_t)0xFF); + + w->Seek(lLayerPlaceholderOff, Ship::SeekOffsetType::Start); + WriteLdlayer(w, 0, lLayerOffset); + w->Seek(rLayerPlaceholderOff, Ship::SeekOffsetType::Start); + WriteLdlayer(w, 1, rLayerOffset); +} + +// --------------------------------------------------------------------------- +// XML V0 reader — mirrors Shipwright's ResourceFactoryXMLAudioSequenceV0 +// --------------------------------------------------------------------------- +std::shared_ptr +ResourceFactoryXMLSequenceV0::ReadResource(std::shared_ptr file, + std::shared_ptr initData) { + if (!FileHasValidFormatAndReader(file, initData)) { + return nullptr; + } + + auto seq = std::make_shared(initData); + auto child = std::get>(file->Reader)->FirstChildElement(); + + seq->mSequence.medium = ResourceFactoryXMLSoundFontV0::MediumStrToInt(child->Attribute("Medium")); + seq->mSequence.cachePolicy = ResourceFactoryXMLSoundFontV0::CachePolicyToInt(child->Attribute("CachePolicy")); + seq->mSequence.seqDataSize = child->IntAttribute("Size"); + seq->mSequence.seqNumber = (uint8_t)child->IntAttribute("Index"); + bool streamed = child->BoolAttribute("Streamed"); + + memset(seq->mSequence.fonts, 0, sizeof(seq->mSequence.fonts)); + + unsigned int i = 0; + tinyxml2::XMLElement* fontsElement = child->FirstChildElement(); + if (fontsElement != nullptr) { + tinyxml2::XMLElement* fontElement = fontsElement->FirstChildElement(); + while (fontElement != nullptr) { + seq->mSequence.fonts[i] = fontElement->IntAttribute("FontIdx"); + fontElement = fontElement->NextSiblingElement(); + i++; + } + } + seq->mSequence.numFonts = i; + + const char* path = child->Attribute("Path"); + std::shared_ptr seqFile; + if (path != nullptr) { + seqFile = Ship::Context::GetInstance() + ->GetResourceManager() + ->GetArchiveManager() + ->LoadFile(path); + } + + if (!streamed) { + if (!seqFile || !seqFile->Buffer || seqFile->Buffer->empty()) { + SPDLOG_ERROR("[SequenceFactory] Could not load sequence file '{}' for '{}'", + path ? path : "(null)", initData->Path); + return nullptr; + } + seq->mSequence.seqDataSize = seqFile->Buffer->size(); + seq->mBuffer.resize(seq->mSequence.seqDataSize); + memcpy(seq->mBuffer.data(), seqFile->Buffer->data(), seq->mSequence.seqDataSize); + seq->mSequence.seqData = seq->mBuffer.data(); + } else { + // Streamed: numFonts = -1 signals the audio engine that fonts[] holds a CRC64 + seq->mSequence.numFonts = (uint32_t)-1; + + if (path != nullptr && seqFile && seqFile->Buffer && !seqFile->Buffer->empty()) { + seq->mSequence.seqDataSize = seqFile->Buffer->size(); + seq->mBuffer.resize(seq->mSequence.seqDataSize); + memcpy(seq->mBuffer.data(), seqFile->Buffer->data(), seq->mSequence.seqDataSize); + seq->mSequence.seqData = seq->mBuffer.data(); + } else { + // Generate synthetic bytecode from Length/Looped/Stereo attributes + unsigned int length = child->UnsignedAttribute("Length"); + bool looped = child->BoolAttribute("Looped", true); + bool stereo = child->BoolAttribute("Stereo", false); + + constexpr uint8_t TEMPO = 1; + constexpr float TEMPO_F = TEMPO; + float delayF = (float)length / (60.0f / (TEMPO_F * 48.0f)); + uint16_t delay = (delayF >= 65535.0f) ? 0x7FFF : (uint16_t)delayF; + + Ship::BinaryWriter writer; + writer.SetEndianness(Ship::Endianness::Big); + if (stereo) { + WriteStereoSingleSeq(&writer, delay, TEMPO, looped); + } else { + WriteMonoSingleSeq(&writer, delay, TEMPO, looped); + } + + auto vec = writer.ToVector(); + seq->mSequence.seqDataSize = vec.size(); + seq->mBuffer.resize(vec.size()); + memcpy(seq->mBuffer.data(), vec.data(), vec.size()); + seq->mSequence.seqData = seq->mBuffer.data(); + } + } + + SF64::AudioDebug_RegisterSequence(seq->mSequence.seqNumber, initData->Path); + return seq; +} + +} // namespace SF64 diff --git a/src/port/resource/importers/audio/SequenceFactory.h b/src/port/resource/importers/audio/SequenceFactory.h new file mode 100644 index 000000000..6bd1ed9e2 --- /dev/null +++ b/src/port/resource/importers/audio/SequenceFactory.h @@ -0,0 +1,25 @@ +#pragma once + +#include +#include +#include +#include "port/resource/type/audio/Sequence.h" +#include "SoundFontFactory.h" + +namespace SF64 { + +class ResourceFactoryBinarySequenceV2 : public Ship::ResourceFactoryBinary { + public: + virtual ~ResourceFactoryBinarySequenceV2() = default; + std::shared_ptr ReadResource(std::shared_ptr file, + std::shared_ptr initData) override; +}; + +class ResourceFactoryXMLSequenceV0 : public Ship::ResourceFactoryXML { + public: + virtual ~ResourceFactoryXMLSequenceV0() = default; + std::shared_ptr ReadResource(std::shared_ptr file, + std::shared_ptr initData) override; +}; + +} // namespace SF64 diff --git a/src/port/resource/importers/audio/SoundFontFactory.cpp b/src/port/resource/importers/audio/SoundFontFactory.cpp index c3d16d0f4..556a0f431 100644 --- a/src/port/resource/importers/audio/SoundFontFactory.cpp +++ b/src/port/resource/importers/audio/SoundFontFactory.cpp @@ -1,9 +1,10 @@ #include "SoundFontFactory.h" #include "../ResourceUtil.h" -#include "utils/StringHelper.h" + +#include +#include #include #include "port/resource/type/audio/SoundFont.h" -#include namespace SF64 { std::shared_ptr ResourceFactoryBinarySoundFontV0::ReadResource(std::shared_ptr file, diff --git a/src/port/resource/importers/audio/SoundFontFactory.h b/src/port/resource/importers/audio/SoundFontFactory.h index 69796b1db..1b7211663 100644 --- a/src/port/resource/importers/audio/SoundFontFactory.h +++ b/src/port/resource/importers/audio/SoundFontFactory.h @@ -1,8 +1,8 @@ #pragma once -#include "Resource.h" -#include "ResourceFactoryXML.h" -#include "ResourceFactoryBinary.h" +#include +#include +#include #include "port/resource/type/audio/SoundFont.h" namespace SF64 { diff --git a/src/port/resource/loaders/AudioLoader.cpp b/src/port/resource/loaders/AudioLoader.cpp index 6db4a3121..b5fca9003 100644 --- a/src/port/resource/loaders/AudioLoader.cpp +++ b/src/port/resource/loaders/AudioLoader.cpp @@ -1,10 +1,6 @@ -#include "AudioLoader.h" -#include "utils/binarytools/BinaryReader.h" -#include "assets/ast_audio.h" -#include "BitConverter.h" #include "port/Engine.h" +#include "AudioLoader.h" #include -#include #include #ifdef OTR_AUDIO diff --git a/src/port/resource/type/Animation.h b/src/port/resource/type/Animation.h index de08a14f4..942e7855e 100644 --- a/src/port/resource/type/Animation.h +++ b/src/port/resource/type/Animation.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include #include namespace SF64 { diff --git a/src/port/resource/type/ColPoly.h b/src/port/resource/type/ColPoly.h index c64e18e30..bba826bc2 100644 --- a/src/port/resource/type/ColPoly.h +++ b/src/port/resource/type/ColPoly.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include #include namespace SF64 { diff --git a/src/port/resource/type/EnvSettings.h b/src/port/resource/type/EnvSettings.h index 6f50e7955..5a2704dec 100644 --- a/src/port/resource/type/EnvSettings.h +++ b/src/port/resource/type/EnvSettings.h @@ -3,7 +3,7 @@ #include "Limb.h" #include -#include +#include namespace SF64 { diff --git a/src/port/resource/type/GenericArray.h b/src/port/resource/type/GenericArray.h index d28d9b68e..18aebd033 100644 --- a/src/port/resource/type/GenericArray.h +++ b/src/port/resource/type/GenericArray.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include #include namespace SF64 { diff --git a/src/port/resource/type/Hitbox.h b/src/port/resource/type/Hitbox.h index c3ab987d7..6983eb5a5 100644 --- a/src/port/resource/type/Hitbox.h +++ b/src/port/resource/type/Hitbox.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include namespace SF64 { class Hitbox : public Ship::Resource { diff --git a/src/port/resource/type/Limb.h b/src/port/resource/type/Limb.h index 2a485834b..a50f2237a 100644 --- a/src/port/resource/type/Limb.h +++ b/src/port/resource/type/Limb.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include namespace SF64 { diff --git a/src/port/resource/type/Message.h b/src/port/resource/type/Message.h index fd456fbef..31b92e7df 100644 --- a/src/port/resource/type/Message.h +++ b/src/port/resource/type/Message.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include #include namespace SF64 { diff --git a/src/port/resource/type/ObjectInit.h b/src/port/resource/type/ObjectInit.h index 3e57240c6..4fa799c3e 100644 --- a/src/port/resource/type/ObjectInit.h +++ b/src/port/resource/type/ObjectInit.h @@ -3,7 +3,7 @@ #include "Limb.h" #include -#include +#include namespace SF64 { diff --git a/src/port/resource/type/Script.h b/src/port/resource/type/Script.h index b04cbea16..2d9f4b5d2 100644 --- a/src/port/resource/type/Script.h +++ b/src/port/resource/type/Script.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include namespace SF64 { class Script : public Ship::Resource { diff --git a/src/port/resource/type/Skeleton.h b/src/port/resource/type/Skeleton.h index 51b521bfd..1e1116f72 100644 --- a/src/port/resource/type/Skeleton.h +++ b/src/port/resource/type/Skeleton.h @@ -2,7 +2,7 @@ #include "Limb.h" -#include +#include namespace SF64 { class Skeleton : public Ship::Resource { diff --git a/src/port/resource/type/Vec3fArray.h b/src/port/resource/type/Vec3fArray.h index 1fc3d3543..daf85befc 100644 --- a/src/port/resource/type/Vec3fArray.h +++ b/src/port/resource/type/Vec3fArray.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include #include namespace SF64 { diff --git a/src/port/resource/type/Vec3sArray.h b/src/port/resource/type/Vec3sArray.h index 8ee88f197..fbc0347bd 100644 --- a/src/port/resource/type/Vec3sArray.h +++ b/src/port/resource/type/Vec3sArray.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include #include namespace SF64 { diff --git a/src/port/resource/type/audio/AdpcmBook.h b/src/port/resource/type/audio/AdpcmBook.h index 45b7cc2f4..c708dcbd5 100644 --- a/src/port/resource/type/audio/AdpcmBook.h +++ b/src/port/resource/type/audio/AdpcmBook.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include namespace SF64 { struct AdpcmBookData { diff --git a/src/port/resource/type/audio/AdpcmLoop.h b/src/port/resource/type/audio/AdpcmLoop.h index 856507543..02d133db2 100644 --- a/src/port/resource/type/audio/AdpcmLoop.h +++ b/src/port/resource/type/audio/AdpcmLoop.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include namespace SF64 { struct AdpcmLoopData { diff --git a/src/port/resource/type/audio/AudioTable.h b/src/port/resource/type/audio/AudioTable.h index f29268940..22280d984 100644 --- a/src/port/resource/type/audio/AudioTable.h +++ b/src/port/resource/type/audio/AudioTable.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include namespace SF64 { struct AudioTableBase { diff --git a/src/port/resource/type/audio/Drum.h b/src/port/resource/type/audio/Drum.h index 44966cd87..3012660a2 100644 --- a/src/port/resource/type/audio/Drum.h +++ b/src/port/resource/type/audio/Drum.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include #include "Envelope.h" #include "AudioContext.h" diff --git a/src/port/resource/type/audio/Envelope.h b/src/port/resource/type/audio/Envelope.h index b2086cae9..0b069650a 100644 --- a/src/port/resource/type/audio/Envelope.h +++ b/src/port/resource/type/audio/Envelope.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include namespace SF64 { diff --git a/src/port/resource/type/audio/Instrument.h b/src/port/resource/type/audio/Instrument.h index 40b00391a..e48242ea0 100644 --- a/src/port/resource/type/audio/Instrument.h +++ b/src/port/resource/type/audio/Instrument.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include #include "Envelope.h" #include "AudioContext.h" diff --git a/src/port/resource/type/audio/Sample.h b/src/port/resource/type/audio/Sample.h index c45854599..c5deeef78 100644 --- a/src/port/resource/type/audio/Sample.h +++ b/src/port/resource/type/audio/Sample.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include #include "Envelope.h" #include "AdpcmLoop.h" #include "AdpcmBook.h" @@ -12,11 +12,14 @@ struct SampleData { uint32_t medium : 2; uint32_t unk : 1; uint32_t isRelocated : 1; - uint32_t size : 24; + uint32_t size; uint8_t* sampleAddr; AdpcmLoopData* loop; AdpcmBookData* book; float tuning = 0.0f; + uint32_t channels = 1; + uint32_t sampleRate = 32000; + uint32_t numFrames = 0; }; class Sample : public Ship::Resource { diff --git a/src/port/resource/type/audio/Sequence.cpp b/src/port/resource/type/audio/Sequence.cpp new file mode 100644 index 000000000..7ba5fd51b --- /dev/null +++ b/src/port/resource/type/audio/Sequence.cpp @@ -0,0 +1,11 @@ +#include "Sequence.h" + +namespace SF64 { +SequenceData* Sequence::GetPointer() { + return reinterpret_cast(mBuffer.data()); +} + +size_t Sequence::GetPointerSize() { + return mBuffer.size(); +} +} // namespace SF64 diff --git a/src/port/resource/type/audio/Sequence.h b/src/port/resource/type/audio/Sequence.h new file mode 100644 index 000000000..df237a248 --- /dev/null +++ b/src/port/resource/type/audio/Sequence.h @@ -0,0 +1,30 @@ +#pragma once + +#include +#include +#include + +namespace SF64 { +struct SequenceData { + uint32_t seqDataSize; + char* seqData; + uint8_t seqNumber; + uint8_t medium; + uint8_t cachePolicy; + uint32_t numFonts; + uint8_t fonts[16]; +}; + +class Sequence : public Ship::Resource { + public: + using Resource::Resource; + + Sequence() : Resource(std::shared_ptr()) {} + + SequenceData* GetPointer(); + size_t GetPointerSize(); + + SequenceData mSequence; + std::vector mBuffer; +}; +} // namespace SF64 diff --git a/src/port/resource/type/audio/SoundFont.h b/src/port/resource/type/audio/SoundFont.h index 2801e2545..bea186327 100644 --- a/src/port/resource/type/audio/SoundFont.h +++ b/src/port/resource/type/audio/SoundFont.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include #include "Instrument.h" #include "Drum.h" diff --git a/src/port/ui/AudioDebugWindow.cpp b/src/port/ui/AudioDebugWindow.cpp new file mode 100644 index 000000000..f38e50dc6 --- /dev/null +++ b/src/port/ui/AudioDebugWindow.cpp @@ -0,0 +1,1456 @@ +#include "AudioDebugWindow.h" +#include "port/audio/AudioDebug.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern "C" { +#include +#include +#include +#include +#include +} + +namespace SF64 { + +// ── Name tables ────────────────────────────────────────────────────────────── + +static const char* CodecName(int codec) { + switch (codec) { + case CODEC_ADPCM: return "ADPCM"; + case CODEC_S8: return "S8"; + case CODEC_S16_INMEMORY: return "S16_INMEMORY"; + case CODEC_SMALL_ADPCM: return "SMALL_ADPCM"; + case CODEC_REVERB: return "REVERB"; + case CODEC_S16: return "S16"; + default: return "UNKNOWN"; + } +} + +static const char* SeqIdName(int id) { + switch (id) { + case SEQ_ID_SFX: return "SFX"; + case SEQ_ID_VOICE: return "VOICE"; + case SEQ_ID_CORNERIA: return "CORNERIA"; + case SEQ_ID_METEO: return "METEO"; + case SEQ_ID_TITANIA: return "TITANIA"; + case SEQ_ID_SECTOR_X: return "SECTOR X"; + case SEQ_ID_ZONESS: return "ZONESS"; + case SEQ_ID_AREA_6: return "AREA 6"; + case SEQ_ID_VENOM_1: return "VENOM 1"; + case SEQ_ID_SECTOR_Y: return "SECTOR Y"; + case SEQ_ID_FORTUNA: return "FORTUNA"; + case SEQ_ID_SOLAR: return "SOLAR"; + case SEQ_ID_BOLSE: return "BOLSE"; + case SEQ_ID_KATINA: return "KATINA"; + case SEQ_ID_AQUAS: return "AQUAS"; + case SEQ_ID_SECTOR_Z: return "SECTOR Z"; + case SEQ_ID_MACBETH: return "MACBETH"; + case SEQ_ID_ANDROSS: return "ANDROSS"; + case SEQ_ID_BOSS_CO_1: return "BOSS CO 1"; + case SEQ_ID_BOSS_ME: return "BOSS ME"; + case SEQ_ID_BOSS_TI: return "BOSS TI"; + case SEQ_ID_BOSS_SX: return "BOSS SX"; + case SEQ_ID_BOSS_ZO: return "BOSS ZO"; + case SEQ_ID_BOSS_A6: return "BOSS A6"; + case SEQ_ID_BOSS_VE: return "BOSS VE"; + case SEQ_ID_BOSS_SY: return "BOSS SY"; + case SEQ_ID_UNK_26: return "UNK_26"; + case SEQ_ID_BOSS_SO: return "BOSS SO"; + case SEQ_ID_BOSS_BO: return "BOSS BO"; + case SEQ_ID_BOSS_KA: return "BOSS KA"; + case SEQ_ID_BOSS_AQ: return "BOSS AQ"; + case SEQ_ID_BOSS_SZ: return "BOSS SZ"; + case SEQ_ID_BOSS_MA: return "BOSS MA"; + case SEQ_ID_BOSS_ANDROSS: return "BOSS ANDROSS"; + case SEQ_ID_TITLE: return "TITLE"; + case SEQ_ID_OPENING: return "OPENING"; + case SEQ_ID_MENU: return "MENU"; + case SEQ_ID_CO_INTRO: return "CO_INTRO"; + case SEQ_ID_GOOD_END: return "GOOD END"; + case SEQ_ID_DEATH: return "DEATH"; + case SEQ_ID_GAME_OVER: return "GAME OVER"; + case SEQ_ID_UNK_41: return "UNK_41"; + case SEQ_ID_STAFF_ROLL: return "STAFF ROLL"; + case SEQ_ID_STAR_WOLF: return "STAR WOLF"; + case SEQ_ID_INTRO_S: return "INTRO S"; + case SEQ_ID_INTRO_M: return "INTRO M"; + case SEQ_ID_VERSUS: return "VERSUS"; + case SEQ_ID_VS_HURRY: return "VS HURRY"; + case SEQ_ID_BOSS_CO_2: return "BOSS CO 2"; + case SEQ_ID_BAD_END: return "BAD END"; + case SEQ_ID_ME_INTRO: return "ME_INTRO"; + case SEQ_ID_INTRO_51: return "INTRO_51"; + case SEQ_ID_UNK_52: return "UNK_52"; + case SEQ_ID_UNK_53: return "UNK_53"; + case SEQ_ID_KATT: return "KATT"; + case SEQ_ID_BILL: return "BILL"; + case SEQ_ID_VS_MENU: return "VS_MENU"; + case SEQ_ID_UNK_57: return "UNK_57"; + case SEQ_ID_WARP_ZONE: return "WARP ZONE"; + case SEQ_ID_UNK_59: return "UNK_59"; + case SEQ_ID_WORLD_MAP: return "WORLD MAP"; + case SEQ_ID_AND_BRAIN: return "AND BRAIN"; + case SEQ_ID_TO_ANDROSS: return "TO ANDROSS"; + case SEQ_ID_TRAINING: return "TRAINING"; + case SEQ_ID_VE_CLEAR: return "VE CLEAR"; + case SEQ_ID_BOSS_RESUME: return "BOSS RESUME"; + case SEQ_ID_VOICE_LYLAT: return "VOICE LYLAT"; + case 0xFFFF: return "NONE"; + default: return "?"; + } +} + +static const char* SeqPlayerName(int idx) { + switch (idx) { + case SEQ_PLAYER_BGM: return "BGM"; + case SEQ_PLAYER_FANFARE: return "FANFARE"; + case SEQ_PLAYER_SFX: return "SFX"; + case SEQ_PLAYER_VOICE: return "VOICE"; + default: return "?"; + } +} + +static const char* SoundModeName(int m) { + switch (m) { + case SOUNDMODE_STEREO: return "Stereo"; + case SOUNDMODE_HEADSET: return "Headset"; + case SOUNDMODE_SURROUND:return "Surround"; + case SOUNDMODE_MONO: return "Mono"; + default: return "?"; + } +} + +static const char* AudioSpecName(int id) { + switch (id) { + case AUDIOSPEC_CO: return "CO (Corneria)"; + case AUDIOSPEC_ME: return "ME (Meteo)"; + case AUDIOSPEC_TI: return "TI (Titania)"; + case AUDIOSPEC_SX: return "SX (Sector X)"; + case AUDIOSPEC_ZO: return "ZO (Zoness)"; + case AUDIOSPEC_A6: return "A6 (Area 6)"; + case AUDIOSPEC_SY: return "SY (Sector Y)"; + case AUDIOSPEC_FO: return "FO (Fortuna)"; + case AUDIOSPEC_SO: return "SO (Solar)"; + case AUDIOSPEC_BO: return "BO (Bolse)"; + case AUDIOSPEC_KA: return "KA (Katina)"; + case AUDIOSPEC_AQ: return "AQ (Aquas)"; + case AUDIOSPEC_SZ: return "SZ (Sector Z)"; + case AUDIOSPEC_MA: return "MA (Macbeth)"; + default: { + static char buf[16]; + snprintf(buf, sizeof(buf), "%d", id); + return buf; + } + } +} + +// ── Helpers ────────────────────────────────────────────────────────────────── + +static void HelpMarker(const char* desc) { + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) { + ImGui::BeginTooltip(); + ImGui::TextUnformatted(desc); + ImGui::EndTooltip(); + } +} + +static s32 DrawPoolBar(const char* label, const AudioAllocPool& pool) { + if (pool.size <= 0) return 0; + s32 used = (s32)(pool.curRamAddr - pool.startRamAddr); + if (used < 0) used = 0; + float frac = (float)used / (float)pool.size; + char overlay[64]; + snprintf(overlay, sizeof(overlay), "%d / %d KB", used / 1024, pool.size / 1024); + ImVec4 col = (frac < 0.6f) ? ImVec4(0.2f, 0.8f, 0.2f, 1.f) + : (frac < 0.85f)? ImVec4(0.9f, 0.75f, 0.1f, 1.f) + : ImVec4(0.9f, 0.2f, 0.2f, 1.f); + ImGui::PushStyleColor(ImGuiCol_PlotHistogram, col); + ImGui::ProgressBar(frac, ImVec2(-1.f, 0.f), overlay); + ImGui::PopStyleColor(); + return used; +} + +// ── Module toggle button (coloured by visibility state) ────────────────────── +static void ModuleToggle(const char* label, bool* pVisible) { + if (*pVisible) + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.2f, 0.5f, 0.2f, 1.f)); + else + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.25f, 0.25f, 0.25f, 1.f)); + if (ImGui::Button(label, ImVec2(120.f, 0.f))) + *pVisible = !*pVisible; + ImGui::PopStyleColor(); +} + +// ── Main draw ──────────────────────────────────────────────────────────────── + +void AudioDebugWindow::DrawElement() { + + // Persistent visibility flags for each detachable module + static bool sShow_PCMCapture = false; + static bool sShow_ChanMute = false; + static bool sShow_SeqPlayers = false; + static bool sShow_Sequences = false; + static bool sShow_ActiveNotes = false; + static bool sShow_ChanStats = false; + static bool sShow_Polyphony = false; + static bool sShow_Reverb = false; + static bool sShow_AudioHeap = false; + static bool sShow_System = false; + static bool sShow_SampleInfo = false; + + // ── Frame Step (always in main window) ─────────────────────────────────── + { + bool stepping = SF64::gAudioStepMode.load(std::memory_order_acquire); + uint64_t frameCount = SF64::gAudioFrameCount.load(std::memory_order_relaxed); + + { + bool wasStepping = stepping; + if (wasStepping) + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.7f, 0.2f, 0.2f, 1.f)); + if (ImGui::Button(wasStepping ? "Resume Audio" : "Pause Audio")) { + stepping = !stepping; + SF64::gAudioStepMode.store(stepping, std::memory_order_release); + if (!stepping) + SF64::gAudioStepOnce.store(false, std::memory_order_release); + } + if (wasStepping) ImGui::PopStyleColor(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(stepping + ? "Audio synthesis is PAUSED — game keeps running, silence output.\nClick to resume." + : "Click to pause audio synthesis for frame-by-frame stepping.\nGame keeps running."); + + ImGui::SameLine(); + { + if (!stepping) ImGui::BeginDisabled(); + if (ImGui::Button("Step Frame")) + SF64::gAudioStepOnce.store(true, std::memory_order_release); + if (!stepping) ImGui::EndDisabled(); + } + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + ImGui::SetTooltip("Run audio synthesis for exactly one frame.\nPause the driver first."); + + ImGui::SameLine(); + static int sStepN = 10; + ImGui::SetNextItemWidth(52.f); + ImGui::InputInt("##stepN", &sStepN, 1, 10); + if (sStepN < 1) sStepN = 1; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Number of frames to advance.\nUse +/- or type a value."); + ImGui::SameLine(); + { + if (!stepping) ImGui::BeginDisabled(); + char stepLabel[32]; + snprintf(stepLabel, sizeof(stepLabel), "Step %d", sStepN); + if (ImGui::Button(stepLabel)) + SF64::gAudioStepN.fetch_add(sStepN, std::memory_order_release); + if (!stepping) ImGui::EndDisabled(); + } + + int remaining = SF64::gAudioStepN.load(std::memory_order_relaxed); + if (remaining > 0) { + ImGui::SameLine(); + ImGui::TextColored(ImVec4(1.f, 0.8f, 0.2f, 1.f), "%d left", remaining); + } + + ImGui::SameLine(); + ImGui::Spacing(); ImGui::SameLine(); + if (stepping) { + ImGui::TextColored(ImVec4(1.f, 0.4f, 0.4f, 1.f), + "[PAUSED] frame %" PRIu64, frameCount); + } else { + ImGui::TextDisabled("frame %" PRIu64, frameCount); + } + } + ImGui::Separator(); + + // ── Module toggle grid ─────────────────────────────────────────────────── + ImGui::TextDisabled("Modules:"); + ModuleToggle("PCM Capture", &sShow_PCMCapture); ImGui::SameLine(); + ModuleToggle("Chan Mute", &sShow_ChanMute); ImGui::SameLine(); + ModuleToggle("Seq Players", &sShow_SeqPlayers); ImGui::SameLine(); + ModuleToggle("Sequences", &sShow_Sequences); + ModuleToggle("Active Notes", &sShow_ActiveNotes); ImGui::SameLine(); + ModuleToggle("Chan Stats", &sShow_ChanStats); ImGui::SameLine(); + ModuleToggle("Polyphony", &sShow_Polyphony); ImGui::SameLine(); + ModuleToggle("Reverb", &sShow_Reverb); + ModuleToggle("Audio Heap", &sShow_AudioHeap); ImGui::SameLine(); + ModuleToggle("System", &sShow_System); ImGui::SameLine(); + ModuleToggle("Sample Info", &sShow_SampleInfo); + + // ── PCM Capture ────────────────────────────────────────────────────────── + if (sShow_PCMCapture) { + ImGui::SetNextWindowSize(ImVec2(450, 175), ImGuiCond_FirstUseEver); + if (ImGui::Begin("PCM Capture##sf64ad", &sShow_PCMCapture)) { + static char sRecPathBuf[512] = "audio_capture.raw"; + ImGui::SetNextItemWidth(340.f); + ImGui::InputText("Output file##recpath", sRecPathBuf, sizeof(sRecPathBuf)); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Raw signed 16-bit little-endian PCM.\n" + "Import in Audacity with:\n" + " File > Import > Raw Data\n" + " Encoding: Signed 16-bit PCM\n" + " Byte order: Little-endian\n" + " Channels: 2 (stereo)"); + + ImGui::Spacing(); + + bool isRecording = SF64::gAudioRecording.load(std::memory_order_acquire); + bool isPaused = SF64::gAudioRecordPaused.load(std::memory_order_acquire); + uint64_t bytes = SF64::gAudioRecordBytes.load(std::memory_order_relaxed); + + if (!isRecording) { + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.15f, 0.55f, 0.15f, 1.f)); + if (ImGui::Button("Record")) { + { + std::lock_guard lk(SF64::gAudioRecordMutex); + SF64::gAudioRecordPath = sRecPathBuf; + } + SF64::gAudioRecordPaused.store(false, std::memory_order_release); + SF64::gAudioSaveAndStop.store(false, std::memory_order_release); + SF64::gAudioRecording.store(true, std::memory_order_release); + } + ImGui::PopStyleColor(); + } else { + { + bool wasPaused = isPaused; + if (wasPaused) + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.6f, 0.45f, 0.1f, 1.f)); + if (ImGui::Button(wasPaused ? "Resume" : "Pause")) { + SF64::gAudioRecordPaused.store(!isPaused, std::memory_order_release); + } + if (wasPaused) ImGui::PopStyleColor(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(isPaused ? "Resume writing PCM to file." + : "Pause writing — keeps file open, no data lost."); + + ImGui::SameLine(); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.6f, 0.1f, 0.1f, 1.f)); + if (ImGui::Button("Save & Stop")) { + SF64::gAudioSaveAndStop.store(true, std::memory_order_release); + } + ImGui::PopStyleColor(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Flush and close the output file, then stop recording."); + } + + ImGui::SameLine(); + ImGui::Spacing(); ImGui::SameLine(); + if (isRecording) { + double mb = bytes / (1024.0 * 1024.0); + if (isPaused) + ImGui::TextColored(ImVec4(1.f, 0.7f, 0.1f, 1.f), + "[PAUSED] %.2f MB captured", mb); + else + ImGui::TextColored(ImVec4(0.3f, 1.f, 0.3f, 1.f), + "[REC] %.2f MB", mb); + } else { + ImGui::TextDisabled("idle"); + } + } + ImGui::End(); + } + + // ── Channel Mute ───────────────────────────────────────────────────────── + if (sShow_ChanMute) { + ImGui::SetNextWindowSize(ImVec2(460, 130), ImGuiCond_FirstUseEver); + if (ImGui::Begin("Channel Mute##sf64ad", &sShow_ChanMute)) { + if (ImGui::Button("Mute All")) { + for (int i = 0; i < SF64::kNumSeqChannels; i++) + SF64::gMutedChannels[i].store(true, std::memory_order_relaxed); + } + ImGui::SameLine(); + if (ImGui::Button("Unmute All")) { + for (int i = 0; i < SF64::kNumSeqChannels; i++) + SF64::gMutedChannels[i].store(false, std::memory_order_relaxed); + } + ImGui::Spacing(); + + for (int i = 0; i < SF64::kNumSeqChannels; i++) { + if (i > 0 && i % 8 == 0) ImGui::NewLine(); + else if (i > 0) ImGui::SameLine(); + + bool muted = SF64::gMutedChannels[i].load(std::memory_order_relaxed); + if (muted) ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.7f, 0.15f, 0.15f, 1.f)); + char label[8]; + snprintf(label, sizeof(label), "Ch %d", i); + if (ImGui::Button(label, ImVec2(52.f, 0.f))) + SF64::gMutedChannels[i].store(!muted, std::memory_order_relaxed); + if (muted) ImGui::PopStyleColor(); + if (ImGui::IsItemHovered()) { + ImGui::BeginTooltip(); + ImGui::Text("Channel %d — %s\nClick to %s", i, + muted ? "MUTED" : "active", + muted ? "unmute" : "mute"); + ImGui::EndTooltip(); + } + } + ImGui::NewLine(); + } + ImGui::End(); + } + + // ── Sequence Players ───────────────────────────────────────────────────── + if (sShow_SeqPlayers) { + static float sVolScale[SEQ_PLAYER_MAX] = {1.f, 1.f, 1.f, 1.f}; + static int sTempoDelta[SEQ_PLAYER_MAX] = {0, 0, 0, 0}; + static int sTranspose[SEQ_PLAYER_MAX] = {0, 0, 0, 0}; + + ImGui::SetNextWindowSize(ImVec2(480, 520), ImGuiCond_FirstUseEver); + if (ImGui::Begin("Sequence Players##sf64ad", &sShow_SeqPlayers)) { + for (int pi = 0; pi < SEQ_PLAYER_MAX; pi++) { + const SequencePlayer& p = gSeqPlayers[pi]; + + ImVec4 nameCol = p.enabled + ? ImVec4(0.4f, 1.f, 0.4f, 1.f) + : ImVec4(0.5f, 0.5f, 0.5f, 1.f); + ImGui::TextColored(nameCol, "[%d] %s", pi, SeqPlayerName(pi)); + ImGui::SameLine(); + ImGui::TextDisabled("state=%d", p.state); + + if (!p.enabled) { ImGui::Separator(); continue; } + + ImGui::Columns(2, nullptr, false); + ImGui::SetColumnWidth(0, 160.f); + +#define ROW(lbl, ...) do { ImGui::TextDisabled(lbl); ImGui::NextColumn(); ImGui::Text(__VA_ARGS__); ImGui::NextColumn(); } while(0) + ROW("Sequence", "%s (id %u)", SeqIdName(p.seqId), (unsigned)p.seqId); + ROW("Volume", "%.3f (fade %.3f applied %.3f)", + p.volume, p.fadeVolume, p.appliedFadeVolume); + ROW("Tempo", "%u ticks/min (change %+d)", (unsigned)p.tempo, (int)p.tempoChange); + ROW("Transpose", "%+d semitones", (int)p.transposition); + ROW("Fade Timer", "%u ticks", (unsigned)p.fadeTimer); + ROW("Muted", "%s", p.muted ? "YES" : "no"); +#undef ROW + ImGui::Columns(1); + + ImGui::Spacing(); + ImGui::PushID(pi); + + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.7f, 0.15f, 0.15f, 1.f)); + if (ImGui::Button("Stop")) { + AUDIOCMD_GLOBAL_DISABLE_SEQPLAYER(pi, 20); + } + ImGui::PopStyleColor(); + ImGui::SameLine(); HelpMarker("Fade out and disable this sequence player (20 tick fade)."); + + ImGui::SameLine(); + if (ImGui::Button("Silence")) { + AUDIOCMD_SEQPLAYER_FADE_TO_SET_VOLUME(pi, 0, 0); + } + ImGui::SameLine(); HelpMarker("Instantly set volume to 0 (player stays running)."); + + ImGui::SameLine(); + if (ImGui::Button("Restore Vol")) { + sVolScale[pi] = 1.f; + AUDIOCMD_SEQPLAYER_FADE_VOLUME_SCALE(pi, 1.f); + } + ImGui::SameLine(); HelpMarker("Reset volume scale to 1.0."); + + ImGui::SetNextItemWidth(200.f); + if (ImGui::SliderFloat("Vol Scale", &sVolScale[pi], 0.f, 2.f, "%.2f")) { + AUDIOCMD_SEQPLAYER_FADE_VOLUME_SCALE(pi, sVolScale[pi]); + } + ImGui::SameLine(); HelpMarker("Multiplicative volume scale (1.0 = normal)."); + + ImGui::SetNextItemWidth(200.f); + if (ImGui::SliderInt("Tempo +/-", &sTempoDelta[pi], -300, 300)) { + AUDIOCMD_SEQPLAYER_CHANGE_TEMPO(pi, sTempoDelta[pi]); + } + ImGui::SameLine(); + if (ImGui::Button("Reset##tempo")) { + AUDIOCMD_SEQPLAYER_CHANGE_TEMPO(pi, -sTempoDelta[pi]); + sTempoDelta[pi] = 0; + } + ImGui::SameLine(); HelpMarker("Add a BPM delta on top of the sequence's native tempo."); + + ImGui::SetNextItemWidth(200.f); + if (ImGui::SliderInt("Transpose", &sTranspose[pi], -24, 24)) { + AUDIOCMD_SEQPLAYER_SET_TRANSPOSITION(pi, (s8)sTranspose[pi]); + } + ImGui::SameLine(); + if (ImGui::Button("Reset##tr")) { + sTranspose[pi] = 0; + AUDIOCMD_SEQPLAYER_SET_TRANSPOSITION(pi, 0); + } + ImGui::SameLine(); HelpMarker("Shift all notes on this player up/down by semitones."); + + ImGui::PopID(); + ImGui::Separator(); + } + } + ImGui::End(); + } + + // ── Sequences ──────────────────────────────────────────────────────────── + if (sShow_Sequences) { + static int sSeqSelPlayer = 0; + static int sSeqSelId = 2; + static bool sSeqDisasmDirty = true; + static std::string sSeqDisasm; + + ImGui::SetNextWindowSize(ImVec2(620, 560), ImGuiCond_FirstUseEver); + if (ImGui::Begin("Sequences##sf64ad", &sShow_Sequences)) { + // Player picker + ImGui::AlignTextToFramePadding(); + ImGui::TextDisabled("Player:"); ImGui::SameLine(); + for (int pi = 0; pi < SEQ_PLAYER_MAX; pi++) { + if (pi > 0) ImGui::SameLine(); + char plabel[32]; + snprintf(plabel, sizeof(plabel), "%s##seqpl%d", SeqPlayerName(pi), pi); + if (ImGui::RadioButton(plabel, &sSeqSelPlayer, pi)) {} + } + + ImGui::Spacing(); + + static ImGuiTextFilter sSeqFilter; + sSeqFilter.Draw("Filter##seqfilter", 200.f); + ImGui::SameLine(); HelpMarker("Filter sequence list by name, id, or path."); + + if (ImGui::BeginTable("##seqlist", 4, + ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | + ImGuiTableFlags_ScrollY | ImGuiTableFlags_SizingFixedFit, + ImVec2(0.f, 220.f))) { + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn("ID", ImGuiTableColumnFlags_WidthFixed, 36.f); + ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed, 120.f); + ImGui::TableSetupColumn("Path", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 80.f); + ImGui::TableHeadersRow(); + + for (int id = 0; id < SEQ_ID_MAX; id++) { + const char* name = SeqIdName(id); + const std::string& seqPath = AudioDebug_GetSeqPath((uint8_t)id); + char idstr[8]; + snprintf(idstr, sizeof(idstr), "%d", id); + if (!sSeqFilter.PassFilter(name) && + !sSeqFilter.PassFilter(idstr) && + !sSeqFilter.PassFilter(seqPath.c_str())) + continue; + + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + bool sel = (sSeqSelId == id); + if (sel) ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.4f, 1.f, 0.4f, 1.f)); + if (ImGui::Selectable(idstr, sel, + ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowOverlap, + ImVec2(0.f, 0.f))) { + if (sSeqSelId != id) { sSeqSelId = id; sSeqDisasmDirty = true; } + } + if (sel) ImGui::PopStyleColor(); + + ImGui::TableSetColumnIndex(1); + ImGui::TextUnformatted(name); + + ImGui::TableSetColumnIndex(2); + if (seqPath.empty()) { + ImGui::TextDisabled("—"); + } else { + const char* slash = strrchr(seqPath.c_str(), '/'); + ImGui::TextUnformatted(slash ? slash + 1 : seqPath.c_str()); + if (ImGui::IsItemHovered()) { + ImGui::BeginTooltip(); + ImGui::TextUnformatted(seqPath.c_str()); + ImGui::EndTooltip(); + } + } + + ImGui::TableSetColumnIndex(3); + ImGui::PushID(id); + const SequencePlayer& liveP = gSeqPlayers[sSeqSelPlayer]; + bool isPlaying = liveP.enabled && ((int)liveP.seqId == id); + if (isPlaying) + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.15f, 0.55f, 0.15f, 1.f)); + if (ImGui::SmallButton(isPlaying ? "■ Stop" : "▶ Play")) { + if (isPlaying) { + AUDIOCMD_GLOBAL_DISABLE_SEQPLAYER(sSeqSelPlayer, 10); + } else { + AUDIOCMD_GLOBAL_INIT_SEQPLAYER(sSeqSelPlayer, id, 0, 0); + } + sSeqDisasmDirty = true; + } + if (isPlaying) ImGui::PopStyleColor(); + ImGui::PopID(); + } + ImGui::EndTable(); + } + + ImGui::Spacing(); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.55f, 0.1f, 0.1f, 1.f)); + if (ImGui::Button("Stop Player")) { + AUDIOCMD_GLOBAL_DISABLE_SEQPLAYER(sSeqSelPlayer, 10); + } + ImGui::PopStyleColor(); + ImGui::SameLine(); HelpMarker("Stop the selected sequence player with a short fade-out."); + + ImGui::Separator(); + + ImGui::TextDisabled("Bytecode disassembly"); + ImGui::SameLine(); + if (ImGui::SmallButton("Refresh##seqdis")) sSeqDisasmDirty = true; + ImGui::SameLine(); HelpMarker( + "Disassembles the raw N64 sequence bytecode for the selected sequence ID.\n" + "The disassembly follows audio_seqplayer.c opcode dispatch tables.\n" + "Click Refresh after changing the selected sequence."); + + if (sSeqDisasmDirty) { + sSeqDisasm.clear(); + sSeqDisasmDirty = false; + + const SequencePlayer* src = nullptr; + for (int pi = 0; pi < SEQ_PLAYER_MAX; pi++) { + if (gSeqPlayers[pi].enabled && (int)gSeqPlayers[pi].seqId == sSeqSelId) { + src = &gSeqPlayers[pi]; + break; + } + } + if (!src && gSeqPlayers[sSeqSelPlayer].enabled) + src = &gSeqPlayers[sSeqSelPlayer]; + + if (src && src->seqData != nullptr) { + const uint8_t* d = reinterpret_cast(src->seqData); + size_t sz = 65536; + char linebuf[256]; + + snprintf(linebuf, sizeof(linebuf), + "seqId: %u seqData: %p\n\n", (unsigned)src->seqId, (const void*)src->seqData); + sSeqDisasm += linebuf; + + size_t pc = 0; + int iter = 0; + while (pc < sz && iter < 256) { + iter++; + size_t opc = pc; + uint8_t cmd = d[pc++]; + + const char* mnem = nullptr; + char args[128] = ""; + + auto rdU8 = [&]() -> uint8_t { return (pc < sz) ? d[pc++] : 0; }; + auto rdS8 = [&]() -> int8_t { return (int8_t)rdU8(); }; + auto rdU16 = [&]() -> uint16_t { + uint8_t hi = rdU8(), lo = rdU8(); + return (uint16_t)((hi << 8) | lo); + }; + auto rdCU16 = [&]() -> uint16_t { + uint8_t hi = rdU8(); + if (hi & 0x80) { uint8_t lo = rdU8(); return (uint16_t)(((hi & 0x7F) << 8) | lo); } + return hi; + }; + + if (cmd == 0xFF) { mnem = "end/return"; } + else if (cmd == 0xFE) { mnem = "loop_back (delay 1)"; } + else if (cmd == 0xFD) { uint16_t v = rdCU16(); snprintf(args, sizeof(args), "%u", v); mnem = "delay"; } + else if (cmd == 0xFC) { uint16_t v = rdU16(); snprintf(args, sizeof(args), "%#06x", v); mnem = "call"; } + else if (cmd == 0xFB) { uint16_t v = rdU16(); snprintf(args, sizeof(args), "%#06x", v); mnem = "jump"; } + else if (cmd == 0xFA) { uint16_t v = rdU16(); snprintf(args, sizeof(args), "%#06x", v); mnem = "jump_if_zero"; } + else if (cmd == 0xF9) { uint16_t v = rdU16(); snprintf(args, sizeof(args), "%#06x", v); mnem = "jump_if_nonneg"; } + else if (cmd == 0xF8) { uint8_t c = rdU8(); snprintf(args, sizeof(args), "count=%u", c); mnem = "loop_start"; } + else if (cmd == 0xF7) { mnem = "loop_end"; } + else if (cmd == 0xF6) { mnem = "loop_break"; } + else if (cmd == 0xF5) { uint16_t v = rdU16(); snprintf(args, sizeof(args), "%#06x", v); mnem = "jump_if_neg"; } + else if (cmd == 0xF1) { uint8_t c = rdU8(); snprintf(args, sizeof(args), "count=%u", c); mnem = "note_pool_fill"; } + else if (cmd == 0xF0) { mnem = "note_pool_clear"; } + else if (cmd == 0xDF) { mnem = "transpose=0, then"; } + else if (cmd == 0xDE) { int8_t v = rdS8(); snprintf(args, sizeof(args), "%+d", (int)v); mnem = "transpose+="; } + else if (cmd == 0xDD) { uint8_t v = rdU8(); snprintf(args, sizeof(args), "%u (~%.1f BPM)", v, v * 2.34f); mnem = "tempo"; } + else if (cmd == 0xDC) { int8_t v = rdS8(); snprintf(args, sizeof(args), "%+d", (int)v); mnem = "tempo_change"; } + else if (cmd == 0xDB) { uint8_t v = rdU8(); snprintf(args, sizeof(args), "%u", v); mnem = "seq_volume"; } + else if (cmd == 0xDA) { uint8_t s = rdU8(); uint16_t v = rdU16(); snprintf(args, sizeof(args), "sub=%u val=%u", s, v); mnem = "fade"; } + else if (cmd == 0xD9) { uint8_t v = rdU8(); snprintf(args, sizeof(args), "%u", v); mnem = "fade_vol_mod"; } + else if (cmd == 0xD7) { uint16_t v = rdU16(); snprintf(args, sizeof(args), "%#06x", v); mnem = "initchan"; } + else if (cmd == 0xD6) { uint16_t v = rdU16(); snprintf(args, sizeof(args), "%#06x", v); mnem = "disablechan"; } + else if (cmd == 0xD5) { uint8_t v = rdU8(); snprintf(args, sizeof(args), "%u", v); mnem = "mute_vol_scale"; } + else if (cmd == 0xD4) { mnem = "mute"; } + else if (cmd == 0xD3) { uint8_t v = rdU8(); snprintf(args, sizeof(args), "%#04x", v); mnem = "mute_behavior"; } + else if (cmd == 0xD2) { uint16_t v = rdU16(); snprintf(args, sizeof(args), "@%#06x", v); mnem = "short_note_vel_table"; } + else if (cmd == 0xD1) { uint16_t v = rdU16(); snprintf(args, sizeof(args), "@%#06x", v); mnem = "short_note_gate_table"; } + else if (cmd == 0xD0) { uint8_t v = rdU8(); snprintf(args, sizeof(args), "%u", v); mnem = "note_alloc_policy"; } + else if (cmd == 0xCC) { uint8_t v = rdU8(); snprintf(args, sizeof(args), "%u", v); mnem = "io_write"; } + else if (cmd == 0xC9) { uint8_t v = rdU8(); snprintf(args, sizeof(args), "%#04x", v); mnem = "io_and"; } + else if (cmd == 0xC8) { uint8_t v = rdU8(); snprintf(args, sizeof(args), "%u", v); mnem = "io_sub"; } + else if (cmd == 0xC7) { uint8_t a = rdU8(); uint16_t o = rdU16(); snprintf(args, sizeof(args), "@%#06x += %u", o, a); mnem = "write_seq_data"; } + else if (cmd >= 0xC0) { + snprintf(args, sizeof(args), "0x%02X", cmd); mnem = "seq_cmd"; + } else { + uint8_t hi = cmd & 0xF0, ch = cmd & 0x0F; + if (hi == 0x90 || hi == 0xA0 || hi == 0x20 || hi == 0xB0) { + uint16_t off = rdU16(); + const char* n = (hi == 0x90) ? "ldchan" : (hi == 0xA0 || hi == 0x20) ? "enable_chan" : "ldchan_dyn"; + snprintf(args, sizeof(args), "ch=%u @%#06x", ch, off); + mnem = n; + } else if (hi == 0x30) { + uint8_t io = rdU8(); + snprintf(args, sizeof(args), "ch=%u port=%u", ch, io); + mnem = "write_chan_io"; + } else if (hi == 0x40) { + uint8_t io = rdU8(); + snprintf(args, sizeof(args), "ch=%u port=%u", ch, io); + mnem = "read_chan_io"; + } else if (hi == 0x60) { + snprintf(args, sizeof(args), "ch=%u ticks=%u", ch, ch); + mnem = "chan_delay"; + } else { + snprintf(args, sizeof(args), "0x%02X", cmd); + mnem = "raw"; + } + } + + snprintf(linebuf, sizeof(linebuf), + "[%04zX] %-24s %s\n", opc, mnem ? mnem : "?", args); + sSeqDisasm += linebuf; + + if (cmd == 0xFF || cmd == 0xFE) break; + } + if (iter >= 256) sSeqDisasm += "[...] (truncated at 256 instructions)\n"; + } else { + sSeqDisasm = "(sequence not loaded — play it first to populate seqData)"; + } + } + + ImGui::InputTextMultiline("##seqdisasm", + const_cast(sSeqDisasm.c_str()), sSeqDisasm.size() + 1, + ImVec2(-1.f, 200.f), + ImGuiInputTextFlags_ReadOnly); + } + ImGui::End(); + } + + // ── Active Notes ───────────────────────────────────────────────────────── + if (sShow_ActiveNotes) { + struct NoteRow { + int noteIdx = -1; + int playerIdx = -1; + int channelIdx = -1; + s32 samplePos = 0; + u32 loopStart = 0, loopEnd = 0, loopCount = 0; + u16 resampleRate = 0; + int codec = 0; + u32 sampleSize = 0; + bool active = false; + bool isSynthetic = false; + bool hasLoop = false; + std::string samplePath; + }; + + static std::vector sCachedRows; + static bool sFreeze = false; + static float sRefreshHz = 4.f; + static double sLastRefreshTime = 0.0; + static bool sShowPlayer[SEQ_PLAYER_MAX] = { true, true, true, true }; + static bool sActiveOnly = false; + static float sTableHeightPx = 320.f; + + // Sample path history for the current sequence (BGM player). + // Cleared automatically when the BGM sequence ID changes. + static std::vector sSampleHistory; + static std::unordered_set sSampleHistorySet; + static int sLastSeqId = -1; + + auto capture = [&]() { + std::vector rows; + rows.reserve(SEQ_PLAYER_MAX * SEQ_NUM_CHANNELS); + + // Build a reverse map: layer pointer → note index for quick lookup. + std::unordered_map layerToNote; + if (gNotes && gNumNotes > 0) { + for (int ni = 0; ni < gNumNotes; ni++) { + Note& n = gNotes[ni]; + if (!n.noteSubEu.bitField0.enabled) continue; + SequenceLayer* lay = n.playbackState.parentLayer; + if (lay) layerToNote[lay] = ni; + } + } + + // Always emit exactly one row per player×channel so the table + // never changes size (no jumpiness). For polyphonic channels the + // highest-priority (first found) active note is shown. + for (int pi = 0; pi < SEQ_PLAYER_MAX; pi++) { + const SequencePlayer& p = gSeqPlayers[pi]; + for (int ci = 0; ci < SEQ_NUM_CHANNELS; ci++) { + NoteRow r{}; + r.playerIdx = pi; + r.channelIdx = ci; + + SequenceChannel* ch = p.channels[ci]; + if (IS_SEQUENCE_CHANNEL_VALID(ch)) { + // Find the first active note across all layers of this channel. + for (int li = 0; li < (int)ARRAY_COUNT(ch->layers); li++) { + SequenceLayer* layer = ch->layers[li]; + if (!layer) continue; + auto it = layerToNote.find(layer); + if (it == layerToNote.end()) continue; + + int ni = it->second; + Note& n = gNotes[ni]; + + r.noteIdx = ni; + r.active = true; + r.samplePos = n.synthesisState.samplePosInt; + r.resampleRate = n.noteSubEu.resampleRate; + r.isSynthetic = (bool)n.noteSubEu.bitField1.isSyntheticWave; + + if (!r.isSynthetic) { + ::Sample* const* addrPtr = n.noteSubEu.waveSampleAddr; + ::Sample* s = addrPtr ? *addrPtr : nullptr; + if (s) { + r.codec = (int)s->codec; + r.sampleSize = s->size; + ::AdpcmLoop* loop = s->loop; + if (loop) { + r.loopStart = loop->start; + r.loopEnd = loop->end; + r.loopCount = loop->count; + r.hasLoop = (loop->count != 0); + } + std::lock_guard lk(gSamplePathMapMutex); + for (auto& [sd, path] : gSamplePathMap) { + if (reinterpret_cast(s) == reinterpret_cast(sd) || + (s->sampleAddr && + reinterpret_cast(s->sampleAddr) == reinterpret_cast(sd))) { + r.samplePath = path; + break; + } + } + if (r.samplePath.empty() && gSnapshotReady.load(std::memory_order_relaxed)) { + AudioDebugSnapshot snap = AudioDebug_GetSnapshot(); + if (snap.sample && + reinterpret_cast(s) == reinterpret_cast(snap.sample)) + r.samplePath = AudioDebug_GetSamplePath(snap.sample); + } + } + } else { + r.samplePath = "(synthetic wave)"; + } + break; // one row per channel — stop after first active note + } + } + + rows.push_back(std::move(r)); + } + } + sCachedRows = std::move(rows); + }; + + double now = std::chrono::duration( + std::chrono::steady_clock::now().time_since_epoch()).count(); + double interval = (sRefreshHz > 0.f) ? 1.0 / sRefreshHz : 1.0; + bool timeToRefresh = !sFreeze && (now - sLastRefreshTime >= interval); + if (timeToRefresh) { capture(); sLastRefreshTime = now; } + + // History: detect sequence change on BGM player and update path list. + { + int curSeqId = gSeqPlayers[SEQ_PLAYER_BGM].enabled + ? (int)gSeqPlayers[SEQ_PLAYER_BGM].seqId : -1; + if (curSeqId != sLastSeqId) { + sSampleHistory.clear(); + sSampleHistorySet.clear(); + sLastSeqId = curSeqId; + } + for (auto& r : sCachedRows) { + if (!r.active || r.samplePath.empty() || r.isSynthetic) continue; + if (sSampleHistorySet.insert(r.samplePath).second) + sSampleHistory.push_back(r.samplePath); + } + } + + ImGui::SetNextWindowSize(ImVec2(720, 360), ImGuiCond_FirstUseEver); + if (ImGui::Begin("Active Notes##sf64ad", &sShow_ActiveNotes)) { + { + bool wasFrozen = sFreeze; + if (wasFrozen) + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.7f, 0.5f, 0.1f, 1.f)); + if (ImGui::Button(wasFrozen ? "Frozen" : "Live")) { + sFreeze = !sFreeze; + if (!sFreeze) { capture(); sLastRefreshTime = now; } + } + if (wasFrozen) ImGui::PopStyleColor(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(sFreeze + ? "Click to resume live updates." + : "Click to freeze the table so you can read it."); + + ImGui::SameLine(); + ImGui::SetNextItemWidth(120.f); + ImGui::SliderFloat("Hz", &sRefreshHz, 0.5f, 30.f, "%.1f Hz"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("How many times per second to refresh the table."); + + ImGui::SameLine(); + if (ImGui::Button("Capture Now")) { capture(); sLastRefreshTime = now; } + + ImGui::SameLine(); + { + int active = 0, total = 0; + for (auto& r : sCachedRows) { + if (r.playerIdx >= 0 && r.playerIdx < SEQ_PLAYER_MAX && !sShowPlayer[r.playerIdx]) continue; + if (r.active) active++; + total++; + } + ImGui::TextDisabled(" %d active / %d channel(s)", active, total); + } + if (sFreeze) { ImGui::SameLine(); ImGui::TextColored(ImVec4(1.f,0.7f,0.1f,1.f), "[FROZEN]"); } + + ImGui::Separator(); + + // Player visibility filters + mode controls + for (int pi = 0; pi < SEQ_PLAYER_MAX; pi++) { + if (pi > 0) ImGui::SameLine(); + ImGui::Checkbox(SeqPlayerName(pi), &sShowPlayer[pi]); + } + ImGui::SameLine(); + ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical); + ImGui::SameLine(); + ImGui::Checkbox("Active Only", &sActiveOnly); + ImGui::Separator(); + + const float rowH = ImGui::GetFrameHeight() + ImGui::GetStyle().CellPadding.y * 2.0f; + const float minH = rowH * 3.f; + + if (ImGui::BeginTable("##notes", 10, + ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | + ImGuiTableFlags_ScrollY | ImGuiTableFlags_SizingFixedFit | + ImGuiTableFlags_ScrollX | ImGuiTableFlags_Resizable, + ImVec2(0.f, sTableHeightPx))) { + + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn("##dot", ImGuiTableColumnFlags_WidthFixed, 12.f); + ImGui::TableSetupColumn("Pl/Ch", ImGuiTableColumnFlags_WidthFixed, 42.f); + ImGui::TableSetupColumn("Sample", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("Codec", ImGuiTableColumnFlags_WidthFixed, 76.f); + ImGui::TableSetupColumn("Size", ImGuiTableColumnFlags_WidthFixed, 64.f); + ImGui::TableSetupColumn("Position", ImGuiTableColumnFlags_WidthFixed, 120.f); + ImGui::TableSetupColumn("Loop", ImGuiTableColumnFlags_WidthFixed, 32.f); + ImGui::TableSetupColumn("LoopStart", ImGuiTableColumnFlags_WidthFixed, 72.f); + ImGui::TableSetupColumn("LoopEnd", ImGuiTableColumnFlags_WidthFixed, 72.f); + ImGui::TableSetupColumn("LoopCount", ImGuiTableColumnFlags_WidthFixed, 64.f); + ImGui::TableHeadersRow(); + + for (auto& r : sCachedRows) { + if (r.playerIdx >= 0 && r.playerIdx < SEQ_PLAYER_MAX && !sShowPlayer[r.playerIdx]) + continue; + if (sActiveOnly && !r.active) + continue; + ImGui::TableNextRow(ImGuiTableRowFlags_None, rowH); + + // Dim idle rows so active ones stand out. + if (!r.active) + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled)); + + ImGui::TableSetColumnIndex(0); + { + ImVec2 p = ImGui::GetCursorScreenPos(); + float cx = p.x + 5.f; + float cy = p.y + ImGui::GetTextLineHeight() * 0.5f; + ImU32 col = r.active + ? IM_COL32(80, 220, 80, 255) + : IM_COL32(80, 80, 80, 160); + ImGui::GetWindowDrawList()->AddCircleFilled(ImVec2(cx, cy), 4.f, col); + ImGui::Dummy(ImVec2(10.f, 0.f)); + } + + ImGui::TableSetColumnIndex(1); + ImGui::Text("%s/%d", SeqPlayerName(r.playerIdx), r.channelIdx); + + ImGui::TableSetColumnIndex(2); + if (!r.active) { + ImGui::TextDisabled("(idle)"); + } else if (r.isSynthetic) { + ImGui::TextDisabled("(synthetic)"); + } else if (r.samplePath.empty()) { + ImGui::TextDisabled("(unknown)"); + } else { + const char* slash = strrchr(r.samplePath.c_str(), '/'); + ImGui::TextUnformatted(slash ? slash + 1 : r.samplePath.c_str()); + if (ImGui::IsItemHovered()) { + ImGui::BeginTooltip(); + ImGui::TextUnformatted(r.samplePath.c_str()); + ImGui::EndTooltip(); + } + } + + ImGui::TableSetColumnIndex(3); + if (r.active) ImGui::TextUnformatted(CodecName(r.codec)); + else ImGui::TextDisabled("-"); + + ImGui::TableSetColumnIndex(4); + if (r.active) ImGui::Text("%u B", r.sampleSize); + else ImGui::TextDisabled("-"); + + ImGui::TableSetColumnIndex(5); + if (r.active) { + if (r.hasLoop && r.loopEnd > r.loopStart) { + u32 len = r.loopEnd - r.loopStart; + s32 posInLoop = r.samplePos - (s32)r.loopStart; + float frac = (posInLoop >= 0) ? (float)posInLoop / (float)len : 0.f; + frac = frac < 0.f ? 0.f : frac > 1.f ? 1.f : frac; + char ov[32]; snprintf(ov, sizeof(ov), "%d", r.samplePos); + ImGui::PushStyleColor(ImGuiCol_PlotHistogram, ImVec4(0.2f,0.6f,1.f,1.f)); + ImGui::ProgressBar(frac, ImVec2(110.f, 0.f), ov); + ImGui::PopStyleColor(); + } else { + ImGui::Text("%d", r.samplePos); + } + } else { + ImGui::TextDisabled("-"); + } + + ImGui::TableSetColumnIndex(6); + if (r.active) + ImGui::TextColored(r.hasLoop ? ImVec4(0.4f,1.f,0.4f,1.f) + : ImVec4(0.5f,0.5f,0.5f,1.f), + r.hasLoop ? "Y" : "N"); + else + ImGui::TextDisabled("-"); + + ImGui::TableSetColumnIndex(7); + if (r.active && r.hasLoop) ImGui::Text("%u", r.loopStart); else ImGui::TextDisabled("-"); + + ImGui::TableSetColumnIndex(8); + if (r.active && r.hasLoop) ImGui::Text("%u", r.loopEnd); else ImGui::TextDisabled("-"); + + ImGui::TableSetColumnIndex(9); + if (r.active && r.hasLoop) { + if (r.loopCount == 0xFFFFFFFF) + ImGui::TextColored(ImVec4(0.4f,0.8f,1.f,1.f), "inf"); + else + ImGui::Text("%u", r.loopCount); + } else { + ImGui::TextDisabled("-"); + } + + if (!r.active) + ImGui::PopStyleColor(); + } + ImGui::EndTable(); + } + + // ── Resize handle ───────────────────────────────────────────────── + { + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.f, 0.f)); + ImGui::InvisibleButton("##tblresize", ImVec2(-1.f, 6.f)); + ImGui::PopStyleVar(); + + bool hovered = ImGui::IsItemHovered(); + bool active = ImGui::IsItemActive(); + if (hovered || active) + ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNS); + if (active) { + sTableHeightPx += ImGui::GetIO().MouseDelta.y; + if (sTableHeightPx < minH) sTableHeightPx = minH; + } + + // Draw grip dots centred on the handle. + ImVec2 rmin = ImGui::GetItemRectMin(); + ImVec2 rmax = ImGui::GetItemRectMax(); + ImU32 col = active ? IM_COL32(180,180,180,255) : + hovered ? IM_COL32(140,140,140,220) : + IM_COL32(100,100,100,160); + ImDrawList* dl = ImGui::GetWindowDrawList(); + dl->AddRectFilled(rmin, rmax, IM_COL32(60,60,60,80)); + float cy = (rmin.y + rmax.y) * 0.5f; + float cx = (rmin.x + rmax.x) * 0.5f; + for (int d = -2; d <= 2; d++) + dl->AddCircleFilled(ImVec2(cx + d * 6.f, cy), 1.5f, col); + } + + // ── Sample history ──────────────────────────────────────────────── + ImGui::Spacing(); + { + char hdr[64]; + int curSeqId = gSeqPlayers[SEQ_PLAYER_BGM].enabled + ? (int)gSeqPlayers[SEQ_PLAYER_BGM].seqId : -1; + if (curSeqId >= 0) + snprintf(hdr, sizeof(hdr), "Sample History — seq %d (%zu paths)###smhist", + curSeqId, sSampleHistory.size()); + else + snprintf(hdr, sizeof(hdr), "Sample History — (no sequence)###smhist"); + + if (ImGui::CollapsingHeader(hdr)) { + if (ImGui::Button("Clear##smhist")) { + sSampleHistory.clear(); + sSampleHistorySet.clear(); + } + ImGui::SameLine(); + ImGui::TextDisabled("%zu unique sample(s)", sSampleHistory.size()); + + ImGui::BeginChild("##smhistlist", ImVec2(0.f, 120.f), true); + for (int i = (int)sSampleHistory.size() - 1; i >= 0; i--) { + const char* path = sSampleHistory[i].c_str(); + const char* slash = strrchr(path, '/'); + ImGui::TextUnformatted(slash ? slash + 1 : path); + if (ImGui::IsItemHovered()) { + ImGui::BeginTooltip(); + ImGui::TextUnformatted(path); + ImGui::EndTooltip(); + } + } + ImGui::EndChild(); + } + } + } + ImGui::End(); + } + + // ── Channel Stats ──────────────────────────────────────────────────────── + if (sShow_ChanStats) { + ImGui::SetNextWindowSize(ImVec2(560, 400), ImGuiCond_FirstUseEver); + if (ImGui::Begin("Channel Stats##sf64ad", &sShow_ChanStats)) { + for (int pi = 0; pi < SEQ_PLAYER_MAX; pi++) { + const SequencePlayer& p = gSeqPlayers[pi]; + + int validCount = 0; + for (int ci = 0; ci < SEQ_NUM_CHANNELS; ci++) { + if (IS_SEQUENCE_CHANNEL_VALID(p.channels[ci])) validCount++; + } + + char hdr[80]; + snprintf(hdr, sizeof(hdr), "Player %d (%s) — %s###chpl%d", + pi, SeqPlayerName(pi), + p.enabled ? (validCount ? "channels" : "idle (no active channels)") + : "disabled", + pi); + if (!ImGui::TreeNodeEx(hdr, ImGuiTreeNodeFlags_DefaultOpen)) continue; + + if (validCount == 0) { + ImGui::TextDisabled(" No active channels."); + ImGui::TreePop(); + continue; + } + + if (ImGui::BeginTable("##chstats", 8, + ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | + ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollX)) { + ImGui::TableSetupColumn("Ch", ImGuiTableColumnFlags_WidthFixed, 26.f); + ImGui::TableSetupColumn("En", ImGuiTableColumnFlags_WidthFixed, 24.f); + ImGui::TableSetupColumn("Muted", ImGuiTableColumnFlags_WidthFixed, 46.f); + ImGui::TableSetupColumn("Volume", ImGuiTableColumnFlags_WidthFixed, 56.f); + ImGui::TableSetupColumn("Pan", ImGuiTableColumnFlags_WidthFixed, 36.f); + ImGui::TableSetupColumn("Reverb", ImGuiTableColumnFlags_WidthFixed, 50.f); + ImGui::TableSetupColumn("Inst/Wave",ImGuiTableColumnFlags_WidthFixed, 70.f); + ImGui::TableSetupColumn("Priority", ImGuiTableColumnFlags_WidthFixed, 54.f); + ImGui::TableHeadersRow(); + + for (int ci = 0; ci < SEQ_NUM_CHANNELS; ci++) { + const SequenceChannel* ch = p.channels[ci]; + if (!IS_SEQUENCE_CHANNEL_VALID(ch)) continue; + + ImGui::TableNextRow(); + bool isMuted = SF64::gMutedChannels[ci].load(std::memory_order_relaxed); + + if (isMuted) + ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0, + IM_COL32(120, 30, 30, 80)); + + ImGui::TableSetColumnIndex(0); ImGui::Text("%d", ci); + ImGui::TableSetColumnIndex(1); + ImGui::TextColored(ch->enabled ? ImVec4(0.4f,1.f,0.4f,1.f) + : ImVec4(0.5f,0.5f,0.5f,1.f), + ch->enabled ? "Y" : "N"); + ImGui::TableSetColumnIndex(2); + ImGui::TextColored(isMuted ? ImVec4(1.f,0.4f,0.4f,1.f) + : ImVec4(0.5f,0.5f,0.5f,1.f), + isMuted ? "YES" : "-"); + ImGui::TableSetColumnIndex(3); ImGui::Text("%.3f", ch->volume); + ImGui::TableSetColumnIndex(4); ImGui::Text("%d", ch->pan); + ImGui::TableSetColumnIndex(5); ImGui::Text("%d", (int)ch->targetReverbVol); + ImGui::TableSetColumnIndex(6); + { + int iw = ch->instOrWave; + if (iw == 0) ImGui::TextDisabled("none"); + else if (iw >= 0x80) ImGui::Text("wave %02X", iw); + else ImGui::Text("inst %d", iw - 1); + } + ImGui::TableSetColumnIndex(7); ImGui::Text("%d", (int)ch->notePriority); + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + } + ImGui::End(); + } + + // ── Polyphony ──────────────────────────────────────────────────────────── + if (sShow_Polyphony) { + ImGui::SetNextWindowSize(ImVec2(380, 160), ImGuiCond_FirstUseEver); + if (ImGui::Begin("Polyphony##sf64ad", &sShow_Polyphony)) { + int activeCount = 0; + int syntheticCount = 0; + if (gNotes && gNumNotes > 0) { + for (int ni = 0; ni < gNumNotes; ni++) { + if (gNotes[ni].noteSubEu.bitField0.enabled) { + activeCount++; + if (gNotes[ni].noteSubEu.bitField1.isSyntheticWave) + syntheticCount++; + } + } + } + + ImGui::Text("Active voices:"); ImGui::SameLine(); + ImVec4 voiceCol = (activeCount == 0) ? ImVec4(0.5f,0.5f,0.5f,1.f) + : (activeCount < gNumNotes * 3 / 4) ? ImVec4(0.4f,1.f,0.4f,1.f) + : ImVec4(1.f,0.7f,0.2f,1.f); + ImGui::TextColored(voiceCol, "%d / %d", activeCount, gNumNotes); + ImGui::SameLine(); ImGui::TextDisabled("(%d synthetic)", syntheticCount); + + { + float frac = (gNumNotes > 0) ? (float)activeCount / (float)gNumNotes : 0.f; + ImVec4 barCol = (frac < 0.6f) ? ImVec4(0.2f,0.8f,0.2f,1.f) + : (frac < 0.85f)? ImVec4(0.9f,0.75f,0.1f,1.f) + : ImVec4(0.9f,0.2f,0.2f,1.f); + ImGui::PushStyleColor(ImGuiCol_PlotHistogram, barCol); + char ov[32]; snprintf(ov, sizeof(ov), "%d / %d", activeCount, gNumNotes); + ImGui::ProgressBar(frac, ImVec2(-1.f, 0.f), ov); + ImGui::PopStyleColor(); + } + + auto listLen = [](const AudioListItem& head) -> int { + int n = 0; + for (const AudioListItem* it = head.next; it != nullptr && it != &head; it = it->next) + n++; + return n; + }; + int nDisabled = listLen(gNoteFreeLists.disabled); + int nDecaying = listLen(gNoteFreeLists.decaying); + int nReleasing = listLen(gNoteFreeLists.releasing); + int nActive = listLen(gNoteFreeLists.active); + ImGui::Spacing(); + ImGui::TextDisabled("Free lists:"); + ImGui::SameLine(); + ImGui::Text("disabled=%d decaying=%d releasing=%d active=%d", + nDisabled, nDecaying, nReleasing, nActive); + } + ImGui::End(); + } + + // ── Reverb ─────────────────────────────────────────────────────────────── + if (sShow_Reverb) { + ImGui::SetNextWindowSize(ImVec2(340, 240), ImGuiCond_FirstUseEver); + if (ImGui::Begin("Reverb##sf64ad", &sShow_Reverb)) { + if (gNumSynthReverbs == 0) { + ImGui::TextDisabled("No reverb units active."); + } else { + for (int ri = 0; ri < gNumSynthReverbs; ri++) { + const SynthesisReverb& rv = gSynthReverbs[ri]; + char hdr[32]; snprintf(hdr, sizeof(hdr), "Reverb Unit %d###rv%d", ri, ri); + if (!ImGui::TreeNode(hdr)) continue; + + ImGui::Columns(2, nullptr, false); + ImGui::SetColumnWidth(0, 160.f); + +#define RROW(lbl, ...) do { ImGui::TextDisabled(lbl); ImGui::NextColumn(); ImGui::Text(__VA_ARGS__); ImGui::NextColumn(); } while(0) + RROW("Use Reverb", "%s", rv.useReverb ? "yes" : "no"); + RROW("Decay Ratio", "0x%04X (%.3f)", (unsigned)rv.decayRatio, + rv.decayRatio / 65535.f); + RROW("Window Size", "%u", (unsigned)rv.windowSize); + RROW("Downsample", "x%u", (unsigned)rv.downsampleRate); + RROW("Leak R→L", "0x%04X", (unsigned)rv.leakRtL); + RROW("Leak L→R", "0x%04X", (unsigned)rv.leakLtR); +#undef RROW + ImGui::Columns(1); + ImGui::TreePop(); + } + } + } + ImGui::End(); + } + + // ── Audio Heap ─────────────────────────────────────────────────────────── + if (sShow_AudioHeap) { + ImGui::SetNextWindowSize(ImVec2(420, 300), ImGuiCond_FirstUseEver); + if (ImGui::Begin("Audio Heap##sf64ad", &sShow_AudioHeap)) { + struct { const char* name; const AudioAllocPool* pool; } pools[] = { + { "Init Pool", &gInitPool }, + { "Session Pool", &gSessionPool }, + { "Misc Pool", &gMiscPool }, + { "Cache Pool", &gCachePool }, + { "Persistent Common", &gPersistentCommonPool }, + { "Temporary Common", &gTemporaryCommonPool }, + { "Persistent Sample Cache", &gPersistentSampleCache.pool }, + { "Temporary Sample Cache", &gTemporarySampleCache.pool }, + }; + + s32 totalUsed = 0, totalSize = 0; + for (auto& e : pools) { + if (e.pool->size <= 0) continue; + ImGui::TextDisabled("%s", e.name); + DrawPoolBar(e.name, *e.pool); + totalUsed += (s32)(e.pool->curRamAddr - e.pool->startRamAddr); + totalSize += e.pool->size; + } + + ImGui::Separator(); + ImGui::Text("Total audio memory: %d KB / %d KB (%.1f%%)", + totalUsed / 1024, totalSize / 1024, + totalSize > 0 ? 100.f * totalUsed / totalSize : 0.f); + } + ImGui::End(); + } + + // ── System ─────────────────────────────────────────────────────────────── + if (sShow_System) { + ImGui::SetNextWindowSize(ImVec2(420, 320), ImGuiCond_FirstUseEver); + if (ImGui::Begin("System##sf64ad", &sShow_System)) { + ImGui::Columns(2, nullptr, false); + ImGui::SetColumnWidth(0, 160.f); + +#define SROW(lbl, ...) do { ImGui::TextDisabled(lbl); ImGui::NextColumn(); ImGui::Text(__VA_ARGS__); ImGui::NextColumn(); } while(0) + SROW("Audio Spec", "%s (%d)", AudioSpecName(gAudioSpecId), (int)gAudioSpecId); + SROW("Sound Mode", "%s (%d)", SoundModeName(gAudioSoundMode), (int)gAudioSoundMode); + SROW("Reset Step", "%d (0=idle)", (int)gAudioResetStep); + SROW("Num Notes", "%d", gNumNotes); + SROW("Num Reverbs", "%d", (int)gNumSynthReverbs); + SROW("Refresh Rate", "%d Hz", (int)gRefreshRate); + SROW("Seq Ticks/Beat", "%d", (int)gSeqTicksPerBeat); + SROW("Max Tempo", "%d", (int)gMaxTempo); + SROW("Sampling Freq", "%u Hz", (unsigned)gAudioBufferParams.samplingFrequency); + SROW("AI Freq", "%u Hz", (unsigned)gAudioBufferParams.aiSamplingFrequency); + SROW("Samples/Frame", "%d (max %d min %d)", + (int)gAudioBufferParams.samplesPerFrameTarget, + (int)gAudioBufferParams.maxAiBufferLength, + (int)gAudioBufferParams.minAiBufferLength); + SROW("Ticks/Update", "%d", (int)gAudioBufferParams.ticksPerUpdate); + SROW("Samples/Tick", "%d (max %d min %d)", + (int)gAudioBufferParams.samplesPerTick, + (int)gAudioBufferParams.samplesPerTickMax, + (int)gAudioBufferParams.samplesPerTickMin); + SROW("Resample Rate", "%.6f", gAudioBufferParams.resampleRate); +#undef SROW + ImGui::Columns(1); + } + ImGui::End(); + } + + // ── Sample Info (Current Sample + Loop Info + Registered Samples) ──────── + if (sShow_SampleInfo) { + ImGui::SetNextWindowSize(ImVec2(500, 560), ImGuiCond_FirstUseEver); + if (ImGui::Begin("Sample Info##sf64ad", &sShow_SampleInfo)) { + if (!gSnapshotReady.load(std::memory_order_acquire)) { + ImGui::TextDisabled("No sample has played yet."); + } else { + AudioDebugSnapshot s = AudioDebug_GetSnapshot(); + const std::string& path = AudioDebug_GetSamplePath(s.sample); + + if (ImGui::CollapsingHeader("Current Sample", ImGuiTreeNodeFlags_DefaultOpen)) { + ImGui::Columns(2, "sample_cols", false); + ImGui::SetColumnWidth(0, 160.f); + + ImGui::TextDisabled("Path"); ImGui::NextColumn(); + ImGui::TextUnformatted(path.empty() ? "(unknown)" : path.c_str()); + ImGui::NextColumn(); + + ImGui::TextDisabled("Ptr"); ImGui::NextColumn(); + ImGui::Text("%p", static_cast(s.sample)); + ImGui::NextColumn(); + + ImGui::TextDisabled("Codec"); ImGui::NextColumn(); + ImGui::Text("%s (%d)", CodecName(s.codec), s.codec); + ImGui::NextColumn(); + + ImGui::TextDisabled("Size"); ImGui::NextColumn(); + ImGui::Text("%u B (%.1f KB)", s.sampleSize, s.sampleSize / 1024.f); + ImGui::NextColumn(); + + ImGui::TextDisabled("Position"); ImGui::NextColumn(); + { + float frac = (s.endPos > 0) ? (float)s.samplePos / (float)s.endPos : 0.f; + frac = frac < 0.f ? 0.f : frac > 1.f ? 1.f : frac; + char ov[64]; snprintf(ov, sizeof(ov), "%d / %u", s.samplePos, s.endPos); + ImGui::ProgressBar(frac, ImVec2(-1.f, 0.f), ov); + } + ImGui::NextColumn(); + + ImGui::TextDisabled("Resample Rate"); ImGui::NextColumn(); + float pitch = (float)s.resampleRate / 32768.f; + ImGui::Text("0x%04X (%.4fx)", (unsigned)s.resampleRate, pitch); + ImGui::SameLine(); HelpMarker("Q15 fixed-point: 0x8000 = 1.0 (no pitch shift)"); + ImGui::NextColumn(); + + ImGui::Columns(1); + } + + if (ImGui::CollapsingHeader("Loop Info", ImGuiTreeNodeFlags_DefaultOpen)) { + ImGui::Columns(2, "loop_cols", false); + ImGui::SetColumnWidth(0, 160.f); + + bool hasLoop = (s.loopCount != 0); + + ImGui::TextDisabled("Has Loop"); ImGui::NextColumn(); + if (hasLoop) ImGui::TextColored(ImVec4(0.4f,1.f,0.4f,1.f), "Yes"); + else ImGui::TextDisabled("No"); + ImGui::NextColumn(); + + ImGui::TextDisabled("Loop Start"); ImGui::NextColumn(); ImGui::Text("%u", s.loopStart); ImGui::NextColumn(); + ImGui::TextDisabled("Loop End"); ImGui::NextColumn(); ImGui::Text("%u", s.loopEnd); ImGui::NextColumn(); + ImGui::TextDisabled("Loop Length"); ImGui::NextColumn(); + ImGui::Text("%u samples", (s.loopEnd > s.loopStart) ? s.loopEnd - s.loopStart : 0); + ImGui::NextColumn(); + + ImGui::TextDisabled("Loop Count"); ImGui::NextColumn(); + if (s.loopCount == 0xFFFFFFFF) + ImGui::TextColored(ImVec4(0.4f,0.8f,1.f,1.f), "Infinite (0xFFFFFFFF)"); + else + ImGui::Text("%u", s.loopCount); + ImGui::NextColumn(); + + if (hasLoop && s.loopEnd > s.loopStart) { + ImGui::TextDisabled("Loop Progress"); ImGui::NextColumn(); + uint32_t len = s.loopEnd - s.loopStart; + int posInLoop = s.samplePos - (int)s.loopStart; + float frac = (posInLoop >= 0) ? (float)posInLoop / (float)len : 0.f; + frac = frac < 0.f ? 0.f : frac > 1.f ? 1.f : frac; + char ov[64]; snprintf(ov, sizeof(ov), "%d / %u", posInLoop, len); + ImGui::ProgressBar(frac, ImVec2(-1.f, 0.f), ov); + ImGui::NextColumn(); + } + + ImGui::Columns(1); + } + + if (ImGui::CollapsingHeader("Registered Samples")) { + std::lock_guard lk(gSamplePathMapMutex); + ImGui::Text("%zu sample(s) registered", gSamplePathMap.size()); + ImGui::Separator(); + + if (ImGui::BeginTable("##samples", 2, + ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | + ImGuiTableFlags_ScrollY | ImGuiTableFlags_SizingStretchProp, + ImVec2(0.f, 220.f))) { + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn("Path", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("Ptr", ImGuiTableColumnFlags_WidthFixed, 120.f); + ImGui::TableHeadersRow(); + + for (auto& [ptr, p] : gSamplePathMap) { + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + bool isActive = (ptr == s.sample); + if (isActive) ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.4f,1.f,0.4f,1.f)); + ImGui::TextUnformatted(p.c_str()); + if (isActive) ImGui::PopStyleColor(); + ImGui::TableSetColumnIndex(1); + ImGui::Text("%p", static_cast(ptr)); + } + ImGui::EndTable(); + } + } + } + } + ImGui::End(); + } +} + +} // namespace SF64 diff --git a/src/port/ui/AudioDebugWindow.h b/src/port/ui/AudioDebugWindow.h new file mode 100644 index 000000000..c7aceaaed --- /dev/null +++ b/src/port/ui/AudioDebugWindow.h @@ -0,0 +1,15 @@ +#pragma once +#include + +namespace SF64 { + +class AudioDebugWindow : public Ship::GuiWindow { +public: + using Ship::GuiWindow::GuiWindow; + + void InitElement() override {} + void DrawElement() override; + void UpdateElement() override {} +}; + +} // namespace SF64 diff --git a/src/port/ui/ImguiUI.cpp b/src/port/ui/ImguiUI.cpp index 5874ac2ac..d2259ae58 100644 --- a/src/port/ui/ImguiUI.cpp +++ b/src/port/ui/ImguiUI.cpp @@ -1,22 +1,31 @@ #include "ImguiUI.h" #include "UIWidgets.h" #include "ResolutionEditor.h" +#include "AudioDebugWindow.h" #include #include #define IMGUI_DEFINE_MATH_OPERATORS -#include "libultraship/src/Context.h" +#include #include #include -#include +#include +#include +#include #include "port/Engine.h" +#include "port/hooks/Events.h" #include "port/notification/notification.h" -#include "utils/StringHelper.h" +#include +#ifndef __SWITCH__ +#include +#endif +#include "port/audio/AudioDebug.h" +#include #ifdef __SWITCH__ -#include -#include +#include +#include #endif extern "C" { @@ -31,6 +40,7 @@ std::shared_ptr mConsoleWindow; std::shared_ptr mStatsWindow; std::shared_ptr mInputEditorWindow; std::shared_ptr mGfxDebuggerWindow; +std::shared_ptr mAudioDebugWindow; std::shared_ptr mNotificationWindow; std::shared_ptr mAdvancedResolutionSettingsWindow; @@ -66,19 +76,21 @@ void SetupGuiElements() { mInputEditorWindow = gui->GetGuiWindow("Input Editor"); if (mInputEditorWindow == nullptr) { SPDLOG_ERROR("Could not find input editor window"); - return; } - mGfxDebuggerWindow = gui->GetGuiWindow("GfxDebuggerWindow"); + mGfxDebuggerWindow = gui->GetGuiWindow("Gfx Debugger"); if (mGfxDebuggerWindow == nullptr) { SPDLOG_ERROR("Could not find input GfxDebuggerWindow"); } - mAdvancedResolutionSettingsWindow = std::make_shared("gAdvancedResolutionEditorEnabled", "Advanced Resolution Settings"); + mAdvancedResolutionSettingsWindow = std::make_shared( + "gAdvancedResolutionEditorEnabled", "Advanced Resolution Settings"); gui->AddGuiWindow(mAdvancedResolutionSettingsWindow); mNotificationWindow = std::make_shared("gNotifications", "Notifications Window"); gui->AddGuiWindow(mNotificationWindow); mNotificationWindow->Show(); + mAudioDebugWindow = std::make_shared("gAudioDebugEnabled", "Audio Debug"); + gui->AddGuiWindow(mAudioDebugWindow); } void Destroy() { @@ -98,18 +110,20 @@ std::string GetWindowButtonText(const char* text, bool menuOpen) { strcat(buttonText, ICON_FA_CHEVRON_RIGHT " "); } strcat(buttonText, text); - if (!menuOpen) { strcat(buttonText, " "); } + if (!menuOpen) { + strcat(buttonText, " "); + } return buttonText; } -} +} // namespace GameUI static const char* filters[3] = { #ifdef __WIIU__ - "", + "", #else - "Three-Point", + "Three-Point", #endif - "Linear", "None" + "Linear", "None" }; static const char* voiceLangs[] = { @@ -133,9 +147,10 @@ void DrawSpeakerPositionEditor() { // Reset positions if canvas position changed (window resized/moved) if (!initialized || (lastCanvasPos.x != canvasPos.x || lastCanvasPos.y != canvasPos.y)) { - const char* cvarNames[4] = { "gPositionFrontLeft", "gPositionFrontRight", "gPositionRearLeft", "gPositionRearRight" }; + const char* cvarNames[4] = { "gPositionFrontLeft", "gPositionFrontRight", "gPositionRearLeft", + "gPositionRearRight" }; float angles[4] = { 240.f, 300.f, 160.f, 20.f }; // Default angles - + for (int i = 0; i < 4; i++) { int savedAngle = CVarGetInteger(cvarNames[i], -1); if (savedAngle != -1) { @@ -151,7 +166,8 @@ void DrawSpeakerPositionEditor() { // Draw canvas ImDrawList* drawList = ImGui::GetWindowDrawList(); - drawList->AddRectFilled(canvasPos, ImVec2(canvasPos.x + canvasSize.x, canvasPos.y + canvasSize.y), IM_COL32(26, 26, 26, 255)); + drawList->AddRectFilled(canvasPos, ImVec2(canvasPos.x + canvasSize.x, canvasPos.y + canvasSize.y), + IM_COL32(26, 26, 26, 255)); drawList->AddCircleFilled(center, 5.0f, IM_COL32(255, 255, 255, 255)); // Central person // Draw circle line for speaker positions @@ -166,14 +182,16 @@ void DrawSpeakerPositionEditor() { } const char* speakerLabels[4] = { "L", "R", "RL", "RR" }; - const char* cvarNames[4] = { "gPositionFrontLeft", "gPositionFrontRight", "gPositionRearLeft", "gPositionRearRight" }; + const char* cvarNames[4] = { "gPositionFrontLeft", "gPositionFrontRight", "gPositionRearLeft", + "gPositionRearRight" }; const float snapThreshold = 2.5f; // Degrees within which snapping occurs for (int i = 0; i < 4; i++) { // Draw speaker as a darker blue circle drawList->AddCircleFilled(speakerPositions[i], 10.0f, IM_COL32(34, 52, 78, 255)); // Dark blue color - drawList->AddText(ImVec2(speakerPositions[i].x - 6, speakerPositions[i].y - 6), IM_COL32(255, 255, 255, 255), speakerLabels[i]); + drawList->AddText(ImVec2(speakerPositions[i].x - 6, speakerPositions[i].y - 6), IM_COL32(255, 255, 255, 255), + speakerLabels[i]); // Handle dragging ImGui::SetCursorScreenPos(ImVec2(speakerPositions[i].x - 10, speakerPositions[i].y - 10)); @@ -185,11 +203,13 @@ void DrawSpeakerPositionEditor() { // Constrain position to the circle ImVec2 direction = ImVec2(newPos.x - center.x, newPos.y - center.y); float length = sqrtf(direction.x * direction.x + direction.y * direction.y); - ImVec2 constrainedPos = ImVec2(center.x + (direction.x / length) * radius, center.y + (direction.y / length) * radius); + ImVec2 constrainedPos = + ImVec2(center.x + (direction.x / length) * radius, center.y + (direction.y / length) * radius); // Calculate angle of the constrained position float angle = atan2f(constrainedPos.y - center.y, constrainedPos.x - center.x) * (180.0f / M_PI); - if (angle < 0) angle += 360.0f; + if (angle < 0) + angle += 360.0f; // Snap to the nearest 22.5-degree marker if within the snap threshold float snappedAngle = roundf(angle / 22.5f) * 22.5f; @@ -202,15 +222,18 @@ void DrawSpeakerPositionEditor() { ImGui::ResetMouseDragDelta(); // Save the updated angle to CVar after dragging - float updatedAngle = atan2f(speakerPositions[i].y - center.y, speakerPositions[i].x - center.x) * (180.0f / M_PI); - if (updatedAngle < 0) updatedAngle += 360.0f; + float updatedAngle = + atan2f(speakerPositions[i].y - center.y, speakerPositions[i].x - center.x) * (180.0f / M_PI); + if (updatedAngle < 0) + updatedAngle += 360.0f; CVarSetInteger(cvarNames[i], static_cast(updatedAngle)); Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); // Mark for saving } // Calculate angle and save to CVar float angle = atan2f(speakerPositions[i].y - center.y, speakerPositions[i].x - center.x) * (180.0f / M_PI); - if (angle < 0) angle += 360.0f; + if (angle < 0) + angle += 360.0f; CVarSetInteger(cvarNames[i], static_cast(angle)); } @@ -230,41 +253,46 @@ void DrawSpeakerPositionEditor() { ImGui::SetCursorScreenPos(ImVec2(canvasPos.x, canvasPos.y + canvasSize.y + 10)); } -void DrawSettingsMenu(){ - if(UIWidgets::BeginMenu("Settings")){ +void DrawSettingsMenu() { + if (UIWidgets::BeginMenu("Settings")) { if (UIWidgets::BeginMenu("Audio")) { - UIWidgets::CVarSliderFloat("Master Volume", "gGameMasterVolume", 0.0f, 1.0f, 1.0f, { - .format = "%.0f%%", - .isPercentage = true, - }); - if (UIWidgets::CVarSliderFloat("Main Music Volume", "gMainMusicVolume", 0.0f, 1.0f, 1.0f, { - .format = "%.0f%%", - .isPercentage = true, - })) { + UIWidgets::CVarSliderFloat("Master Volume", "gGameMasterVolume", 0.0f, 1.0f, 1.0f, + { + .format = "%.0f%%", + .isPercentage = true, + }); + if (UIWidgets::CVarSliderFloat("Main Music Volume", "gMainMusicVolume", 0.0f, 1.0f, 1.0f, + { + .format = "%.0f%%", + .isPercentage = true, + })) { float val = CVarGetFloat("gMainMusicVolume", 1.0f) * 100; gSaveFile.save.data.musicVolume = (u8) val; Audio_SetVolume(AUDIO_TYPE_MUSIC, (u8) val); } - if (UIWidgets::CVarSliderFloat("Voice Volume", "gVoiceVolume", 0.0f, 1.0f, 1.0f, { - .format = "%.0f%%", - .isPercentage = true, - })) { + if (UIWidgets::CVarSliderFloat("Voice Volume", "gVoiceVolume", 0.0f, 1.0f, 1.0f, + { + .format = "%.0f%%", + .isPercentage = true, + })) { float val = CVarGetFloat("gVoiceVolume", 1.0f) * 100; gSaveFile.save.data.voiceVolume = (u8) val; Audio_SetVolume(AUDIO_TYPE_VOICE, (u8) val); } - if (UIWidgets::CVarSliderFloat("Sound Effects Volume", "gSFXMusicVolume", 0.0f, 1.0f, 1.0f, { - .format = "%.0f%%", - .isPercentage = true, - })) { + if (UIWidgets::CVarSliderFloat("Sound Effects Volume", "gSFXMusicVolume", 0.0f, 1.0f, 1.0f, + { + .format = "%.0f%%", + .isPercentage = true, + })) { float val = CVarGetFloat("gSFXMusicVolume", 1.0f) * 100; gSaveFile.save.data.sfxVolume = (u8) val; Audio_SetVolume(AUDIO_TYPE_SFX, (u8) val); } static std::unordered_map audioBackendNames = { - { Ship::AudioBackend::WASAPI, "Windows Audio Session API" }, - { Ship::AudioBackend::SDL, "SDL" }, + { Ship::AudioBackend::WASAPI, "Windows Audio Session API" }, + { Ship::AudioBackend::SDL, "SDL" }, + { Ship::AudioBackend::COREAUDIO, "CoreAudio" } }; ImGui::Text("Audio API (Needs reload)"); @@ -274,8 +302,9 @@ void DrawSettingsMenu(){ UIWidgets::DisableComponent(ImGui::GetStyle().Alpha * 0.5f); } if (ImGui::BeginCombo("##AApi", audioBackendNames[currentAudioBackend])) { - for (uint8_t i = 0; i < Ship::Context::GetInstance()->GetAudio()->GetAvailableAudioBackends()->size(); i++) { - auto backend = Ship::Context::GetInstance()->GetAudio()->GetAvailableAudioBackends()->data()[i]; + for (uint8_t i = 0; i < Ship::Context::GetInstance()->GetAudio()->GetAvailableAudioBackends()->size(); + i++) { + auto backend = (*Ship::Context::GetInstance()->GetAudio()->GetAvailableAudioBackends())[i]; if (ImGui::Selectable(audioBackendNames[backend], backend == currentAudioBackend)) { Ship::Context::GetInstance()->GetAudio()->SetCurrentAudioBackend(backend); } @@ -285,21 +314,24 @@ void DrawSettingsMenu(){ if (Ship::Context::GetInstance()->GetAudio()->GetAvailableAudioBackends()->size() <= 1) { UIWidgets::ReEnableComponent(""); } - + UIWidgets::PaddedEnhancementCheckbox("Surround 5.1 (Needs reload)", "gAudioChannelsSetting", 1, 0); - + if (CVarGetInteger("gAudioChannelsSetting", 0) == 1) { // Subwoofer threshold - UIWidgets::CVarSliderInt("Subwoofer threshold (Hz)", "gSubwooferThreshold", 10u, 1000u, 80u, { - .tooltip = "The threshold for the subwoofer to be activated. Any sound under this frequency will be played on the subwoofer.", - .format = "%d", - }); + UIWidgets::CVarSliderInt("Subwoofer threshold (Hz)", "gSubwooferThreshold", 10u, 1000u, 80u, + { + .tooltip = "The threshold for the subwoofer to be activated. Any sound " + "under this frequency will be played on the subwoofer.", + .format = "%d", + }); // Rear music volume slider - UIWidgets::CVarSliderFloat("Rear music volume", "gVolumeRearMusic", 0.0f, 1.0f, 1.0f, { - .format = "%.0f%%", - .isPercentage = true, - }); + UIWidgets::CVarSliderFloat("Rear music volume", "gVolumeRearMusic", 0.0f, 1.0f, 1.0f, + { + .format = "%.0f%%", + .isPercentage = true, + }); // Configurable positioning of speakers DrawSpeakerPositionEditor(); @@ -307,7 +339,7 @@ void DrawSettingsMenu(){ ImGui::EndMenu(); } - + if (!GameEngine::HasVersion(SF64_VER_JP) || GameEngine::HasVersion(SF64_VER_EU)) { UIWidgets::Spacer(0); if (UIWidgets::BeginMenu("Language")) { @@ -334,8 +366,10 @@ void DrawSettingsMenu(){ } } else { if (UIWidgets::Button("Install JP/EU Audio")) { - if (GameEngine::GenAssetFile(false)){ - GameEngine::ShowMessage("Success", "Audio assets installed. Changes will be applied on the next startup.", SDL_MESSAGEBOX_INFORMATION); + if (GameEngine::GenAssetFile(false)) { + GameEngine::ShowMessage( + "Success", "Audio assets installed. Changes will be applied on the next startup.", + SDL_MESSAGEBOX_INFORMATION); } Ship::Context::GetInstance()->GetWindow()->Close(); } @@ -343,7 +377,7 @@ void DrawSettingsMenu(){ ImGui::EndMenu(); } } - + UIWidgets::Spacer(0); if (UIWidgets::BeginMenu("Controller")) { @@ -351,13 +385,14 @@ void DrawSettingsMenu(){ UIWidgets::Spacer(0); - UIWidgets::CVarCheckbox("Menubar Controller Navigation", "gControlNav", { - .tooltip = "Allows controller navigation of the SOH menu bar (Settings, Enhancements,...)\nCAUTION: This will disable game inputs while the menubar is visible.\n\nD-pad to move between items, A to select, and X to grab focus on the menu bar" - }); + UIWidgets::CVarCheckbox( + "Menubar Controller Navigation", "gControlNav", + { .tooltip = "Allows controller navigation of the SOH menu bar (Settings, Enhancements,...)\nCAUTION: " + "This will disable game inputs while the menubar is visible.\n\nD-pad to move between " + "items, A to select, and X to grab focus on the menu bar" }); - UIWidgets::CVarCheckbox("Invert Y Axis", "gInvertYAxis",{ - .tooltip = "Inverts the Y axis for controlling vehicles" - }); + UIWidgets::CVarCheckbox("Invert Y Axis", "gInvertYAxis", + { .tooltip = "Inverts the Y axis for controlling vehicles" }); ImGui::EndMenu(); } @@ -367,17 +402,52 @@ void DrawSettingsMenu(){ ImGui::SetCursorPosY(0.0f); if (UIWidgets::BeginMenu("Graphics")) { - UIWidgets::WindowButton("Resolution Editor", "gAdvancedResolutionEditorEnabled", GameUI::mAdvancedResolutionSettingsWindow); + UIWidgets::WindowButton("Resolution Editor", "gAdvancedResolutionEditorEnabled", + GameUI::mAdvancedResolutionSettingsWindow); + + UIWidgets::Spacer(0); + + UIWidgets::CVarCheckbox( + "Dither Noise", "gEnhancements.Graphics.DitherNoise", + { .tooltip = "Recreates the N64's magic-square dithering, adding the original grainy look and " + "reducing color banding.", + .defaultValue = true }); + + UIWidgets::CVarSliderInt( + "Motion Blur Trail: %d%%", "gEnhancements.Graphics.BlurTrailCap", 0, 100, 80, + { .tooltip = "Caps how long the motion-blur trail persists (lower = shorter). Tames the menu smear; " + "values below ~91 also shorten the warp/boost trail." }); + + UIWidgets::CVarSliderInt( + "HD Texture Upload Budget: %d/frame", "gEnhancements.Graphics.TextureUploadBudget", 0, 8, 1, + { .tooltip = "Max new HD-pack texture uploads per frame (0 = unlimited). Lower values spread big " + "4K uploads across frames so loading a new area doesn't hitch; the base texture shows " + "until each HD replacement is ready." }); + + UIWidgets::CVarCheckbox( + "Async Texture Loading", "gEnhancements.Graphics.AsyncTextureLoad", + { .tooltip = "Decodes HD/replacement textures on a background thread instead of blocking the render " + "thread, so loading a level doesn't hitch. The vanilla texture shows until its HD " + "version finishes loading, then swaps in. Only active with Alternative Assets enabled.", + .defaultValue = false }); + + UIWidgets::CVarCheckbox( + "Debug HD Replacement", "gEnhancements.Graphics.TextureReplacementDebug", + { .tooltip = "Tints draws by HD-replacement state: blue = HD active, green flash = just uploaded, " + "red = base shown while the HD upload is still pending.", + .defaultValue = false }); UIWidgets::Spacer(0); // Previously was running every frame, and nothing was setting it? Maybe a bad copy/paste? // Ship::Context::GetInstance()->GetWindow()->SetResolutionMultiplier(CVarGetFloat("gInternalResolution", 1)); - // UIWidgets::Tooltip("Multiplies your output resolution by the value inputted, as a more intensive but effective form of anti-aliasing"); + // UIWidgets::Tooltip("Multiplies your output resolution by the value inputted, as a more intensive but + // effective form of anti-aliasing"); #ifndef __WIIU__ - if (UIWidgets::CVarSliderInt("MSAA: %d", "gMSAAValue", 1, 8, 1, { - .tooltip = "Activates multi-sample anti-aliasing when above 1x up to 8x for 8 samples for every pixel" - })) { + if (UIWidgets::CVarSliderInt( + "MSAA: %d", "gMSAAValue", 1, 8, 1, + { .tooltip = + "Activates multi-sample anti-aliasing when above 1x up to 8x for 8 samples for every pixel" })) { Ship::Context::GetInstance()->GetWindow()->SetMsaaLevel(CVarGetInteger("gMSAAValue", 1)); } #endif @@ -386,7 +456,7 @@ void DrawSettingsMenu(){ const int minFps = 30; static int maxFps = 360; int currentFps = 0; - #ifdef __WIIU__ +#ifdef __WIIU__ UIWidgets::Spacer(0); // only support divisors of 60 on the Wii U if (currentFps > 60) { @@ -446,45 +516,46 @@ void DrawSettingsMenu(){ } CVarSetInteger("gInterpolationFPS", currentFps); Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); - #else +#else bool matchingRefreshRate = CVarGetInteger("gMatchRefreshRate", 0); - UIWidgets::CVarSliderInt((currentFps == 30) ? "FPS: Original (30)" : "FPS: %d", "gInterpolationFPS", minFps, maxFps, 60, { - .disabled = matchingRefreshRate - }); - #endif + UIWidgets::CVarSliderInt((currentFps == 30) ? "FPS: Original (30)" : "FPS: %d", "gInterpolationFPS", minFps, + maxFps, 60, { .disabled = matchingRefreshRate }); +#endif UIWidgets::Tooltip( "Uses Matrix Interpolation to create extra frames, resulting in smoother graphics. This is purely " "visual and does not impact game logic, execution of glitches etc.\n\n" - "A higher target FPS than your monitor's refresh rate will waste resources, and might give a worse result." - ); + "A higher target FPS than your monitor's refresh rate will waste resources, and might give a worse " + "result."); } // END FPS Slider UIWidgets::PaddedEnhancementCheckbox("Match Refresh Rate", "gMatchRefreshRate", true, false); UIWidgets::Tooltip("Matches interpolation value to the refresh rate of your display."); - if (Ship::Context::GetInstance()->GetWindow()->GetWindowBackend() == Ship::WindowBackend::FAST3D_DXGI_DX11) { - UIWidgets::PaddedEnhancementCheckbox("Render parallelization","gRenderParallelization", true, false, {}, {}, {}, true); + if (Ship::Context::GetInstance()->GetWindow()->GetWindowBackend() == Fast::WindowBackend::FAST3D_DXGI_DX11) { + UIWidgets::PaddedEnhancementCheckbox("Render parallelization", "gRenderParallelization", true, false, {}, + {}, {}, true); UIWidgets::Tooltip( "This setting allows the CPU to work on one frame while GPU works on the previous frame.\n" "Recommended if you can't reach the FPS you set, despite it being set below your refresh rate " "or if you notice other performance problems.\n" "Adds up to one frame of input lag under certain scenarios."); } - + UIWidgets::PaddedSeparator(true, true, 3.0f, 3.0f); - static std::unordered_map windowBackendNames = { - { Ship::WindowBackend::FAST3D_DXGI_DX11, "DirectX" }, - { Ship::WindowBackend::FAST3D_SDL_OPENGL, "OpenGL"}, - { Ship::WindowBackend::FAST3D_SDL_METAL, "Metal" } + static std::unordered_map windowBackendNames = { + { Fast::WindowBackend::FAST3D_DXGI_DX11, "DirectX" }, + { Fast::WindowBackend::FAST3D_SDL_OPENGL, "OpenGL" }, + { Fast::WindowBackend::FAST3D_SDL_METAL, "Metal" }, + { Fast::WindowBackend::FAST3D_SDL_VULKAN, "Vulkan" } }; ImGui::Text("Renderer API (Needs reload)"); - Ship::WindowBackend runningWindowBackend = Ship::Context::GetInstance()->GetWindow()->GetWindowBackend(); - Ship::WindowBackend configWindowBackend; + int32_t runningWindowBackend = Ship::Context::GetInstance()->GetWindow()->GetWindowBackend(); + int32_t configWindowBackend; int configWindowBackendId = Ship::Context::GetInstance()->GetConfig()->GetInt("Window.Backend.Id", -1); - if (configWindowBackendId != -1 && configWindowBackendId < static_cast(Ship::WindowBackend::WINDOW_BACKEND_COUNT)) { - configWindowBackend = static_cast(configWindowBackendId); + if (configWindowBackendId > 0) { + configWindowBackend = configWindowBackendId; } else { configWindowBackend = runningWindowBackend; } @@ -493,12 +564,13 @@ void DrawSettingsMenu(){ UIWidgets::DisableComponent(ImGui::GetStyle().Alpha * 0.5f); } if (ImGui::BeginCombo("##RApi", windowBackendNames[configWindowBackend])) { - for (size_t i = 0; i < Ship::Context::GetInstance()->GetWindow()->GetAvailableWindowBackends()->size(); i++) { + for (size_t i = 0; i < Ship::Context::GetInstance()->GetWindow()->GetAvailableWindowBackends()->size(); + i++) { auto backend = Ship::Context::GetInstance()->GetWindow()->GetAvailableWindowBackends()->data()[i]; if (ImGui::Selectable(windowBackendNames[backend], backend == configWindowBackend)) { Ship::Context::GetInstance()->GetConfig()->SetInt("Window.Backend.Id", static_cast(backend)); Ship::Context::GetInstance()->GetConfig()->SetString("Window.Backend.Name", - windowBackendNames[backend]); + windowBackendNames[backend]); Ship::Context::GetInstance()->GetConfig()->Save(); } } @@ -509,7 +581,8 @@ void DrawSettingsMenu(){ } if (Ship::Context::GetInstance()->GetWindow()->CanDisableVerticalSync()) { - UIWidgets::PaddedEnhancementCheckbox("Enable Vsync", "gVsyncEnabled", true, false, false, "", UIWidgets::CheckboxGraphics::Cross, true); + UIWidgets::PaddedEnhancementCheckbox("Enable Vsync", "gVsyncEnabled", true, false, false, "", + UIWidgets::CheckboxGraphics::Cross, true); UIWidgets::Tooltip("Removes tearing, but clamps your max FPS to your displays refresh rate."); } @@ -518,8 +591,10 @@ void DrawSettingsMenu(){ } if (Ship::Context::GetInstance()->GetWindow()->GetGui()->SupportsViewports()) { - UIWidgets::PaddedEnhancementCheckbox("Allow multi-windows", "gEnableMultiViewports", true, false, false, "", UIWidgets::CheckboxGraphics::Cross, true); - UIWidgets::Tooltip("Allows windows to be able to be dragged off of the main game window. Requires a reload to take effect."); + UIWidgets::PaddedEnhancementCheckbox("Allow multi-windows", "gEnableMultiViewports", true, false, false, "", + UIWidgets::CheckboxGraphics::Cross, true); + UIWidgets::Tooltip("Allows windows to be able to be dragged off of the main game window. Requires a reload " + "to take effect."); } UIWidgets::PaddedEnhancementCheckbox("Enable Alternative Assets", "gEnhancements.Mods.AlternateAssets"); @@ -527,7 +602,8 @@ void DrawSettingsMenu(){ ImGui::Text("Texture Filter (Needs reload)"); UIWidgets::EnhancementCombobox("gTextureFilter", filters, 0); - UIWidgets::PaddedEnhancementCheckbox("Apply Point Filtering to UI Elements", "gHUDPointFiltering", true, false, false, "", UIWidgets::CheckboxGraphics::Cross, true); + UIWidgets::PaddedEnhancementCheckbox("Apply Point Filtering to UI Elements", "gHUDPointFiltering", true, false, + false, "", UIWidgets::CheckboxGraphics::Cross, true); UIWidgets::Spacer(0); Ship::Context::GetInstance()->GetWindow()->GetGui()->GetGameOverlay()->DrawSettings(); @@ -539,11 +615,12 @@ void DrawSettingsMenu(){ void DrawMenuBarIcon() { static bool gameIconLoaded = false; if (!gameIconLoaded) { - // Ship::Context::GetInstance()->GetWindow()->GetGui()->LoadGuiTexture("Game_Icon", "textures/icons/gIcon.png", ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); + // Ship::Context::GetInstance()->GetWindow()->GetGui()->LoadGuiTexture("Game_Icon", "textures/icons/gIcon.png", + // ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); gameIconLoaded = false; } - if (Ship::Context::GetInstance()->GetWindow()->GetGui()->GetTextureByName("Game_Icon")) { + if (std::static_pointer_cast(Ship::Context::GetInstance()->GetWindow()->GetGui())->GetTextureByName("Game_Icon")) { #ifdef __SWITCH__ ImVec2 iconSize = ImVec2(20.0f, 20.0f); float posScale = 1.0f; @@ -555,7 +632,7 @@ void DrawMenuBarIcon() { float posScale = 1.5f; #endif ImGui::SetCursorPos(ImVec2(5, 2.5f) * posScale); - ImGui::Image(Ship::Context::GetInstance()->GetWindow()->GetGui()->GetTextureByName("Game_Icon"), iconSize); + ImGui::Image(std::static_pointer_cast(Ship::Context::GetInstance()->GetWindow()->GetGui())->GetTextureByName("Game_Icon"), iconSize); ImGui::SameLine(); ImGui::SetCursorPos(ImVec2(25, 0) * posScale); } @@ -584,67 +661,60 @@ static const char* hudAspects[] = { "Expand", "Custom", "Original (4:3)", "Widescreen (16:9)", "Nintendo 3DS (5:3)", "16:10 (8:5)", "Ultrawide (21:9)" }; -static const char* radioCommBox[] = { - "Original", "Expand" -}; +static const char* radioCommBox[] = { "Original", "Expand" }; void DrawEnhancementsMenu() { if (UIWidgets::BeginMenu("Enhancements")) { if (UIWidgets::BeginMenu("Gameplay")) { - UIWidgets::CVarCheckbox("No Level of Detail (LOD)", "gDisableLOD", { - .tooltip = "Disable Level of Detail (LOD) to avoid models using lower poly versions at a distance", - .defaultValue = true - }); - UIWidgets::CVarCheckbox("Character heads inside Arwings at all times", "gTeamFaces", { - .tooltip = "Character heads are displayed inside Arwings in all cutscenes", - .defaultValue = true - }); + UIWidgets::CVarCheckbox( + "No Level of Detail (LOD)", "gDisableLOD", + { .tooltip = "Disable Level of Detail (LOD) to avoid models using lower poly versions at a distance", + .defaultValue = true }); + UIWidgets::CVarCheckbox( + "Character heads inside Arwings at all times", "gTeamFaces", + { .tooltip = "Character heads are displayed inside Arwings in all cutscenes", .defaultValue = true }); UIWidgets::CVarCheckbox("Use red radio backgrounds for enemies.", "gEnemyRedRadio"); UIWidgets::CVarSliderInt("Cockpit Glass Opacity: %d", "gCockpitOpacity", 0, 255, 120); - ImGui::EndMenu(); } - + if (UIWidgets::BeginMenu("Fixes")) { - UIWidgets::CVarCheckbox("Macbeth: Level ending cutscene camera fix", "gMaCameraFix", { - .tooltip = "Fixes a camera bug found in the code of the game" - }); + UIWidgets::CVarCheckbox("Macbeth: Level ending cutscene camera fix", "gMaCameraFix", + { .tooltip = "Fixes a camera bug found in the code of the game" }); - UIWidgets::CVarCheckbox("Sector Z: Spawn all actors", "gSzActorFix", { - .tooltip = "Fixes a bug found in Sector Z, where only 10 of 12 available actors are spawned, this causes two 'Space Junk Boxes' to be missing from the level." - }); + UIWidgets::CVarCheckbox( + "Sector Z: Spawn all actors", "gSzActorFix", + { .tooltip = "Fixes a bug found in Sector Z, where only 10 of 12 available actors are spawned, this " + "causes two 'Space Junk Boxes' to be missing from the level." }); ImGui::EndMenu(); } if (UIWidgets::BeginMenu("Restoration")) { - UIWidgets::CVarCheckbox("Sector Z: Missile cutscene bug", "gSzMissileBug", { - .tooltip = "Restores the missile cutscene bug present in JP 1.0" - }); + UIWidgets::CVarCheckbox("Sector Z: Missile cutscene bug", "gSzMissileBug", + { .tooltip = "Restores the missile cutscene bug present in JP 1.0" }); - UIWidgets::CVarCheckbox("Beta: Restore beta bomb explosion", "gRestoreBetaBombExplosion", { - .tooltip = "Restores the beta bomb explosion found inside the game" - }); + UIWidgets::CVarCheckbox("Beta: Restore beta bomb explosion", "gRestoreBetaBombExplosion", + { .tooltip = "Restores the beta bomb explosion found inside the game" }); - UIWidgets::CVarCheckbox("Beta: Restore beta coin", "gRestoreBetaCoin", { - .tooltip = "Restores the beta coin that got replaced with the gold ring" - }); + UIWidgets::CVarCheckbox("Beta: Restore beta coin", "gRestoreBetaCoin", + { .tooltip = "Restores the beta coin that got replaced with the gold ring" }); - UIWidgets::CVarCheckbox("Beta: Restore beta boost/brake gauge", "gRestoreBetaBoostGauge", { - .tooltip = "Restores the beta boost gauge that was seen in some beta footage" - }); + UIWidgets::CVarCheckbox("Beta: Restore beta boost/brake gauge", "gRestoreBetaBoostGauge", + { .tooltip = "Restores the beta boost gauge that was seen in some beta footage" }); ImGui::EndMenu(); } if (UIWidgets::BeginMenu("HUD")) { - if (UIWidgets::CVarCombobox("Radio Communication Box", "gRadioCommBox.Selection", radioCommBox, - { - .tooltip = "Which Aspect Ratio to use when drawing the Radio Communication Box", - .defaultIndex = 0, - })) { + if (UIWidgets::CVarCombobox( + "Radio Communication Box", "gRadioCommBox.Selection", radioCommBox, + { + .tooltip = "Which Aspect Ratio to use when drawing the Radio Communication Box", + .defaultIndex = 0, + })) { switch (CVarGetInteger("gRadioCommBox.Selection", 0)) { case 0: CVarSetInteger("gRadioCommBox.expand", 0); @@ -655,11 +725,12 @@ void DrawEnhancementsMenu() { } } - if (UIWidgets::CVarCombobox("HUD Aspect Ratio", "gHUDAspectRatio.Selection", hudAspects, - { - .tooltip = "Which Aspect Ratio to use when drawing the HUD (Radar, gauges and radio messages)", - .defaultIndex = 0, - })) { + if (UIWidgets::CVarCombobox( + "HUD Aspect Ratio", "gHUDAspectRatio.Selection", hudAspects, + { + .tooltip = "Which Aspect Ratio to use when drawing the HUD (Radar, gauges and radio messages)", + .defaultIndex = 0, + })) { CVarSetInteger("gHUDAspectRatio.Enabled", 1); switch (CVarGetInteger("gHUDAspectRatio.Selection", 0)) { case 0: @@ -668,10 +739,10 @@ void DrawEnhancementsMenu() { CVarSetInteger("gHUDAspectRatio.Y", 0); break; case 1: - if (CVarGetInteger("gHUDAspectRatio.X", 0) <= 0){ + if (CVarGetInteger("gHUDAspectRatio.X", 0) <= 0) { CVarSetInteger("gHUDAspectRatio.X", 1); } - if (CVarGetInteger("gHUDAspectRatio.Y", 0) <= 0){ + if (CVarGetInteger("gHUDAspectRatio.Y", 0) <= 0) { CVarSetInteger("gHUDAspectRatio.Y", 1); } break; @@ -694,12 +765,11 @@ void DrawEnhancementsMenu() { case 6: CVarSetInteger("gHUDAspectRatio.X", 21); CVarSetInteger("gHUDAspectRatio.Y", 9); - break; + break; } } - - if (CVarGetInteger("gHUDAspectRatio.Selection", 0) == 1) - { + + if (CVarGetInteger("gHUDAspectRatio.Selection", 0) == 1) { UIWidgets::CVarSliderInt("Horizontal: %d", "gHUDAspectRatio.X", 1, 100, 1); UIWidgets::CVarSliderInt("Vertical: %d", "gHUDAspectRatio.Y", 1, 100, 1); } @@ -708,15 +778,15 @@ void DrawEnhancementsMenu() { ImGui::EndMenu(); } - if (UIWidgets::BeginMenu("Accessibility")) { - UIWidgets::CVarCheckbox("Disable Gorgon (Area 6 boss) screen flashes", "gDisableGorgonFlash", { - .tooltip = "Gorgon flashes the screen repeatedly when firing its beam or when teleporting, which causes eye pain for some players and may be harmful to those with photosensitivity.", - .defaultValue = false - }); - UIWidgets::CVarCheckbox("Add outline to Arwing and Wolfen in radar", "gFighterOutlines", { - .tooltip = "Increases visibility of ships in the radar.", - .defaultValue = false - }); + if (UIWidgets::BeginMenu("Accessibility")) { + UIWidgets::CVarCheckbox( + "Disable Gorgon (Area 6 boss) screen flashes", "gDisableGorgonFlash", + { .tooltip = "Gorgon flashes the screen repeatedly when firing its beam or when teleporting, which " + "causes eye pain for some players and may be harmful to those with photosensitivity.", + .defaultValue = false }); + UIWidgets::CVarCheckbox( + "Add outline to Arwing and Wolfen in radar", "gFighterOutlines", + { .tooltip = "Increases visibility of ships in the radar.", .defaultValue = false }); ImGui::EndMenu(); } @@ -733,35 +803,29 @@ void DrawCheatsMenu() { UIWidgets::CVarCheckbox("Infinite Boost/Brake", "gInfiniteBoost"); UIWidgets::CVarCheckbox("Hyper Laser", "gHyperLaser"); UIWidgets::CVarSliderInt("Laser Range Multiplier: %d%%", "gLaserRangeMult", 15, 800, 100, - { .tooltip = "Changes how far your lasers fly." }); - UIWidgets::CVarCheckbox("Rapid-fire mode", "gRapidFire", { - .tooltip = "Hold A to keep firing. Release A to start charging a shot." - }); - if (CVarGetInteger("gRapidFire", 0) == 1) { - ImGui::Dummy(ImVec2(22.0f, 0.0f)); - ImGui::SameLine(); - UIWidgets::CVarCheckbox("Hold L to Charge", "gLtoCharge", { - .tooltip = "If you prefer to not have auto-charge." - }); - } - UIWidgets::CVarCheckbox("Self destruct button", "gHit64SelfDestruct", { - .tooltip = "Press Down on the D-PAD to instantly self destruct." - }); - UIWidgets::CVarCheckbox("Start with Falco dead", "gHit64FalcoDead", { - .tooltip = "Start the level with with Falco dead." - }); - UIWidgets::CVarCheckbox("Start with Slippy dead", "gHit64SlippyDead", { - .tooltip = "Start the level with with Slippy dead." - }); - UIWidgets::CVarCheckbox("Start with Peppy dead", "gHit64PeppyDead", { - .tooltip = "Start the level with with Peppy dead." - }); - + { .tooltip = "Changes how far your lasers fly." }); + UIWidgets::CVarCheckbox("Rapid-fire mode", "gRapidFire", + { .tooltip = "Hold A to keep firing. Release A to start charging a shot." }); + if (CVarGetInteger("gRapidFire", 0) == 1) { + ImGui::Dummy(ImVec2(22.0f, 0.0f)); + ImGui::SameLine(); + UIWidgets::CVarCheckbox("Hold L to Charge", "gLtoCharge", + { .tooltip = "If you prefer to not have auto-charge." }); + } + UIWidgets::CVarCheckbox("Self destruct button", "gHit64SelfDestruct", + { .tooltip = "Press Down on the D-PAD to instantly self destruct." }); + UIWidgets::CVarCheckbox("Start with Falco dead", "gHit64FalcoDead", + { .tooltip = "Start the level with with Falco dead." }); + UIWidgets::CVarCheckbox("Start with Slippy dead", "gHit64SlippyDead", + { .tooltip = "Start the level with with Slippy dead." }); + UIWidgets::CVarCheckbox("Start with Peppy dead", "gHit64PeppyDead", + { .tooltip = "Start the level with with Peppy dead." }); + UIWidgets::CVarCheckbox("Score Editor", "gScoreEditor", { .tooltip = "Enable the score editor" }); if (CVarGetInteger("gScoreEditor", 0) == 1) { UIWidgets::CVarSliderInt("Score: %d", "gScoreEditValue", 0, 999, 0, - { .tooltip = "Increase or decrease the current mission score number" }); + { .tooltip = "Increase or decrease the current mission score number" }); } ImGui::EndMenu(); @@ -769,120 +833,239 @@ void DrawCheatsMenu() { } static const char* debugInfoPages[6] = { - "Object", - "Check Surface", - "Map", - "Stage", - "Effect", - "Enemy", + "Object", "Check Surface", "Map", "Stage", "Effect", "Enemy", }; static const char* logLevels[] = { "trace", "debug", "info", "warn", "error", "critical", "off", }; +void DrawModsMenu() { + if (UIWidgets::BeginMenu("Mods")) { +#ifndef __SWITCH__ + if (UIWidgets::Button(ICON_FA_REFRESH " Reload Scripts", { .color = UIWidgets::Colors::Yellow, .size = ImVec2(0.0f, 0.0f), + .tooltip = "Reloads all scripts from disk." })) { + Ship::Context::GetInstance()->GetScriptLoader()->UnloadAll(); + GameEngine::LoadScripts(); + } +#else + ImGui::TextColored(ImVec4(1.0f, 0.2f, 0.2f, 1.0f), ICON_FA_TIMES " Scripting not supported on Switch"); +#endif + // Open mods folder button + if (UIWidgets::Button(ICON_FA_FOLDER_OPEN " Open Mods Folder", { .color = UIWidgets::Colors::Yellow, .size = ImVec2(0.0f, 0.0f), + .tooltip = "Opens the mods folder in your file explorer." })) { + std::string filesPath = Ship::Context::GetInstance()->GetAppDirectoryPath() + "/mods"; + SDL_OpenURL(std::string("file:///" + std::filesystem::absolute(filesPath).string()).c_str()); + } + UIWidgets::PaddedSeparator(true, true); + + auto archiveManager = Ship::Context::GetInstance()->GetResourceManager()->GetArchiveManager(); + auto mods = archiveManager->GetArchives(); +#ifndef __SWITCH__ + auto keystore = Ship::Context::GetInstance()->GetKeystore(); + auto allKeys = keystore->GetAllKeys(); +#endif + + bool hasAnyMod = false; + for (const auto& entry : *mods) { + if (!entry->GetManifest().Name.empty()) { + hasAnyMod = true; + break; + } + } + + if (UIWidgets::BeginMenu(ICON_FA_PUZZLE_PIECE " List")) { + if (!hasAnyMod) { + ImGui::TextDisabled("No mods loaded."); + } else { + bool firstMod = true; + for (const auto& entry : *mods) { + const auto& info = entry->GetManifest(); + if (info.Name.empty()) { + continue; + } + +#ifndef __SWITCH__ + // Resolve key origin + Ship::KeyOrigin origin = Ship::KeyOrigin::User; + for (const auto& key : allKeys) { + if (key.Data == StringHelper::HexToBytes(info.PublicKey)) { + origin = key.Origin; + break; + } + } +#endif + + if (!firstMod) { + UIWidgets::PaddedSeparator(true, true); + } + firstMod = false; + + // Mod name header + std::string nameLabel = info.Name; + if (!info.Icon.empty()) { + nameLabel = info.Icon + " " + nameLabel; + } + ImGui::TextUnformatted(nameLabel.c_str()); + + // Author / Version + if (!info.Author.empty()) { + if (!info.Version.empty()) { + ImGui::TextDisabled(" %s v%s", info.Author.c_str(), info.Version.c_str()); + } else { + ImGui::TextDisabled(" %s", info.Author.c_str()); + } + } + if (!info.License.empty()) { + ImGui::TextDisabled(" License: %s", info.License.c_str()); + } + + // Description + if (!info.Description.empty()) { + ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + 280.0f); + ImGui::TextDisabled(" %s", info.Description.c_str()); + ImGui::PopTextWrapPos(); + } + +#ifndef __SWITCH__ + // Security status + if (entry->IsSigned() && entry->IsChecksumValid()) { + ImVec4 originColor = UIWidgets::Colors::Green; + const char* originLabel = " [Game]"; + switch (origin) { + case Ship::KeyOrigin::User: + originColor = UIWidgets::Colors::Yellow; + originLabel = " [User]"; + break; + case Ship::KeyOrigin::Game: + originColor = UIWidgets::Colors::Green; + originLabel = " [Game]"; + break; + case Ship::KeyOrigin::System: + originColor = UIWidgets::Colors::White; + originLabel = " [System]"; + break; + } + ImGui::TextColored(originColor, " " ICON_FA_CHECK_CIRCLE " Signed%s", originLabel); + } else if (entry->IsChecksumValid()) { + ImGui::TextColored(UIWidgets::Colors::Yellow, + " " ICON_FA_EXCLAMATION_TRIANGLE " Unsigned (Caution)"); + } else { + ImGui::TextColored(UIWidgets::Colors::Red, " " ICON_FA_EXCLAMATION_TRIANGLE " Untrusted"); + } +#endif + + // Website + if (!info.Website.empty()) { + if (UIWidgets::MenuItem(ICON_FA_EXTERNAL_LINK " Open Webpage")) { + SDL_OpenURL(info.Website.c_str()); + } + } + } + } + ImGui::EndMenu(); + } + + UIWidgets::PaddedSeparator(true, true); + CALL_EVENT(EngineRenderModsEvent); + + ImGui::EndMenu(); + } +} + void DrawDebugMenu() { if (UIWidgets::BeginMenu("Developer")) { - if (UIWidgets::CVarCombobox("Log Level", "gDeveloperTools.LogLevel", logLevels, { - .tooltip = "The log level determines which messages are printed to the " - "console. This does not affect the log file output", - .defaultIndex = 1, - })) { - Ship::Context::GetInstance()->GetLogger()->set_level((spdlog::level::level_enum)CVarGetInteger("gDeveloperTools.LogLevel", 1)); + if (UIWidgets::CVarCombobox("Log Level", "gDeveloperTools.LogLevel", logLevels, + { + .tooltip = "The log level determines which messages are printed to the " + "console. This does not affect the log file output", + .defaultIndex = 1, + })) { + Ship::Context::GetInstance()->GetLogger()->set_level( + (spdlog::level::level_enum) CVarGetInteger("gDeveloperTools.LogLevel", 1)); } #ifdef __SWITCH__ - if (UIWidgets::CVarCombobox("Switch CPU Profile", "gSwitchPerfMode", SWITCH_CPU_PROFILES, { - .tooltip = "Switches the CPU profile to a different one", - .defaultIndex = (int)Ship::SwitchProfiles::STOCK - })) { - SPDLOG_INFO("Profile:: %s", SWITCH_CPU_PROFILES[CVarGetInteger("gSwitchPerfMode", (int)Ship::SwitchProfiles::STOCK)]); + if (UIWidgets::CVarCombobox("Switch CPU Profile", "gSwitchPerfMode", SWITCH_CPU_PROFILES, + { .tooltip = "Switches the CPU profile to a different one", + .defaultIndex = (int) Ship::SwitchProfiles::STOCK })) { + SPDLOG_INFO("Profile:: %s", + SWITCH_CPU_PROFILES[CVarGetInteger("gSwitchPerfMode", (int) Ship::SwitchProfiles::STOCK)]); Ship::Switch::ApplyOverclock(); } #endif - UIWidgets::WindowButton("Gfx Debugger", "gGfxDebuggerEnabled", GameUI::mGfxDebuggerWindow, { - .tooltip = "Enables the Gfx Debugger window, allowing you to input commands, type help for some examples" + UIWidgets::WindowButton( + "Gfx Debugger", "gGfxDebuggerEnabled", GameUI::mGfxDebuggerWindow, + { .tooltip = + "Enables the Gfx Debugger window, allowing you to input commands, type help for some examples" }); + + UIWidgets::WindowButton("Audio Debug", "gAudioDebugEnabled", GameUI::mAudioDebugWindow, { + .tooltip = "Shows the last triggered sample and all registered samples" }); // UIWidgets::CVarCheckbox("Debug mode", "gEnableDebugMode", { // .tooltip = "TBD" // }); - UIWidgets::CVarCheckbox("Level Selector", "gLevelSelector", { - .tooltip = "Allows you to select any level from the main menu" - }); + UIWidgets::CVarCheckbox("Level Selector", "gLevelSelector", + { .tooltip = "Allows you to select any level from the main menu" }); - UIWidgets::CVarCheckbox("Skip Briefing", "gSkipBriefing", { - .tooltip = "Allows you to skip the briefing sequence in level select" - }); + UIWidgets::CVarCheckbox("Skip Briefing", "gSkipBriefing", + { .tooltip = "Allows you to skip the briefing sequence in level select" }); - UIWidgets::CVarCheckbox("Enable Expert Mode", "gForceExpertMode", { - .tooltip = "Allows you to force expert mode" - }); + UIWidgets::CVarCheckbox("Enable Expert Mode", "gForceExpertMode", + { .tooltip = "Allows you to force expert mode" }); - UIWidgets::CVarCheckbox("SFX Jukebox", "gSfxJukebox", { - .tooltip = "Press L in the Expert Sound options to play sound effects from the game" - }); + UIWidgets::CVarCheckbox( + "SFX Jukebox", "gSfxJukebox", + { .tooltip = "Press L in the Expert Sound options to play sound effects from the game" }); - UIWidgets::CVarCheckbox("Disable Starfield interpolation", "gDisableStarsInterpolation", { - .tooltip = "Disable starfield interpolation to increase performance on slower CPUs" - }); - UIWidgets::CVarCheckbox("Disable Gamma Boost (Needs reload)", "gGraphics.GammaMode", { - .tooltip = "Disables the game's Built-in Gamma Boost. Useful for modders", - .defaultValue = false - }); + UIWidgets::CVarCheckbox( + "Disable Starfield interpolation", "gDisableStarsInterpolation", + { .tooltip = "Disable starfield interpolation to increase performance on slower CPUs" }); + UIWidgets::CVarCheckbox( + "Disable Gamma Boost (Needs reload)", "gGraphics.GammaMode", + { .tooltip = "Disables the game's Built-in Gamma Boost. Useful for modders", .defaultValue = false }); - UIWidgets::CVarCheckbox("Spawner Mod", "gSpawnerMod", { - .tooltip = "Spawn Scenery, Actors, Bosses, Sprites, Items, Effects and even Event Actors.\n" - "\n" - "Controls:\n" - "D-Pad left and right to set the object Id.\n" - "C-Right to change between spawn modes.\n" - "Analog stick sets the spawn position.\n" - "L-Trigger to spawn the object.\n" - "D-Pad UP to kill all objects.\n" - "D-Pad DOWN to freeze/unfreeze the ship speed.\n" - "WARNING: Spawning an object that's not loaded in memory will likely result in a crash." - }); + UIWidgets::CVarCheckbox( + "Spawner Mod", "gSpawnerMod", + { .tooltip = "Spawn Scenery, Actors, Bosses, Sprites, Items, Effects and even Event Actors.\n" + "\n" + "Controls:\n" + "D-Pad left and right to set the object Id.\n" + "C-Right to change between spawn modes.\n" + "Analog stick sets the spawn position.\n" + "L-Trigger to spawn the object.\n" + "D-Pad UP to kill all objects.\n" + "D-Pad DOWN to freeze/unfreeze the ship speed.\n" + "WARNING: Spawning an object that's not loaded in memory will likely result in a crash." }); - UIWidgets::CVarCheckbox("Jump To Map", "gDebugJumpToMap", { - .tooltip = "Press Z + R + C-UP to get back to the map" - }); + UIWidgets::CVarCheckbox("Jump To Map", "gDebugJumpToMap", + { .tooltip = "Press Z + R + C-UP to get back to the map" }); - UIWidgets::CVarCheckbox("L To Warp Zone", "gDebugWarpZone", { - .tooltip = "Press L to get into the Warp Zone" - }); + UIWidgets::CVarCheckbox("L To Warp Zone", "gDebugWarpZone", { .tooltip = "Press L to get into the Warp Zone" }); - UIWidgets::CVarCheckbox("L to Level Complete", "gDebugLevelComplete", { - .tooltip = "Press L to Level Complete" - }); + UIWidgets::CVarCheckbox("L to Level Complete", "gDebugLevelComplete", + { .tooltip = "Press L to Level Complete" }); - UIWidgets::CVarCheckbox("L to All-Range mode", "gDebugJumpToAllRange", { - .tooltip = "Press L to switch to All-Range mode" - }); + UIWidgets::CVarCheckbox("L to All-Range mode", "gDebugJumpToAllRange", + { .tooltip = "Press L to switch to All-Range mode" }); - UIWidgets::CVarCheckbox("Disable Collision", "gDebugNoCollision", { - .tooltip = "Disable vehicle collision" - }); - - UIWidgets::CVarCheckbox("Speed Control", "gDebugSpeedControl", { - .tooltip = "Arwing speed control. Use D-PAD Left and Right to Increase/Decrease the Arwing Speed, D-PAD Down to stop movement." - }); + UIWidgets::CVarCheckbox("Disable Collision", "gDebugNoCollision", { .tooltip = "Disable vehicle collision" }); - UIWidgets::CVarCheckbox("Debug Ending", "gDebugEnding", { - .tooltip = "Jump to credits at the main menu" - }); + UIWidgets::CVarCheckbox("Speed Control", "gDebugSpeedControl", + { .tooltip = "Arwing speed control. Use D-PAD Left and Right to Increase/Decrease the " + "Arwing Speed, D-PAD Down to stop movement." }); - UIWidgets::CVarCheckbox("Debug Pause", "gLToDebugPause", { - .tooltip = "Press L to toggle Debug Pause" - }); + UIWidgets::CVarCheckbox("Debug Ending", "gDebugEnding", { .tooltip = "Jump to credits at the main menu" }); + + UIWidgets::CVarCheckbox("Debug Pause", "gLToDebugPause", { .tooltip = "Press L to toggle Debug Pause" }); if (CVarGetInteger("gLToDebugPause", 0)) { ImGui::Dummy(ImVec2(22.0f, 0.0f)); ImGui::SameLine(); - UIWidgets::CVarCheckbox("Frame Advance", "gLToFrameAdvance", { - .tooltip = "Pressing L again advances one frame instead" - }); + UIWidgets::CVarCheckbox("Frame Advance", "gLToFrameAdvance", + { .tooltip = "Pressing L again advances one frame instead" }); } if (CVarGetInteger(StringHelper::Sprintf("gCheckpoint.%d.Set", gCurrentLevel).c_str(), 0)) { @@ -893,50 +1076,55 @@ void DrawDebugMenu() { } else if (gPlayer != NULL && gGameState == GSTATE_PLAY) { if (UIWidgets::Button("Set Checkpoint")) { CVarSetInteger(StringHelper::Sprintf("gCheckpoint.%d.Set", gCurrentLevel).c_str(), 1); - CVarSetInteger(StringHelper::Sprintf("gCheckpoint.%d.gSavedPathProgress", gCurrentLevel).c_str(), gGroundSurface); - CVarSetFloat(StringHelper::Sprintf("gCheckpoint.%d.gSavedPathProgress", gCurrentLevel).c_str(), (-gPlayer->pos.z) - 250.0f); - CVarSetInteger(StringHelper::Sprintf("gCheckpoint.%d.gSavedObjectLoadIndex", gCurrentLevel).c_str(), gObjectLoadIndex); + CVarSetInteger(StringHelper::Sprintf("gCheckpoint.%d.gSavedPathProgress", gCurrentLevel).c_str(), + gGroundSurface); + CVarSetFloat(StringHelper::Sprintf("gCheckpoint.%d.gSavedPathProgress", gCurrentLevel).c_str(), + (-gPlayer->pos.z) - 250.0f); + CVarSetInteger(StringHelper::Sprintf("gCheckpoint.%d.gSavedObjectLoadIndex", gCurrentLevel).c_str(), + gObjectLoadIndex); Ship::Context::GetInstance()->GetWindow()->GetGui()->SaveConsoleVariablesNextFrame(); } } UIWidgets::Spacer(0); - UIWidgets::WindowButton("Stats", "gStatsEnabled", GameUI::mStatsWindow, { - .tooltip = "Shows the stats window, with your FPS and frametimes, and the OS you're playing on" - }); - UIWidgets::WindowButton("Console", "gConsoleEnabled", GameUI::mConsoleWindow, { - .tooltip = "Enables the console window, allowing you to input commands, type help for some examples" - }); + UIWidgets::WindowButton( + "Stats", "gStatsEnabled", GameUI::mStatsWindow, + { .tooltip = "Shows the stats window, with your FPS and frametimes, and the OS you're playing on" }); + UIWidgets::WindowButton( + "Console", "gConsoleEnabled", GameUI::mConsoleWindow, + { .tooltip = "Enables the console window, allowing you to input commands, type help for some examples" }); ImGui::EndMenu(); } } void GameMenuBar::DrawElement() { - if(ImGui::BeginMenuBar()){ - DrawMenuBarIcon(); + if (ImGui::BeginMenuBar()) { + CALL_CANCELLABLE_EVENT(EngineRenderMenubarEvent) { + DrawMenuBarIcon(); - DrawGameMenu(); + DrawGameMenu(); - ImGui::SetCursorPosY(0.0f); + ImGui::SetCursorPosY(0.0f); - DrawSettingsMenu(); + DrawSettingsMenu(); - ImGui::SetCursorPosY(0.0f); + ImGui::SetCursorPosY(0.0f); - DrawEnhancementsMenu(); + DrawEnhancementsMenu(); - ImGui::SetCursorPosY(0.0f); + ImGui::SetCursorPosY(0.0f); - DrawCheatsMenu(); + DrawCheatsMenu(); - ImGui::SetCursorPosY(0.0f); + ImGui::SetCursorPosY(0.0f); - ImGui::SetCursorPosY(0.0f); - - DrawDebugMenu(); + ImGui::SetCursorPosY(0.0f); + DrawDebugMenu(); + DrawModsMenu(); + } ImGui::EndMenuBar(); } } \ No newline at end of file diff --git a/src/port/ui/ResolutionEditor.cpp b/src/port/ui/ResolutionEditor.cpp index cc78edafa..132ce26dc 100644 --- a/src/port/ui/ResolutionEditor.cpp +++ b/src/port/ui/ResolutionEditor.cpp @@ -1,11 +1,11 @@ #include "ResolutionEditor.h" #include "UIWidgets.h" -#include "libultraship/src/Context.h" +#include #include "port/Engine.h" #include #include -#include +#include /* Console Variables are grouped under gAdvancedResolution. (e.g. "gAdvancedResolution.Enabled") diff --git a/src/port/ui/UIWidgets.cpp b/src/port/ui/UIWidgets.cpp index 1aa98ec15..9eb9642af 100644 --- a/src/port/ui/UIWidgets.cpp +++ b/src/port/ui/UIWidgets.cpp @@ -1,7 +1,7 @@ #define NOMINMAX // prevent defining min/max macros on windows #include "UIWidgets.h" -#include "libultraship/src/Context.h" +#include #include #include diff --git a/src/port/ui/cvar_prefixes.h b/src/port/ui/cvar_prefixes.h new file mode 100644 index 000000000..760361e5e --- /dev/null +++ b/src/port/ui/cvar_prefixes.h @@ -0,0 +1,22 @@ +#pragma once + +#define CVAR_RANDOMIZER_ENHANCEMENT(var) CVAR_PREFIX_RANDOMIZER_ENHANCEMENT "." var +#define CVAR_RANDOMIZER_SETTING(var) CVAR_PREFIX_RANDOMIZER_SETTING "." var +#define CVAR_COSMETIC(var) CVAR_PREFIX_COSMETIC "." var +#define CVAR_AUDIO(var) CVAR_PREFIX_AUDIO "." var +#define CVAR_CHEAT(var) CVAR_PREFIX_CHEAT "." var +#define CVAR_ENHANCEMENT(var) CVAR_PREFIX_ENHANCEMENT "." var +#define CVAR_SETTING(var) CVAR_PREFIX_SETTING "." var +#define CVAR_WINDOW(var) CVAR_PREFIX_WINDOW "." var +#define CVAR_TRACKER(var) CVAR_PREFIX_TRACKER "." var +#define CVAR_TRACKER_ITEM(var) CVAR_TRACKER("ItemTracker." var) +#define CVAR_TRACKER_CHECK(var) CVAR_TRACKER("CheckTracker." var) +#define CVAR_TRACKER_ENTRANCE(var) CVAR_TRACKER("EntranceTracker." var) +#define CVAR_DEVELOPER_TOOLS(var) CVAR_PREFIX_DEVELOPER_TOOLS "." var +#define CVAR_GENERAL(var) CVAR_PREFIX_GENERAL "." var +#define CVAR_REMOTE(var) CVAR_PREFIX_REMOTE "." var +#define CVAR_REMOTE_CROWD_CONTROL(var) CVAR_REMOTE("CrowdControl." var) +#define CVAR_REMOTE_SAIL(var) CVAR_REMOTE("Sail." var) +#define CVAR_REMOTE_ANCHOR(var) CVAR_REMOTE("Anchor." var) +#define CVAR_GAMEPLAY_STATS(var) CVAR_PREFIX_GAMEPLAY_STATS "." var +#define CVAR_TIME_DISPLAY(var) CVAR_PREFIX_TIME_DISPLAY "." var \ No newline at end of file diff --git a/src/sys/sys_matrix.c b/src/sys/sys_matrix.c index 141e87af4..820aa245a 100644 --- a/src/sys/sys_matrix.c +++ b/src/sys/sys_matrix.c @@ -44,10 +44,6 @@ void Matrix_Copy(Matrix* dst, Matrix* src) { void Matrix_Push(Matrix** mtxStack) { FrameInterpolation_RecordMatrixPush(mtxStack); - if (mtxStack == NULL || *mtxStack == NULL) { - int bp = 0; - } - Matrix_Copy(*mtxStack + 1, *mtxStack); (*mtxStack)++; } diff --git a/tools/Torch b/tools/Torch index cd92cc0f1..4e021e103 160000 --- a/tools/Torch +++ b/tools/Torch @@ -1 +1 @@ -Subproject commit cd92cc0f161c5e79e36f5dda0d0029edd3fc8d50 +Subproject commit 4e021e10381fe5fabc8dd90b92a982aebe3c7934 diff --git a/tools/generate_audio_modding.py b/tools/generate_audio_modding.py new file mode 100644 index 000000000..c6f63068c --- /dev/null +++ b/tools/generate_audio_modding.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +""" +Update the audio sample entries in src/assets/modding.yml so that replacement +files can be placed at human-readable alias paths instead of hex paths. + +Before: + ast_audio/ast_audio_v1_sample_100E0: ast_audio/ast_audio_v1_sample_100E0 + +After: + ast_audio/ast_audio_v1_sample_100E0: ast_audio/se_ding + +Entries without an alias are left unchanged. +""" + +import json +import re +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +ALIASES_JSON = ROOT / "sf64_aliases.json" +MODDING_YML = ROOT / "src" / "assets" / "modding.yml" + + +def main() -> None: + with open(ALIASES_JSON) as f: + aliases: dict[str, str] = json.load(f)["aliases"] + # aliases: {"ast_audio/ast_audio_v1_sample_100E0": "se_ding", ...} + + text = MODDING_YML.read_text() + lines = text.splitlines(keepends=True) + out = [] + changed = 0 + skipped = 0 + + sample_re = re.compile( + r'^(\s+)(ast_audio/ast_audio_v1_sample_[0-9A-Fa-f]+)' + r':\s*(ast_audio/ast_audio_v1_sample_[0-9A-Fa-f]+)\s*$' + ) + + for line in lines: + m = sample_re.match(line) + if m: + indent = m.group(1) + key = m.group(2) # archive key (kept as-is) + if key in aliases: + alias = aliases[key] + directory = key.split("/")[0] + new_value = f"{directory}/{alias}" + out.append(f"{indent}{key}: {new_value}\n") + changed += 1 + else: + out.append(line) + skipped += 1 + else: + out.append(line) + + MODDING_YML.write_text("".join(out)) + print(f"Updated {changed} entries, {skipped} sample entries had no alias (left unchanged)") + print(f"Written to {MODDING_YML.relative_to(ROOT)}") + + +if __name__ == "__main__": + main() diff --git a/tools/generate_sample_yaml.py b/tools/generate_sample_yaml.py new file mode 100644 index 000000000..a4ed9867e --- /dev/null +++ b/tools/generate_sample_yaml.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python3 +""" +Generate explicit NAUDIO:V1:SAMPLE YAML entries for every entry in sf64_aliases.json +and append them to ast_audio.yaml AFTER audio_soundfont_table. + +Ordering matters: Torch has two phases: + 1. Pre-register all YAML offsets in gAddrMap (blocks auto-generation cascade) + 2. ParseNode in YAML order — explicit entries need FONT_TABLE.entries populated, + which only happens after audio_soundfont_table processes. + +Reads the soundfont table from sf64.o2r to recover `parent` and `sampleBankId` +for each sample (both required fields that are not stored in the aliases JSON). +""" + +import bisect +import json +import re +import struct +import sys +import zipfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +ALIASES_JSON = ROOT / "sf64_aliases.json" +O2R_PATH = ROOT / "test" / "sf64.o2r" +# Entries are appended to ast_audio.yaml itself, after audio_soundfont_table. +AUDIO_YAML = ROOT / "assets" / "yaml" / "us" / "rev1" / "ast_audio.yaml" +# Sentinel: entries go after this key (last table entry that must precede samples). +AFTER_KEY = "audio_seq_font_table:" + +OTR_HEADER = 64 # bytes + +# ── binary helpers ──────────────────────────────────────────────────────────── + +def _u8(data, off): return struct.unpack_from(" list[dict]: + """Return list of {addr, size, bankId} sorted by addr, derived from the + binary AudioTable entry for the SOUNDFONT format.""" + body = raw[OTR_HEADER:] + # int16 medium, uint32 addr, uint32 count + count = _u32(body, 6) + ENTRY = 20 # crc(8) + size(4) + medium(1) + policy(1) + sd1(2) + sd2(2) + sd3(2) + entries = [] + off = 10 + for _ in range(count): + sz = _u32(body, off + 8) + sd1 = _i16(body, off + 14) + entries.append({"sz": sz, "bankId": (sd1 >> 8) & 0xFF}) + off += ENTRY + return entries + + +def build_font_ranges(sf_paths: list[str], font_info: list[dict]) -> list[tuple]: + """Return sorted list of (addr, end_addr, bankId) — one per SoundFont.""" + addrs = [] + for path in sf_paths: + m = re.search(r"sound_font_([0-9A-Fa-f]+)$", path) + if m: + addrs.append(int(m.group(1), 16)) + addrs.sort() + + ranges = [] + for i, (addr, info) in enumerate(zip(addrs, font_info)): + end = addr + info["sz"] + ranges.append((addr, end, info["bankId"])) + return sorted(ranges) + + +def find_font(ranges: list[tuple], offset: int): + """Binary search: return (parent, bankId) for the SoundFont that owns offset.""" + lo, hi = 0, len(ranges) - 1 + while lo <= hi: + mid = (lo + hi) // 2 + addr, end, bankId = ranges[mid] + if addr <= offset < end: + return addr, bankId + elif offset < addr: + hi = mid - 1 + else: + lo = mid + 1 + return None, None + + +# ── main ────────────────────────────────────────────────────────────────────── + +def main() -> None: + with open(ALIASES_JSON) as f: + aliases: dict[str, str] = json.load(f)["aliases"] + # {archive_path: alias} e.g. {"ast_audio/ast_audio_v1_sample_100E0": "se_ding"} + + with zipfile.ZipFile(O2R_PATH) as z: + names = z.namelist() + sf_paths = sorted(n for n in names if "sound_font" in n) + font_table_raw = z.read("ast_audio/audio_soundfont_table") + + font_info = parse_soundfont_table(font_table_raw) + font_ranges = build_font_ranges(sf_paths, font_info) + + # Resolve each archive path to (alias, offset, parent, bankId), then + # deduplicate by alias — keep the entry with the lowest offset so that + # the canonical sample (the first one encountered by Torch) is documented. + canonical: dict[str, tuple] = {} # alias → (offset, parent, bankId) + skipped = 0 + + for archive_path, alias in aliases.items(): + m = re.search(r"_sample_([0-9A-Fa-f]+)$", archive_path) + if not m: + skipped += 1 + continue + + offset = int(m.group(1), 16) + parent, bank_id = find_font(font_ranges, offset) + + if parent is None: + print(f"WARNING: no font found for {alias} (offset 0x{offset:X})", file=sys.stderr) + skipped += 1 + continue + + # Keep the occurrence with the smallest offset as canonical. + if alias not in canonical or offset < canonical[alias][0]: + canonical[alias] = (offset, parent, bank_id) + + # Build the new sample block. + sample_lines: list[str] = [ + "\n", + "# --- auto-generated sample entries (tools/generate_sample_yaml.py) ---\n", + "# Must stay AFTER audio_soundfont_table so FONT_TABLE.entries is populated\n", + "# when Torch parses these in phase 2.\n", + "\n", + ] + for alias, (offset, parent, bank_id) in sorted(canonical.items()): + sample_lines.append(f"{alias}:\n") + sample_lines.append(f" type: NAUDIO:V1:SAMPLE\n") + sample_lines.append(f" offset: 0x{offset:X}\n") + sample_lines.append(f" parent: 0x{parent:X}\n") + sample_lines.append(f" sampleBankId: {bank_id}\n") + sample_lines.append(f" symbol: {alias}\n") + sample_lines.append("\n") + + # Read existing ast_audio.yaml, strip any previously generated block, then + # re-append the fresh block after AFTER_KEY. + existing = AUDIO_YAML.read_text() + + # Strip old generated block (everything from the sentinel comment onward). + gen_marker = "\n# --- auto-generated sample entries" + if gen_marker in existing: + existing = existing[: existing.index(gen_marker)] + + # Find the end of the AFTER_KEY entry so we can insert after it. + idx = existing.find(AFTER_KEY) + if idx == -1: + print(f"ERROR: '{AFTER_KEY}' not found in {AUDIO_YAML}", file=sys.stderr) + sys.exit(1) + + # Advance past the entire AFTER_KEY block (until next blank line or EOF). + end = existing.find("\n\n", idx) + insert_at = end if end != -1 else len(existing) + + result = existing[:insert_at] + "".join(sample_lines) + AUDIO_YAML.write_text(result) + print(f"Appended {len(canonical)} unique sample entries to {AUDIO_YAML.relative_to(ROOT)}") + if skipped: + print(f"Skipped {skipped} entries (no matching font range)") + + +if __name__ == "__main__": + main() diff --git a/tools/import_audio_sample.py b/tools/import_audio_sample.py new file mode 100755 index 000000000..43bdd2ec1 --- /dev/null +++ b/tools/import_audio_sample.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python3 +""" +Generates an XML descriptor for a custom audio sample (WAV/OGG/MP3) compatible +with Starship's ResourceFactoryXMLSampleV0. + +The XML and the audio file must both be packed into the same OTR/o2r archive so +that the engine can load them at runtime. This tool only generates the XML; use +your archive-packing workflow (e.g. o2r_builder) to bundle both files. + +Usage examples: + python3 tools/import_audio_sample.py mysound.wav --asset audio/custom/mysound + python3 tools/import_audio_sample.py bgm.ogg --asset audio/custom/bgm --sample-rate 44100 --channels 1 + python3 tools/import_audio_sample.py voice.mp3 --asset audio/custom/voice --out-dir mods/my_mod/assets +""" + +import argparse +import json +import os +import shutil +import struct +import subprocess +import sys +import wave +import xml.dom.minidom +import xml.etree.ElementTree as ET + + +# Starship runs its audio mixer at 32 kHz. Tuning is the ratio of the +# sample's playback rate to that reference frequency. +_AUDIO_REFERENCE_HZ = 32000.0 + + +def _probe_wav(path): + """Return (sample_rate, channels) from a WAV file using stdlib only.""" + with wave.open(path, "rb") as w: + return w.getframerate(), w.getnchannels() + + +def _probe_via_ffprobe(path): + """ + Return (sample_rate, channels) by calling ffprobe. + Raises FileNotFoundError if ffprobe is not on PATH. + """ + result = subprocess.run( + [ + "ffprobe", "-v", "quiet", + "-print_format", "json", + "-show_streams", + "-select_streams", "a:0", + path, + ], + capture_output=True, + text=True, + check=True, + ) + info = json.loads(result.stdout) + stream = info["streams"][0] + return int(stream["sample_rate"]), int(stream["channels"]) + + +def probe_audio(path, sample_rate=None, channels=None): + """ + Determine sample_rate and channels. Explicit arguments take precedence. + Falls back to WAV stdlib, then ffprobe, then asks the user. + """ + ext = os.path.splitext(path)[1].lower() + + if sample_rate is None or channels is None: + detected_rate, detected_ch = None, None + + if ext == ".wav": + try: + detected_rate, detected_ch = _probe_wav(path) + except Exception as e: + print(f"[warn] Could not read WAV header: {e}", file=sys.stderr) + + if detected_rate is None: + try: + detected_rate, detected_ch = _probe_via_ffprobe(path) + except (FileNotFoundError, subprocess.CalledProcessError, KeyError) as e: + pass + + if detected_rate is None: + print( + "[info] Could not detect audio metadata automatically.\n" + " Install ffprobe (part of ffmpeg) for automatic detection.", + file=sys.stderr, + ) + if sample_rate is None: + sample_rate = int(input(" Enter sample rate (e.g. 44100): ")) + if channels is None: + channels = int(input(" Enter channel count (1=mono, 2=stereo): ")) + else: + if sample_rate is None: + sample_rate = detected_rate + if channels is None: + channels = detected_ch + + return sample_rate, channels + + +def make_xml(asset_path, audio_filename, fmt, tuning): + """ + Build the tinyxml2-compatible XML used by ResourceFactoryXMLSampleV0. + + asset_path – the in-archive path for the audio file (e.g. audio/custom/mysound.wav) + audio_filename – basename of the audio file as stored in the archive + fmt – "wav", "ogg", or "mp3" + tuning – (sample_rate * channels) / 32000.0 + """ + root = ET.Element("Sample") + root.set("Version", "0") + root.set("Codec", "S16") + root.set("Medium", "Ram") + root.set("bit26", "0") + root.set("Tuning", f"{tuning:.6f}") + # Size will be determined at decode time; 0 is a safe placeholder. + root.set("Size", "0") + root.set("Relocated", "0") + root.set("Path", asset_path) + root.set("CustomFormat", fmt) + + raw = ET.tostring(root, encoding="unicode") + dom = xml.dom.minidom.parseString(raw) + return dom.toprettyxml(indent=" ", encoding=None).replace('\n', "") + + +def main(): + parser = argparse.ArgumentParser( + description="Generate a Starship sample XML for a custom audio file." + ) + parser.add_argument("audio", help="Input audio file (.wav, .ogg, or .mp3)") + parser.add_argument( + "--asset", + required=True, + help="Asset path inside the archive, without extension (e.g. audio/custom/mysound). " + "The audio file will be stored at ..", + ) + parser.add_argument( + "--out-dir", + default=None, + help="Directory to write the XML and copy the audio file into. " + "Mirrors the asset path hierarchy. Defaults to the directory of the input file.", + ) + parser.add_argument( + "--sample-rate", + type=int, + default=None, + help="Override detected sample rate (Hz).", + ) + parser.add_argument( + "--channels", + type=int, + default=None, + help="Override detected channel count.", + ) + args = parser.parse_args() + + audio_path = os.path.abspath(args.audio) + if not os.path.isfile(audio_path): + print(f"error: file not found: {audio_path}", file=sys.stderr) + sys.exit(1) + + ext = os.path.splitext(audio_path)[1].lower().lstrip(".") + if ext not in ("wav", "ogg", "mp3"): + print(f"error: unsupported format '.{ext}'. Only wav, ogg, mp3 are supported.", file=sys.stderr) + sys.exit(1) + + sample_rate, channels = probe_audio(audio_path, args.sample_rate, args.channels) + tuning = (sample_rate * channels) / _AUDIO_REFERENCE_HZ + + asset_path_with_ext = f"{args.asset}.{ext}" + + xml_content = make_xml(asset_path_with_ext, os.path.basename(audio_path), ext, tuning) + + if args.out_dir is not None: + out_dir = os.path.abspath(args.out_dir) + else: + out_dir = os.path.dirname(audio_path) + + # Mirror the asset hierarchy inside out_dir. + asset_rel_dir = os.path.dirname(args.asset) + dest_dir = os.path.join(out_dir, asset_rel_dir) + os.makedirs(dest_dir, exist_ok=True) + + asset_basename = os.path.basename(args.asset) + xml_out = os.path.join(dest_dir, f"{asset_basename}.xml") + audio_out = os.path.join(dest_dir, f"{asset_basename}.{ext}") + + with open(xml_out, "w", encoding="utf-8") as f: + f.write(xml_content) + + if os.path.abspath(audio_path) != os.path.abspath(audio_out): + shutil.copy2(audio_path, audio_out) + + print(f"Sample rate : {sample_rate} Hz") + print(f"Channels : {channels}") + print(f"Tuning : {tuning:.6f}") + print(f"XML written : {xml_out}") + print(f"Audio file : {audio_out}") + print() + print("Next steps:") + print(f" 1. Add both files to your OTR/o2r archive under the paths:") + print(f" {args.asset}.xml") + print(f" {asset_path_with_ext}") + print(f" 2. In your mod/game code, load the sample via:") + print(f' ResourceManager::LoadResource("{args.asset}")') + + +if __name__ == "__main__": + main() diff --git a/tools/import_sequence.py b/tools/import_sequence.py new file mode 100644 index 000000000..4f5a0215b --- /dev/null +++ b/tools/import_sequence.py @@ -0,0 +1,755 @@ +#!/usr/bin/env python3 +""" +import_sequence.py — N64 sequence bytecode importer for Starship (SF64 port). + +Given a raw N64 sequence binary (.m64 / .mus / headerless bytes) this tool: + 1. Disassembles the bytecode to human-readable text. + 2. Generates a Starship XML descriptor (ResourceFactoryXMLSequenceV0 format). + 3. Optionally packs the XML + binary into a mod .o2r archive. + +Usage: + # Disassemble only + python3 tools/import_sequence.py seq_corneria.m64 --disassemble + + # Generate XML descriptor (binary is referenced by path inside archive) + python3 tools/import_sequence.py seq_corneria.m64 \\ + --asset ast_audio/corneria_custom \\ + --index 2 --medium Ram --cache Temporary + + # Pack XML + binary into a mod archive (requires o2r_builder on PATH) + python3 tools/import_sequence.py seq_corneria.m64 \\ + --asset ast_audio/corneria_custom \\ + --index 2 --pack --out-dir mods/my_mod + +Attributes written to the XML (ResourceFactoryXMLSequenceV0): + Version always "0" + Medium one of: Ram, Cart, Disk (default: Ram) + CachePolicy one of: Temporary, Persistent, Either, Permanent (default: Temporary) + Size byte count of the raw binary (informational; factory re-reads from file) + Index seqId (0–66) this sequence replaces (default: 0) + Streamed always "false" for raw binary imports + Path in-archive path to the raw binary (e.g. ast_audio/corneria_custom.m64) + +The XML is named .xml; the binary is copied/renamed to .. +""" + +import argparse +import os +import shutil +import struct +import sys +import xml.dom.minidom +import xml.etree.ElementTree as ET +from collections import deque + +# --------------------------------------------------------------------------- +# N64 sequence bytecode disassembler — recursive / graph-based +# +# The N64 audio engine has three execution levels: +# SEQ — sequence player (top level) +# CHANNEL — per-channel player +# LAYER — per-layer note player +# +# Each level reads its own section of the binary starting at a pointer: +# SEQ: starts at offset 0 +# CHANNEL: started by SEQ opcode 0x90+ch (ldchan) +# LAYER: started by CHAN opcode 0x90+lay (ldlayer) +# +# The same byte 0x90+N means *ldchan* at SEQ level and *ldlayer* at CHANNEL +# level. A linear disassembler therefore misses almost all note data. +# This disassembler uses BFS to follow every cross-reference. +# --------------------------------------------------------------------------- + +_NOTE_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"] + +def _note_name(pitch): + octave = pitch // 12 - 1 + return f"{_NOTE_NAMES[pitch % 12]}{octave}" + + +# ── Primitive readers ──────────────────────────────────────────────────────── + +def _read_u8(data, pc): + if pc >= len(data): + raise IndexError(f"PC={pc:#06x} out of range (size={len(data):#x})") + return data[pc], pc + 1 + +def _read_s8(data, pc): + v, pc = _read_u8(data, pc) + return (v - 256) if v >= 128 else v, pc + +def _read_u16be(data, pc): + if pc + 1 >= len(data): + raise IndexError(f"PC={pc:#06x} out of range reading u16") + return (data[pc] << 8) | data[pc + 1], pc + 2 + +def _read_cu16(data, pc): + """Compressed u16: MSB set → two-byte value; else one-byte value.""" + hi, pc = _read_u8(data, pc) + if hi & 0x80: + lo, pc = _read_u8(data, pc) + return ((hi & 0x7F) << 8) | lo, pc + return hi, pc + + +# ── Shared control-flow opcodes (0xC0-0xFF, identical at SEQ and CHANNEL) ─── + +def _shared_ctrl(data, pc, cmd, orig_pc, ctx, ln, refs): + """Decode one shared control-flow opcode. + + Returns (mnemonic_string, new_pc, is_terminal). + Returns (None, pc, False) when cmd is not a shared opcode. + Appends to refs: list of (offset, ctx, label, large_notes). + """ + if cmd == 0xFF: + return "return", pc, True + if cmd == 0xFE: + return "wait_1tick", pc, True # exits script tick + if cmd == 0xFD: + delay, pc = _read_cu16(data, pc) + return f"wait {delay}", pc, True # exits script tick + if cmd == 0xFC: + off, pc = _read_u16be(data, pc) + refs.append((off, ctx, f"sub_{off:04X}", ln)) + return f"call @{off:#06x}", pc, False + if cmd == 0xFB: + off, pc = _read_u16be(data, pc) + refs.append((off, ctx, f"@{off:04X}", ln)) + return f"goto @{off:#06x}", pc, True # follow at worklist level + if cmd == 0xFA: + off, pc = _read_u16be(data, pc) + refs.append((off, ctx, f"@{off:04X}", ln)) + return f"jump_if_nonzero @{off:#06x}", pc, False + if cmd == 0xF9: + off, pc = _read_u16be(data, pc) + refs.append((off, ctx, f"@{off:04X}", ln)) + return f"jump_if_neg @{off:#06x}", pc, False + if cmd == 0xF8: + n, pc = _read_u8(data, pc) + return f"loop {n}x", pc, False + if cmd == 0xF7: + return "loop_end", pc, False + if cmd == 0xF6: + return "loop_break", pc, True + if cmd == 0xF5: + off, pc = _read_u16be(data, pc) + refs.append((off, ctx, f"@{off:04X}", ln)) + return f"jump_if_nonneg @{off:#06x}", pc, False + if cmd == 0xF4: + rel, pc = _read_s8(data, pc) + tgt = pc + rel + refs.append((tgt, ctx, f"@{tgt:04X}", ln)) + return f"branch_always {rel:+d} (@{tgt:04X})", pc, False + if cmd == 0xF3: + rel, pc = _read_s8(data, pc) + tgt = pc + rel + refs.append((tgt, ctx, f"@{tgt:04X}", ln)) + return f"branch_if_zero {rel:+d} (@{tgt:04X})", pc, False + if cmd == 0xF2: + rel, pc = _read_s8(data, pc) + tgt = pc + rel + refs.append((tgt, ctx, f"@{tgt:04X}", ln)) + return f"branch_if_neg {rel:+d} (@{tgt:04X})", pc, False + if cmd == 0xF1: + n, pc = _read_u8(data, pc) + return f"pool_fill {n}", pc, False + if cmd == 0xF0: + return "pool_clear", pc, False + return None, pc, False + + +# ── SEQ level ──────────────────────────────────────────────────────────────── + +def _disasm_seq_block(data, pc, refs): + lines = [] + visited = set() + while pc < len(data): + if pc in visited: break + visited.add(pc) + orig_pc = pc + try: + cmd, pc = _read_u8(data, pc) + except IndexError: + break + + if cmd >= 0xF0: + mn, pc, term = _shared_ctrl(data, pc, cmd, orig_pc, "seq", False, refs) + lines.append(f" [{orig_pc:04X}] {mn or f'seq_0x{cmd:02X}'}") + if term: break + continue + + hi, lo = cmd & 0xF0, cmd & 0x0F + + if hi == 0x90: # ldchan + off, pc = _read_u16be(data, pc) + refs.append((off, "channel", f"channel_{lo}_{off:04X}", False)) + lines.append(f" [{orig_pc:04X}] ldchan ch={lo} @{off:#06x}") + elif hi == 0xA0: # enable_channel (alt) + off, pc = _read_u16be(data, pc) + refs.append((off, "channel", f"channel_{lo}_{off:04X}", False)) + lines.append(f" [{orig_pc:04X}] enable_chan ch={lo} @{off:#06x}") + elif cmd == 0xDF: + lines.append(f" [{orig_pc:04X}] transposition_reset") + elif cmd == 0xDE: + v, pc = _read_s8(data, pc) + lines.append(f" [{orig_pc:04X}] transposition += {v:+d}") + elif cmd == 0xDD: + t, pc = _read_u8(data, pc) + bpm = t * 0x30 / 0x80 * 60 + lines.append(f" [{orig_pc:04X}] tempo {t} (~{bpm:.1f} BPM)") + elif cmd == 0xDC: + v, pc = _read_s8(data, pc) + lines.append(f" [{orig_pc:04X}] tempo_change {v:+d}") + elif cmd == 0xDB: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] seq_volume {v}/127") + elif cmd == 0xDA: + s, pc = _read_u8(data, pc) + v, pc = _read_u16be(data, pc) + lines.append(f" [{orig_pc:04X}] fade state={s} timer={v}") + elif cmd == 0xD9: + v, pc = _read_s8(data, pc) + lines.append(f" [{orig_pc:04X}] fade_volume_mod {v}") + elif cmd == 0xD8: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] mute_seq_vol {v}") + elif cmd == 0xD7: + mask, pc = _read_u16be(data, pc) + chs = [i for i in range(16) if mask & (1 << (15 - i))] + lines.append(f" [{orig_pc:04X}] enablechans mask={mask:#06x} {chs}") + elif cmd == 0xD6: + mask, pc = _read_u16be(data, pc) + lines.append(f" [{orig_pc:04X}] disablechans mask={mask:#06x}") + elif cmd == 0xD5: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] mute_vol_scale {v}/127") + elif cmd == 0xD4: + lines.append(f" [{orig_pc:04X}] mute") + elif cmd == 0xD3: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] mute_behavior {v:#04x}") + elif cmd == 0xD2: + off, pc = _read_u16be(data, pc) + lines.append(f" [{orig_pc:04X}] shortnote_gate_table @{off:#06x}") + elif cmd == 0xD1: + off, pc = _read_u16be(data, pc) + lines.append(f" [{orig_pc:04X}] shortnote_vel_table @{off:#06x}") + elif cmd == 0xD0: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] note_alloc_policy {v}") + elif cmd == 0xCC: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] load_u8 {v}") + elif cmd == 0xC9: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] arith_and {v:#04x}") + elif cmd == 0xC8: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] arith_sub {v}") + elif cmd == 0xC7: + v, pc = _read_u8(data, pc) + off, pc = _read_u16be(data, pc) + lines.append(f" [{orig_pc:04X}] dynwrite @{off:#06x} += {v}") + elif hi in (0x00, 0x10, 0x50, 0x70, 0x80): + lines.append(f" [{orig_pc:04X}] io_{cmd:#04x} ch={lo}") + elif hi == 0x20: + off, pc = _read_u16be(data, pc) + lines.append(f" [{orig_pc:04X}] enable_chan_alt ch={lo} @{off:#06x}") + elif hi in (0x30, 0x40): + port, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] ch_io_{cmd:#04x} ch={lo} port={port}") + elif hi == 0x60: + lines.append(f" [{orig_pc:04X}] channel_delay ch={lo}") + elif hi == 0xB0: + off, pc = _read_u16be(data, pc) + lines.append(f" [{orig_pc:04X}] ldlayer_dyn ch={lo} @{off:#06x}") + else: + lines.append(f" [{orig_pc:04X}] seq_0x{cmd:02X}") + return lines + + +# ── CHANNEL level ───────────────────────────────────────────────────────────── + +def _disasm_channel_block(data, pc, refs): + """Returns (lines, final_large_notes).""" + lines = [] + visited = set() + ln = False # largeNotes state — tracks C3/C4 opcodes + + while pc < len(data): + if pc in visited: break + visited.add(pc) + orig_pc = pc + try: + cmd, pc = _read_u8(data, pc) + except IndexError: + break + + if cmd >= 0xF0: + mn, pc, term = _shared_ctrl(data, pc, cmd, orig_pc, "channel", ln, refs) + lines.append(f" [{orig_pc:04X}] {mn or f'ch_0x{cmd:02X}'}") + if term: break + continue + + hi, lo = cmd & 0xF0, cmd & 0x0F + + if hi == 0x90: # ldlayer (same byte as ldchan at seq level) + off, pc = _read_u16be(data, pc) + refs.append((off, "layer", f"layer_{off:04X}", ln)) + flag = " ; large_notes" if ln else "" + lines.append(f" [{orig_pc:04X}] ldlayer layer={lo} @{off:#06x}{flag}") + elif hi == 0xA0: + lines.append(f" [{orig_pc:04X}] free_layer layer={lo}") + elif hi == 0xB0: + lines.append(f" [{orig_pc:04X}] ldlayer_dyn layer={lo}") + elif cmd == 0xEF: + v, pc = _read_u16be(data, pc) + v2, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] ch_0xEF @{v:#06x} {v2}") + elif cmd == 0xEE: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] pitchbend_2semi {v}") + elif cmd == 0xED: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] reverb_index {v}") + elif cmd == 0xEC: + lines.append(f" [{orig_pc:04X}] vibrato_off") + elif cmd == 0xEB: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] set_font_lookup {v}") + elif cmd == 0xEA: + lines.append(f" [{orig_pc:04X}] stop_script") + break + elif cmd == 0xE9: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] note_priority {v}") + elif cmd == 0xE8: + vals = [] + for _ in range(8): + v, pc = _read_u8(data, pc); vals.append(v) + lines.append(f" [{orig_pc:04X}] load_config_inline {vals}") + elif cmd == 0xE7: + off, pc = _read_u16be(data, pc) + lines.append(f" [{orig_pc:04X}] load_config_block @{off:#06x}") + elif cmd == 0xE6: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] book_offset {v}") + elif cmd == 0xE5: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] some_priority {v}") + elif cmd == 0xE4: + lines.append(f" [{orig_pc:04X}] call_dyntable") + elif cmd == 0xE3: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] vibrato_delay {v * 0x10}") + elif cmd == 0xE2: + a, pc = _read_u8(data, pc) + b, pc = _read_u8(data, pc) + c, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] vibrato_depth_ramp {a}→{b} delay={c}") + elif cmd == 0xE1: + a, pc = _read_u8(data, pc) + b, pc = _read_u8(data, pc) + c, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] vibrato_rate_ramp {a}→{b} delay={c}") + elif cmd == 0xE0: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] volume_mod {v}/128") + elif cmd == 0xDF: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] volume {v}/127") + elif cmd == 0xDE: + v, pc = _read_u16be(data, pc) + lines.append(f" [{orig_pc:04X}] freq_mod {v}") + elif cmd == 0xDD: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] pan {v}/127") + elif cmd == 0xDC: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] pan_weight {v}") + elif cmd == 0xDB: + v, pc = _read_s8(data, pc) + lines.append(f" [{orig_pc:04X}] transposition {v:+d}") + elif cmd == 0xDA: + off, pc = _read_u16be(data, pc) + lines.append(f" [{orig_pc:04X}] adsr_envelope @{off:#06x}") + elif cmd == 0xD9: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] adsr_decay {v}") + elif cmd == 0xD8: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] vibrato_depth {v * 8}") + elif cmd == 0xD7: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] vibrato_rate {v * 32}") + elif cmd in (0xD5, 0xD6): + lines.append(f" [{orig_pc:04X}] nop_0x{cmd:02X}") + elif cmd == 0xD4: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] reverb {v}") + elif cmd == 0xD3: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] pitchbend_1oct {v}") + elif cmd == 0xD2: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] adsr_sustain {v}") + elif cmd == 0xD1: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] note_alloc {v}") + elif cmd == 0xD0: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] stereo {v:#04x}") + elif cmd == 0xCF: + off, pc = _read_u16be(data, pc) + lines.append(f" [{orig_pc:04X}] write_unkc4 @{off:#06x}") + elif cmd == 0xCE: + v, pc = _read_u16be(data, pc) + lines.append(f" [{orig_pc:04X}] store_u16 {v:#06x}") + elif cmd == 0xCD: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] disable_chan {v}") + elif cmd == 0xCC: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] load_u8 {v}") + elif cmd == 0xCB: + off, pc = _read_u16be(data, pc) + lines.append(f" [{orig_pc:04X}] dynread @{off:#06x}") + elif cmd == 0xCA: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] mute_behavior {v:#04x}") + elif cmd == 0xC9: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] arith_and {v:#04x}") + elif cmd == 0xC8: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] arith_sub {v}") + elif cmd == 0xC7: + v, pc = _read_u8(data, pc) + off, pc = _read_u16be(data, pc) + lines.append(f" [{orig_pc:04X}] dynwrite @{off:#06x} += {v}") + elif cmd == 0xC6: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] set_font {v}") + elif cmd == 0xC5: + lines.append(f" [{orig_pc:04X}] dyntable_index") + elif cmd == 0xC4: + ln = True + lines.append(f" [{orig_pc:04X}] large_notes_on") + elif cmd == 0xC3: + ln = False + lines.append(f" [{orig_pc:04X}] large_notes_off") + elif cmd == 0xC2: + off, pc = _read_u16be(data, pc) + lines.append(f" [{orig_pc:04X}] dyntable_set @{off:#06x}") + elif cmd == 0xC1: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] set_instrument {v}") + elif hi in (0x30, 0x40): + port, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] io_{cmd:#04x} layer={lo} port={port}") + else: + lines.append(f" [{orig_pc:04X}] ch_{cmd:#04x} layer={lo}") + return lines, ln + + +# ── LAYER level ─────────────────────────────────────────────────────────────── + +def _disasm_layer_block(data, pc, refs, large_notes=False): + lines = [] + visited = set() + last_delay = None + def_delay = None + + while pc < len(data): + if pc in visited: break + visited.add(pc) + orig_pc = pc + try: + cmd, pc = _read_u8(data, pc) + except IndexError: + break + + if cmd == 0xFF: + lines.append(f" [{orig_pc:04X}] end_layer"); break + if cmd == 0xFE: + lines.append(f" [{orig_pc:04X}] loop_back"); break + if cmd == 0xFD: + d, pc = _read_cu16(data, pc) + last_delay = d + lines.append(f" [{orig_pc:04X}] delay {d}") + continue + if cmd == 0xFC: + off, pc = _read_u16be(data, pc) + refs.append((off, "layer", f"sub_{off:04X}", large_notes)) + lines.append(f" [{orig_pc:04X}] call @{off:#06x}") + continue + if cmd == 0xFB: + off, pc = _read_u16be(data, pc) + refs.append((off, "layer", f"@{off:04X}", large_notes)) + lines.append(f" [{orig_pc:04X}] goto @{off:#06x}"); break + if cmd == 0xF8: + n, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] loop {n}x"); continue + if cmd == 0xF7: + lines.append(f" [{orig_pc:04X}] loop_end"); continue + if cmd == 0xF6: + lines.append(f" [{orig_pc:04X}] loop_break"); break + if 0xD0 <= cmd <= 0xDF: + lines.append(f" [{orig_pc:04X}] vel_table[{cmd & 0xF}]"); continue + if 0xE0 <= cmd <= 0xEF: + lines.append(f" [{orig_pc:04X}] gate_table[{cmd & 0xF}]"); continue + if cmd == 0xCD: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] stereo {v:#04x}"); continue + if cmd == 0xCC: + lines.append(f" [{orig_pc:04X}] bit1_on"); continue + if cmd == 0xCB: + off, pc = _read_u16be(data, pc) + di, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] envelope @{off:#06x} decay={di}"); continue + if cmd == 0xCA: + v, pc = _read_s8(data, pc) + lines.append(f" [{orig_pc:04X}] transpose {v:+d}"); continue + if cmd == 0xC9: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] pan {v}/127"); continue + if cmd == 0xC8: + lines.append(f" [{orig_pc:04X}] portamento_off"); continue + if cmd == 0xC7: + mode, pc = _read_u8(data, pc) + note, pc = _read_u8(data, pc) + t, pc = _read_cu16(data, pc) if (mode & 0x80) else _read_u8(data, pc) + lines.append( + f" [{orig_pc:04X}] portamento mode={mode:#04x} " + f"note={_note_name(note)} time={t}"); continue + if cmd == 0xC6: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] set_instrument {v}"); continue + if cmd == 0xC5: + lines.append(f" [{orig_pc:04X}] cont_notes_off"); continue + if cmd == 0xC4: + lines.append(f" [{orig_pc:04X}] cont_notes_on"); continue + if cmd == 0xC3: + d, pc = _read_cu16(data, pc) + def_delay = d + lines.append(f" [{orig_pc:04X}] set_default_delay {d}"); continue + if cmd == 0xC2: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] set_gate {v}"); continue + if cmd == 0xC1: + v, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] set_velocity {v}"); continue + if cmd > 0xC0: + lines.append(f" [{orig_pc:04X}] layer_0x{cmd:02X}"); continue + + # ── Note bytes (cmd <= 0xC0) ───────────────────────────────────────── + pitch = cmd & 0x3F + variant = cmd >> 6 # 0 = full, 1 = short/alt, 2 = repeat + pname = _note_name(pitch) + + if not large_notes: + # Short-note format: no per-note vel/gate + if variant == 0: # full: explicit delay + d, pc = _read_cu16(data, pc) + last_delay = d + lines.append(f" [{orig_pc:04X}] note {pname} delay={d}") + elif variant == 1: # short: uses default delay + dd = def_delay if def_delay is not None else "default" + lines.append(f" [{orig_pc:04X}] note {pname} delay=default({dd})") + else: # repeat: reuse last delay + lines.append(f" [{orig_pc:04X}] note {pname} delay=last({last_delay})") + else: + # Large-note format: explicit vel + gate per note + if variant == 0: + d, pc = _read_cu16(data, pc) + vel, pc = _read_u8(data, pc) + gat, pc = _read_u8(data, pc) + last_delay = d + lines.append(f" [{orig_pc:04X}] note {pname} delay={d} vel={vel} gate={gat}") + elif variant == 1: # 0x40: explicit delay, gate=0 + d, pc = _read_cu16(data, pc) + vel, pc = _read_u8(data, pc) + last_delay = d + lines.append(f" [{orig_pc:04X}] note {pname} delay={d} vel={vel} gate=0") + else: # 0x80: repeat delay + vel, pc = _read_u8(data, pc) + gat, pc = _read_u8(data, pc) + lines.append(f" [{orig_pc:04X}] note {pname} delay=last({last_delay}) vel={vel} gate={gat}") + + return lines + + +# ── BFS graph disassembler ──────────────────────────────────────────────────── + +def disassemble(data): + """Full recursive disassembly of raw N64 sequence bytes. + + Follows every ldchan / ldlayer / call / jump cross-reference to produce + complete output for all SEQ, CHANNEL, and LAYER blocks. + """ + blocks = {} # offset -> (label, ctx, lines) + worklist = deque([(0, "seq", "seq", False)]) + + MAX_BLOCKS = 4096 + while worklist and len(blocks) < MAX_BLOCKS: + off, ctx, label, ln = worklist.popleft() + if off in blocks or off >= len(data): + continue + + refs = [] + try: + if ctx == "seq": + lines = _disasm_seq_block(data, off, refs) + elif ctx == "channel": + lines, _ = _disasm_channel_block(data, off, refs) + else: # layer + lines = _disasm_layer_block(data, off, refs, ln) + except Exception as exc: + lines = [f" [{off:04X}] ; ERROR: {exc}"] + + blocks[off] = (label, ctx, lines) + for r in refs: + if r[0] not in blocks: + worklist.append(r) + + ctx_tag = {"seq": "SEQ", "channel": "CHANNEL", "layer": "LAYER"} + out = [f"Sequence size: {len(data)} bytes ({len(data):#06x})", ""] + for off in sorted(blocks): + label, ctx, lines = blocks[off] + tag = ctx_tag.get(ctx, ctx.upper()) + ruler = "─" * max(0, 56 - len(label) - len(tag)) + out.append(f"; ── {label} [{off:#06x}] {tag} {ruler}") + out.extend(lines) + out.append("") + + if len(blocks) >= MAX_BLOCKS: + out.append("; (output truncated — MAX_BLOCKS limit reached)") + + return "\n".join(out) + + +# --------------------------------------------------------------------------- +# XML generation (matches ResourceFactoryXMLSequenceV0) +# --------------------------------------------------------------------------- + +_VALID_MEDIUM = {"Ram", "Cart", "Disk"} +_VALID_CACHE_POLICY = {"Temporary", "Persistent", "Either", "Permanent"} + + +def make_xml(asset_path_no_ext, binary_ext, seq_size, seq_index, medium, cache_policy): + """ + Build the XML descriptor consumed by ResourceFactoryXMLSequenceV0. + + asset_path_no_ext – in-archive path without extension, e.g. "ast_audio/corneria_custom" + binary_ext – file extension of the raw binary, e.g. "m64" + seq_size – byte length of the raw binary (informational) + seq_index – seqId this sequence replaces (0–66) + medium – one of Ram / Cart / Disk + cache_policy – one of Temporary / Persistent / Either / Permanent + """ + binary_path = f"{asset_path_no_ext}.{binary_ext}" + + root = ET.Element("Sequence") + root.set("Version", "0") + root.set("Medium", medium) + root.set("CachePolicy", cache_policy) + root.set("Size", str(seq_size)) + root.set("Index", str(seq_index)) + root.set("Streamed", "false") + root.set("Path", binary_path) + + raw = ET.tostring(root, encoding="unicode") + dom = xml.dom.minidom.parseString(raw) + return dom.toprettyxml(indent=" ", encoding=None).replace('\n', "") + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + +def main(): + parser = argparse.ArgumentParser( + description="Import a raw N64 sequence binary for the Starship (SF64) port." + ) + parser.add_argument("binary", + help="Raw N64 sequence binary (.m64, .mus, or any extension).") + parser.add_argument("--disassemble", action="store_true", + help="Print a disassembly of the sequence bytecode and exit.") + parser.add_argument("--asset", default=None, + help="In-archive asset path WITHOUT extension " + "(e.g. ast_audio/corneria_custom). Required unless --disassemble.") + parser.add_argument("--index", type=int, default=0, + help="seqId (0–66) that this sequence replaces (default: 0).") + parser.add_argument("--medium", default="Ram", choices=sorted(_VALID_MEDIUM), + help="Storage medium (default: Ram).") + parser.add_argument("--cache", default="Temporary", + choices=sorted(_VALID_CACHE_POLICY), + help="Cache policy (default: Temporary).") + parser.add_argument("--out-dir", default=None, + help="Output directory. Defaults to the directory of the input binary.") + parser.add_argument("--pack", action="store_true", + help="(NYI) Pack XML + binary into a .o2r mod archive after generating XML.") + args = parser.parse_args() + + bin_path = os.path.abspath(args.binary) + if not os.path.isfile(bin_path): + print(f"error: file not found: {bin_path}", file=sys.stderr) + sys.exit(1) + + with open(bin_path, "rb") as f: + data = f.read() + + # ── Disassemble-only mode ───────────────────────────────────────────────── + if args.disassemble: + print(disassemble(bytearray(data))) + return + + # ── XML generation ──────────────────────────────────────────────────────── + if args.asset is None: + print("error: --asset is required when not using --disassemble.", file=sys.stderr) + sys.exit(1) + + if args.index < 0 or args.index > 66: + print(f"warning: --index {args.index} is outside the known range 0–66.", file=sys.stderr) + + ext = os.path.splitext(bin_path)[1].lstrip(".") or "m64" + xml_content = make_xml(args.asset, ext, len(data), args.index, args.medium, args.cache) + + if args.out_dir is not None: + out_dir = os.path.abspath(args.out_dir) + else: + out_dir = os.path.dirname(bin_path) + + asset_rel_dir = os.path.dirname(args.asset) + dest_dir = os.path.join(out_dir, asset_rel_dir) + os.makedirs(dest_dir, exist_ok=True) + + asset_basename = os.path.basename(args.asset) + xml_out = os.path.join(dest_dir, f"{asset_basename}.xml") + binary_out = os.path.join(dest_dir, f"{asset_basename}.{ext}") + + with open(xml_out, "w", encoding="utf-8") as f: + f.write(xml_content) + + if os.path.abspath(bin_path) != os.path.abspath(binary_out): + shutil.copy2(bin_path, binary_out) + + print(f"Sequence size : {len(data)} bytes") + print(f"Seq index : {args.index}") + print(f"Medium : {args.medium}") + print(f"Cache policy : {args.cache}") + print(f"XML written : {xml_out}") + print(f"Binary copied : {binary_out}") + print() + print("Next steps:") + print(f" 1. Add both files to your .o2r mod archive:") + print(f" {args.asset}.xml") + print(f" {args.asset}.{ext}") + print(f" 2. The engine will override seqId {args.index} automatically when your mod is loaded.") + if args.pack: + print() + print("note: --pack not yet implemented; pack manually with your o2r_builder workflow.") + + +if __name__ == "__main__": + main() diff --git a/tools/merge.py b/tools/merge.py new file mode 100644 index 000000000..4ec884431 --- /dev/null +++ b/tools/merge.py @@ -0,0 +1,595 @@ +import os +import re +import argparse +import struct +from enum import Enum +from io import BytesIO +from typing import Optional, Dict + +from PIL import Image + +class TextureType(Enum): + Error = 0 + RGBA32bpp = 1 + RGBA16bpp = 2 + Palette4bpp = 3 + Palette8bpp = 4 + Grayscale4bpp = 5 + Grayscale8bpp = 6 + GrayscaleAlpha4bpp = 7 + GrayscaleAlpha8bpp = 8 + GrayscaleAlpha16bpp = 9 + + +TexturePixelMultipliers: Dict[TextureType, float] = { + TextureType.Error: 0.0, + TextureType.RGBA32bpp: 4.0, + TextureType.RGBA16bpp: 2.0, + TextureType.Palette4bpp: 0.5, + TextureType.Palette8bpp: 1.0, + TextureType.Grayscale4bpp: 0.5, + TextureType.Grayscale8bpp: 1.0, + TextureType.GrayscaleAlpha4bpp: 0.5, + TextureType.GrayscaleAlpha8bpp: 1.0, + TextureType.GrayscaleAlpha16bpp: 2.0, +} + +class TextureTypeUtils: + @staticmethod + def num_to_texture_type(num: int) -> TextureType: + mapping = { + 1: TextureType.RGBA32bpp, + 2: TextureType.RGBA16bpp, + 3: TextureType.Palette4bpp, + 4: TextureType.Palette8bpp, + 5: TextureType.Grayscale4bpp, + 6: TextureType.Grayscale8bpp, + 7: TextureType.GrayscaleAlpha4bpp, + 8: TextureType.GrayscaleAlpha8bpp, + 9: TextureType.GrayscaleAlpha16bpp, + } + if num not in mapping: + raise ValueError(f"Unknown texture type number: {num}") + return mapping[num] + + @staticmethod + def str_to_texture_type(string: str) -> TextureType: + mapping = { + 'RGBA32': TextureType.RGBA32bpp, + 'RGBA16': TextureType.RGBA16bpp, + 'TLUT': TextureType.RGBA16bpp, + 'CI4': TextureType.Palette4bpp, + 'CI8': TextureType.Palette8bpp, + 'I4': TextureType.Grayscale4bpp, + 'I8': TextureType.Grayscale8bpp, + 'IA4': TextureType.GrayscaleAlpha4bpp, + 'IA8': TextureType.GrayscaleAlpha8bpp, + 'IA16': TextureType.GrayscaleAlpha16bpp, + } + if string not in mapping: + raise ValueError(f"Unknown texture type string: {string}") + return mapping[string] + + @staticmethod + def get_buffer_size(tex_type: TextureType, width: int, height: int) -> int: + pixels = width * height + if tex_type == TextureType.RGBA32bpp: + return pixels * 4 + elif tex_type in (TextureType.RGBA16bpp, TextureType.GrayscaleAlpha16bpp): + return pixels * 2 + elif tex_type in (TextureType.Palette8bpp, TextureType.Grayscale8bpp, TextureType.GrayscaleAlpha8bpp): + return pixels + elif tex_type in (TextureType.Palette4bpp, TextureType.Grayscale4bpp, TextureType.GrayscaleAlpha4bpp): + return (pixels + 1) // 2 + return 0 + + +class Texture: + def __init__(self, width: int, height: int, texture_type: TextureType, tex_data: bytearray = None, tlut: Optional['Texture'] = None): + self.width = width + self.height = height + self.texture_type = texture_type + self.tex_data_size = TextureTypeUtils.get_buffer_size(texture_type, width, height) + self.tex_data = tex_data if tex_data is not None else bytearray(self.tex_data_size) + self.tlut = tlut + + def to_png_bytes(self) -> bytes: + return N64Graphics.convert_n64_to_png(self) + + +# --- Main Implementation --- + +class N64Graphics: + + @staticmethod + def has_alpha(texture: Texture) -> bool: + t = texture.texture_type + return t in ( + TextureType.Palette4bpp, + TextureType.Palette8bpp, + TextureType.RGBA32bpp, + TextureType.RGBA16bpp, + TextureType.GrayscaleAlpha16bpp, + TextureType.GrayscaleAlpha8bpp, + TextureType.GrayscaleAlpha4bpp, + ) + + @staticmethod + def pixels_to_png(texture: Texture, data: bytes) -> bytes: + img = Image.frombytes("RGBA", (texture.width, texture.height), data) + out_buffer = BytesIO() + img.save(out_buffer, format="PNG") + return out_buffer.getvalue() + + @staticmethod + def convert_raw_to_n64(texture: Texture, img: Image.Image) -> None: + texture.width = img.width + texture.height = img.height + texture.tex_data_size = TextureTypeUtils.get_buffer_size(texture.texture_type, texture.width, texture.height) + texture.tex_data = bytearray(texture.tex_data_size) + + w, h = texture.width, texture.height + tex_data = texture.tex_data + tex_type = texture.texture_type + + if tex_type == TextureType.RGBA16bpp: + img_rgba = img.convert("RGBA") + pixels = img_rgba.load() + for y in range(h): + for x in range(w): + r, g, b, a = pixels[x, y] + pos = ((y * w) + x) * 2 + r5 = r // 8 + g5 = g // 8 + b5 = b // 8 + a_bit = 1 if a != 0 else 0 + + data_val = (r5 << 11) | (g5 << 6) | (b5 << 1) | a_bit + tex_data[pos] = (data_val & 0xFF00) >> 8 + tex_data[pos + 1] = data_val & 0x00FF + + elif tex_type == TextureType.RGBA32bpp: + img_rgba = img.convert("RGBA") + pixels = img_rgba.load() + for y in range(h): + for x in range(w): + r, g, b, a = pixels[x, y] + pos = ((y * w) + x) * 4 + tex_data[pos:pos+4] = [r, g, b, a] + + elif tex_type == TextureType.Palette4bpp: + img_p = img.convert("P") if img.mode != "P" else img + pixels = img_p.load() + for y in range(h): + for x in range(0, w, 2): + pos = ((y * w) + x) // 2 + idx1 = pixels[x, y] + idx2 = pixels[x + 1, y] if x + 1 < w else 0 + tex_data[pos] = ((idx1 & 0x0F) << 4) | (idx2 & 0x0F) + + elif tex_type == TextureType.Palette8bpp: + img_p = img.convert("P") if img.mode != "P" else img + pixels = img_p.load() + for y in range(h): + for x in range(w): + pos = (y * w) + x + tex_data[pos] = pixels[x, y] & 0xFF + + elif tex_type == TextureType.Grayscale4bpp: + img_l = img.convert("L") if img.mode != "L" else img + pixels = img_l.load() + for y in range(h): + for x in range(0, w, 2): + pos = ((y * w) + x) // 2 + r1 = pixels[x, y] + r2 = pixels[x + 1, y] if x + 1 < w else 0 + tex_data[pos] = (((r1 // 16) << 4) | (r2 // 16)) & 0xFF + + elif tex_type == TextureType.Grayscale8bpp: + img_l = img.convert("L") if img.mode != "L" else img + pixels = img_l.load() + for y in range(h): + for x in range(w): + pos = (y * w) + x + tex_data[pos] = pixels[x, y] & 0xFF + + elif tex_type == TextureType.GrayscaleAlpha4bpp: + img_la = img.convert("LA") if img.mode != "LA" else img + pixels = img_la.load() + for y in range(h): + for x in range(0, w, 2): + pos = ((y * w) + x) // 2 + l1, a1 = pixels[x, y] + l2, a2 = pixels[x + 1, y] if x + 1 < w else (0, 0) + + alpha_bit1 = 1 if a1 != 0 else 0 + alpha_bit2 = 1 if a2 != 0 else 0 + + data_val = ((((l1 // 32) << 1) | alpha_bit1) << 4) | (((l2 // 32) << 1) | alpha_bit2) + tex_data[pos] = data_val & 0xFF + + elif tex_type == TextureType.GrayscaleAlpha8bpp: + img_la = img.convert("LA") if img.mode != "LA" else img + pixels = img_la.load() + for y in range(h): + for x in range(w): + pos = (y * w) + x + l, a = pixels[x, y] + tex_data[pos] = (((l // 16) << 4) | (a // 16)) & 0xFF + + elif tex_type == TextureType.GrayscaleAlpha16bpp: + img_la = img.convert("LA") if img.mode != "LA" else img + pixels = img_la.load() + for y in range(h): + for x in range(w): + pos = ((y * w) + x) * 2 + l, a = pixels[x, y] + tex_data[pos] = l & 0xFF + tex_data[pos + 1] = a & 0xFF + + elif tex_type == TextureType.Error: + raise ValueError("Unknown texture type") + + @staticmethod + def convert_n64_to_png(texture: Texture) -> Optional[bytes]: + w, h = texture.width, texture.height + tex_data = texture.tex_data + tex_type = texture.texture_type + is_palette = tex_type in (TextureType.Palette4bpp, TextureType.Palette8bpp) + + img: Optional[Image.Image] = None + + if tex_type == TextureType.RGBA32bpp: + img = Image.frombytes("RGBA", (w, h), bytes(tex_data)) + + elif tex_type == TextureType.RGBA16bpp: + img = Image.new("RGBA", (w, h)) + pixels = img.load() + for y in range(h): + for x in range(w): + pos = ((y * w) + x) * 2 + data_val = (tex_data[pos] << 8) | tex_data[pos + 1] + r = ((data_val & 0xF800) >> 11) * 8 + g = ((data_val & 0x07C0) >> 6) * 8 + b = ((data_val & 0x003E) >> 1) * 8 + a = (data_val & 0x01) * 255 + pixels[x, y] = (r, g, b, a) + + elif tex_type == TextureType.Palette4bpp: + img = Image.new("P", (w, h)) + pixels = img.load() + palette = [0] * (256 * 4) + for y in range(h): + for x in range(0, w, 2): + pos = ((y * w) + x) // 2 + idx1 = (tex_data[pos] & 0xF0) >> 4 + idx2 = tex_data[pos] & 0x0F + + pixels[x, y] = idx1 + if x + 1 < w: + pixels[x + 1, y] = idx2 + + palette[idx1*4 : idx1*4+4] = [idx1*16, idx1*16, idx1*16, 255] + palette[idx2*4 : idx2*4+4] = [idx2*16, idx2*16, idx2*16, 255] + + elif tex_type == TextureType.Palette8bpp: + img = Image.new("P", (w, h)) + pixels = img.load() + palette = [0] * (256 * 4) + for y in range(h): + for x in range(w): + pos = (y * w) + x + idx = tex_data[pos] + pixels[x, y] = idx + palette[idx*4 : idx*4+4] = [idx, idx, idx, 255] + + elif tex_type == TextureType.Grayscale4bpp: + img = Image.new("L", (w, h)) + pixels = img.load() + for y in range(h): + for x in range(0, w, 2): + pos = ((y * w) + x) // 2 + g1 = tex_data[pos] & 0xF0 + g2 = (tex_data[pos] & 0x0F) << 4 + + pixels[x, y] = g1 + if x + 1 < w: + pixels[x + 1, y] = g2 + + elif tex_type == TextureType.Grayscale8bpp: + img = Image.new("L", (w, h)) + pixels = img.load() + for y in range(h): + for x in range(w): + pos = (y * w) + x + pixels[x, y] = tex_data[pos] + + elif tex_type == TextureType.GrayscaleAlpha4bpp: + img = Image.new("LA", (w, h)) + pixels = img.load() + for y in range(h): + for x in range(0, w, 2): + pos = ((y * w) + x) // 2 + val = tex_data[pos] + + d1 = (val & 0xF0) >> 4 + g1 = ((d1 & 0x0E) >> 1) * 32 + a1 = (d1 & 0x01) * 255 + pixels[x, y] = (g1, a1) + + if x + 1 < w: + d2 = val & 0x0F + g2 = ((d2 & 0x0E) >> 1) * 32 + a2 = (d2 & 0x01) * 255 + pixels[x + 1, y] = (g2, a2) + + elif tex_type == TextureType.GrayscaleAlpha8bpp: + img = Image.new("LA", (w, h)) + pixels = img.load() + for y in range(h): + for x in range(w): + pos = (y * w) + x + val = tex_data[pos] + g = val & 0xF0 + a = (val & 0x0F) << 4 + pixels[x, y] = (g, a) + + elif tex_type == TextureType.GrayscaleAlpha16bpp: + img = Image.new("LA", (w, h)) + pixels = img.load() + for y in range(h): + for x in range(w): + pos = ((y * w) + x) * 2 + g = tex_data[pos] + a = tex_data[pos + 1] + pixels[x, y] = (g, a) + else: + return None + + if is_palette: + if texture.tlut: + pal_bytes = texture.tlut.to_png_bytes() + pal_img = Image.open(BytesIO(pal_bytes)).convert("RGBA") + pal_pixels = pal_img.load() + + for y in range(pal_img.height): + for x in range(pal_img.width): + index = y * pal_img.width + x + if index >= 256: + continue + r, g, b, a = pal_pixels[x, y] + palette[index*4 : index*4+4] = [r, g, b, a] + + img.putpalette(bytearray(palette), rawmode='RGBA') + + out_buffer = BytesIO() + img.save(out_buffer, format="PNG") + return out_buffer.getvalue() + +def convert_png_to_n64_texture(png_bytes: bytes, texture_type: TextureType) -> Texture: + img = Image.open(BytesIO(png_bytes)) + texture = Texture(0, 0, texture_type) + N64Graphics.convert_raw_to_n64(texture, img) + return texture + +def write_header(resource_type: int, version: int) -> bytes: + endianness = 0x00 + game_version = 0 + rom_crc = 0 + rom_enum = 0 + magic = 0xDEADBEEFDEADBEEF + + # Struct format characters (assuming Little-Endian '<'): + # I = unsigned int (4 bytes) + # Q = unsigned long long (8 bytes) + # + # Order: Endianness(I), Type(I), Version(I), Magic(Q), GameVer(I), CRC(Q), Enum(I) + header_data = struct.pack( + ' 0: + header_data += b'\x00' * padding_needed + + return header_data + +def preprocess_asset(bytes_data: bytes, filename: str) -> bytes: + file = filename.lower() + + if file.lower().endswith('.bin'): + return bytes_data + + elif file.endswith('.png'): + if 'rgba16' in file: + tex_type = TextureType.RGBA16bpp + elif 'rgba32' in file: + tex_type = TextureType.RGBA32bpp + elif 'ci4' in file: + tex_type = TextureType.Palette4bpp + elif 'ci8' in file: + tex_type = TextureType.Palette8bpp + else: + raise ValueError(f"Unknown texture format in filename: {filename}") + + data = convert_png_to_n64_texture(bytes_data, tex_type) + + texture_type = 1 + width = data.width + height = data.height + tex_data_size = len(data.tex_data) + + otr_header = write_header(resource_type=0x4F544558, version=0x0) + tex_header = struct.pack( + ' bytes: + # If you want bytes to be embedded directly into the C file, you can preprocess them here. + return bytes_data + +def amalgamate(file_path, include_dirs, processed, out_file, assets_dir): + abs_path = os.path.abspath(file_path) + + if abs_path in processed: + return + processed.add(abs_path) + + try: + with open(abs_path, 'r', encoding='utf-8') as f: + content = f.read() + + # Step 1: Find and process `#asset` blocks ONLY + # Replaces `u8 array[] = { #asset ... };` with ALIGN_ASSET macro and extracts .bin + asset_block_pattern = re.compile( + r'(?:(?:static|const|ALIGNED8|extern)\s+)*u8\s+([a-zA-Z0-9_]+)\s*\[\]\s*=\s*\{\s*#asset\s+([<"])([^>"]+)[>"]\s*\};', + re.MULTILINE + ) + + def repl_asset_block(match): + var_name = match.group(1) + delimiter = match.group(2) + target_name = match.group(3) + + target_path = None + search_paths = list(include_dirs) + if delimiter == '"': + search_paths.insert(0, os.path.dirname(abs_path)) + + for path in search_paths: + potential_path = os.path.join(path, target_name) + if os.path.exists(potential_path): + target_path = potential_path + break + + if target_path: + try: + with open(target_path, 'rb') as bin_file: + raw_bytes = bin_file.read() + + resource_name = target_name + if resource_name.lower().endswith('.png'): + resource_name = resource_name[:-4] + + # Write the .bin companion file mirroring directory tree + if assets_dir: + companion_path = os.path.join(assets_dir, resource_name) + os.makedirs(os.path.dirname(companion_path), exist_ok=True) + with open(companion_path, 'wb') as cf: + cf.write(preprocess_asset(raw_bytes, target_name)) + + # Return formatted string literal block for C + return f'static const ALIGN_ASSET(2) char {var_name}[] = "__OTR__{resource_name}";' + + except Exception as e: + print(f"Warning: Failed to read asset file {target_path}: {e}") + return f"/* ERROR: Failed to process {target_name} */" + else: + print(f"Warning: Could not find asset file {target_name} requested from {abs_path}") + return f"/* ERROR: Could not find {target_name} */" + + # Apply the #asset replacement over the whole text file + content = asset_block_pattern.sub(repl_asset_block, content) + + # Step 2: Process the remaining lines one by one for standard #embeds and #includes + for line in content.splitlines(keepends=True): + + # Look for legacy #embed (leaves the surrounding u8 array intact, just injects hex) + embed = re.match(r'^\s*#\s*embed\s+([<"])([^>"]+)[>"]', line) + if embed: + delimiter = embed.group(1) + target_name = embed.group(2) + target_path = None + + search_paths = list(include_dirs) + if delimiter == '"': + search_paths.insert(0, os.path.dirname(abs_path)) + + for path in search_paths: + potential_path = os.path.join(path, target_name) + if os.path.exists(potential_path): + target_path = potential_path + break + + if target_path: + out_file.write(f"/* --- Start Embedded Bytes: {target_name} --- */\n") + try: + with open(target_path, 'rb') as bin_file: + raw_bytes = bin_file.read() + + raw_bytes = preprocess_embed(raw_bytes, target_name) + + # Write out raw hex array right into the C file + hex_array = [f"0x{b:02x}" for b in raw_bytes] + for i in range(0, len(hex_array), 16): + chunk = hex_array[i:i+16] + out_file.write(" " + ", ".join(chunk) + ",\n") + except Exception as e: + print(f"Warning: Failed to read embedded file {target_path}: {e}") + out_file.write(f"/* ERROR: Failed to read {target_name} */\n") + out_file.write(f"/* --- End Embedded Bytes: {target_name} --- */\n") + else: + out_file.write(f"/* ERROR: Could not find {target_name} */\n") + continue + + # Standard #include amalgamation + include = re.match(r'^\s*#\s*include\s+([<"])([^>"]+)[>"]', line) + if include: + delimiter = include.group(1) + header_name = include.group(2) + header_path = None + search_paths = list(include_dirs) + if delimiter == '"': + search_paths.insert(0, os.path.dirname(abs_path)) + + for path in search_paths: + potential_path = os.path.join(path, header_name) + if os.path.exists(potential_path): + header_path = potential_path + break + + if header_path: + out_file.write(f"/* --- Start: {header_name} --- */\n") + amalgamate(header_path, include_dirs, processed, out_file, assets_dir) + out_file.write(f"/* --- End: {header_name} --- */\n") + else: + out_file.write(line) + else: + out_file.write(line) + except Exception as e: + print(f"Warning: Could not process {abs_path}: {e}") + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Generate a Unity Build amalgamation.") + parser.add_argument('--out', required=True, help="The single output .c file") + parser.add_argument('--assets-dir', default=None, help="Root output directory for companion .bin files") + parser.add_argument('--includes', nargs='*', default=[], help="Include directories") + parser.add_argument('--srcs', nargs='+', required=True, help="Input .c files") + + args = parser.parse_args() + + global_processed = set() + + with open(args.out, 'w', encoding='utf-8') as out_file: + for src_file in args.srcs: + out_file.write(f"\n/* ========================================= */\n") + out_file.write(f"/* === Start of Source: {os.path.basename(src_file)} === */\n") + out_file.write(f"/* ========================================= */\n\n") + + amalgamate(src_file, args.includes, global_processed, out_file, args.assets_dir) \ No newline at end of file diff --git a/tools/sample_editor.py b/tools/sample_editor.py new file mode 100755 index 000000000..6f93c4b78 --- /dev/null +++ b/tools/sample_editor.py @@ -0,0 +1,5396 @@ +#!/usr/bin/env python3 +""" +Starship Sample Editor — browse, export, and replace audio samples in an o2r archive. + +Run without arguments (or with `gui`) to open the graphical interface. +All subcommands are also available on the CLI: + + list [--filter TEXT] [--codec N] + info + export [--out FILE] [--decode] + play + replace --input AUDIO [--out-dir DIR] + gui [archive] +""" + +from __future__ import annotations + +import argparse +import array +import atexit +import json +import re +import os +import shutil +import struct +import subprocess +import sys +import tempfile +import threading +import wave +import xml.dom.minidom +import xml.etree.ElementTree as ET +import zipfile + +# ─── constants ──────────────────────────────────────────────────────────────── + +OTR_HEADER_SIZE = 64 +BODY_OFFSET = OTR_HEADER_SIZE +SAMPLE_RES_TYPE = 0x41554643 # Torch::ResourceType::Sample (AUFC) +LOOP_RES_TYPE = 0x4150434C # Torch::ResourceType::AdpcmLoop (APCL) +BOOK_RES_TYPE = 0x41504342 # Torch::ResourceType::AdpcmBook (APCB) +INST_RES_TYPE = 0x494E5354 # Torch::ResourceType::Instrument (INST) +DRUM_RES_TYPE = 0x4452554D # Torch::ResourceType::Drum (DRUM) +FONT_RES_TYPE = 0x53464E54 # Torch::ResourceType::SoundFont (SFNT) +SEQ_RES_TYPE = 0x53455143 # SF64::ResourceType::Sequence (SEQC) +BLOB_RES_TYPE = 0x4F424C42 # Torch::ResourceType::Blob (OBLB) +ATBL_RES_TYPE = 0x4154424C # Torch::ResourceType::AudioTable (ATBL) + +CODEC_NAMES = {0: "ADPCM", 1: "S8", 2: "S16MEM", 3: "SMALL_ADPCM", 4: "REVERB", 5: "S16"} +MEDIUM_NAMES = {0: "Ram", 1: "Unk", 2: "Cart", 3: "Disk", 5: "RamUnloaded"} + +# N64 VADPCM: each 9-byte frame decodes to 16 S16 samples +ADPCM_FRAME_BYTES = 9 +ADPCM_FRAME_SAMPLES = 16 + +AUDIO_REF_HZ = 32000.0 +MIXER_RATE_HZ = 32000 + +LOOP_INFINITE = 0xFFFFFFFF + +# CRC-64 table — matches libultraship/src/ship/utils/StrHash64.cpp exactly. +# Used to map archive entry paths to the loop_hash/book_hash stored in sample binaries. +_CRC64_TABLE = ( + 0x0000000000000000, 0x42f0e1eba9ea3693, 0x85e1c3d753d46d26, 0xc711223cfa3e5bb5, + 0x493366450e42ecdf, 0x0bc387aea7a8da4c, 0xccd2a5925d9681f9, 0x8e224479f47cb76a, + 0x9266cc8a1c85d9be, 0xd0962d61b56fef2d, 0x17870f5d4f51b498, 0x5577eeb6e6bb820b, + 0xdb55aacf12c73561, 0x99a54b24bb2d03f2, 0x5eb4691841135847, 0x1c4488f3e8f96ed4, + 0x663d78ff90e185ef, 0x24cd9914390bb37c, 0xe3dcbb28c335e8c9, 0xa12c5ac36adfde5a, + 0x2f0e1eba9ea36930, 0x6dfeff5137495fa3, 0xaaefdd6dcd770416, 0xe81f3c86649d3285, + 0xf45bb4758c645c51, 0xb6ab559e258e6ac2, 0x71ba77a2dfb03177, 0x334a9649765a07e4, + 0xbd68d2308226b08e, 0xff9833db2bcc861d, 0x388911e7d1f2dda8, 0x7a79f00c7818eb3b, + 0xcc7af1ff21c30bde, 0x8e8a101488293d4d, 0x499b3228721766f8, 0x0b6bd3c3dbfd506b, + 0x854997ba2f81e701, 0xc7b97651866bd192, 0x00a8546d7c558a27, 0x4258b586d5bfbcb4, + 0x5e1c3d753d46d260, 0x1cecdc9e94ace4f3, 0xdbfdfea26e92bf46, 0x990d1f49c77889d5, + 0x172f5b3033043ebf, 0x55dfbadb9aee082c, 0x92ce98e760d05399, 0xd03e790cc93a650a, + 0xaa478900b1228e31, 0xe8b768eb18c8b8a2, 0x2fa64ad7e2f6e317, 0x6d56ab3c4b1cd584, + 0xe374ef45bf6062ee, 0xa1840eae168a547d, 0x66952c92ecb40fc8, 0x2465cd79455e395b, + 0x3821458aada7578f, 0x7ad1a461044d611c, 0xbdc0865dfe733aa9, 0xff3067b657990c3a, + 0x711223cfa3e5bb50, 0x33e2c2240a0f8dc3, 0xf4f3e018f031d676, 0xb60301f359dbe0e5, + 0xda050215ea6c212f, 0x98f5e3fe438617bc, 0x5fe4c1c2b9b84c09, 0x1d14202910527a9a, + 0x93366450e42ecdf0, 0xd1c685bb4dc4fb63, 0x16d7a787b7faa0d6, 0x5427466c1e109645, + 0x4863ce9ff6e9f891, 0x0a932f745f03ce02, 0xcd820d48a53d95b7, 0x8f72eca30cd7a324, + 0x0150a8daf8ab144e, 0x43a04931514122dd, 0x84b16b0dab7f7968, 0xc6418ae602954ffb, + 0xbc387aea7a8da4c0, 0xfec89b01d3679253, 0x39d9b93d2959c9e6, 0x7b2958d680b3ff75, + 0xf50b1caf74cf481f, 0xb7fbfd44dd257e8c, 0x70eadf78271b2539, 0x321a3e938ef113aa, + 0x2e5eb66066087d7e, 0x6cae578bcfe24bed, 0xabbf75b735dc1058, 0xe94f945c9c3626cb, + 0x676dd025684a91a1, 0x259d31cec1a0a732, 0xe28c13f23b9efc87, 0xa07cf2199274ca14, + 0x167ff3eacbaf2af1, 0x548f120162451c62, 0x939e303d987b47d7, 0xd16ed1d631917144, + 0x5f4c95afc5edc62e, 0x1dbc74446c07f0bd, 0xdaad56789639ab08, 0x985db7933fd39d9b, + 0x84193f60d72af34f, 0xc6e9de8b7ec0c5dc, 0x01f8fcb784fe9e69, 0x43081d5c2d14a8fa, + 0xcd2a5925d9681f90, 0x8fdab8ce70822903, 0x48cb9af28abc72b6, 0x0a3b7b1923564425, + 0x70428b155b4eaf1e, 0x32b26afef2a4998d, 0xf5a348c2089ac238, 0xb753a929a170f4ab, + 0x3971ed50550c43c1, 0x7b810cbbfce67552, 0xbc902e8706d82ee7, 0xfe60cf6caf321874, + 0xe224479f47cb76a0, 0xa0d4a674ee214033, 0x67c58448141f1b86, 0x253565a3bdf52d15, + 0xab1721da49899a7f, 0xe9e7c031e063acec, 0x2ef6e20d1a5df759, 0x6c0603e6b3b7c1ca, + 0xf6fae5c07d3274cd, 0xb40a042bd4d8425e, 0x731b26172ee619eb, 0x31ebc7fc870c2f78, + 0xbfc9838573709812, 0xfd39626eda9aae81, 0x3a28405220a4f534, 0x78d8a1b9894ec3a7, + 0x649c294a61b7ad73, 0x266cc8a1c85d9be0, 0xe17dea9d3263c055, 0xa38d0b769b89f6c6, + 0x2daf4f0f6ff541ac, 0x6f5faee4c61f773f, 0xa84e8cd83c212c8a, 0xeabe6d3395cb1a19, + 0x90c79d3fedd3f122, 0xd2377cd44439c7b1, 0x15265ee8be079c04, 0x57d6bf0317edaa97, + 0xd9f4fb7ae3911dfd, 0x9b041a914a7b2b6e, 0x5c1538adb04570db, 0x1ee5d94619af4648, + 0x02a151b5f156289c, 0x4051b05e58bc1e0f, 0x87409262a28245ba, 0xc5b073890b687329, + 0x4b9237f0ff14c443, 0x0962d61b56fef2d0, 0xce73f427acc0a965, 0x8c8315cc052a9ff6, + 0x3a80143f5cf17f13, 0x7870f5d4f51b4980, 0xbf61d7e80f251235, 0xfd913603a6cf24a6, + 0x73b3727a52b393cc, 0x31439391fb59a55f, 0xf652b1ad0167feea, 0xb4a25046a88dc879, + 0xa8e6d8b54074a6ad, 0xea16395ee99e903e, 0x2d071b6213a0cb8b, 0x6ff7fa89ba4afd18, + 0xe1d5bef04e364a72, 0xa3255f1be7dc7ce1, 0x64347d271de22754, 0x26c49cccb40811c7, + 0x5cbd6cc0cc10fafc, 0x1e4d8d2b65facc6f, 0xd95caf179fc497da, 0x9bac4efc362ea149, + 0x158e0a85c2521623, 0x577eeb6e6bb820b0, 0x906fc95291867b05, 0xd29f28b9386c4d96, + 0xcedba04ad0952342, 0x8c2b41a1797f15d1, 0x4b3a639d83414e64, 0x09ca82762aab78f7, + 0x87e8c60fded7cf9d, 0xc51827e4773df90e, 0x020905d88d03a2bb, 0x40f9e43324e99428, + 0x2cffe7d5975e55e2, 0x6e0f063e3eb46371, 0xa91e2402c48a38c4, 0xebeec5e96d600e57, + 0x65cc8190991cb93d, 0x273c607b30f68fae, 0xe02d4247cac8d41b, 0xa2dda3ac6322e288, + 0xbe992b5f8bdb8c5c, 0xfc69cab42231bacf, 0x3b78e888d80fe17a, 0x7988096371e5d7e9, + 0xf7aa4d1a85996083, 0xb55aacf12c735610, 0x724b8ecdd64d0da5, 0x30bb6f267fa73b36, + 0x4ac29f2a07bfd00d, 0x08327ec1ae55e69e, 0xcf235cfd546bbd2b, 0x8dd3bd16fd818bb8, + 0x03f1f96f09fd3cd2, 0x41011884a0170a41, 0x86103ab85a2951f4, 0xc4e0db53f3c36767, + 0xd8a453a01b3a09b3, 0x9a54b24bb2d03f20, 0x5d45907748ee6495, 0x1fb5719ce1045206, + 0x919735e51578e56c, 0xd367d40ebc92d3ff, 0x1476f63246ac884a, 0x568617d9ef46bed9, + 0xe085162ab69d5e3c, 0xa275f7c11f7768af, 0x6564d5fde549331a, 0x279434164ca30589, + 0xa9b6706fb8dfb2e3, 0xeb46918411358470, 0x2c57b3b8eb0bdfc5, 0x6ea7525342e1e956, + 0x72e3daa0aa188782, 0x30133b4b03f2b111, 0xf7021977f9cceaa4, 0xb5f2f89c5026dc37, + 0x3bd0bce5a45a6b5d, 0x79205d0e0db05dce, 0xbe317f32f78e067b, 0xfcc19ed95e6430e8, + 0x86b86ed5267cdbd3, 0xc4488f3e8f96ed40, 0x0359ad0275a8b6f5, 0x41a94ce9dc428066, + 0xcf8b0890283e370c, 0x8d7be97b81d4019f, 0x4a6acb477bea5a2a, 0x089a2aacd2006cb9, + 0x14dea25f3af9026d, 0x562e43b4931334fe, 0x913f6188692d6f4b, 0xd3cf8063c0c759d8, + 0x5dedc41a34bbeeb2, 0x1f1d25f19d51d821, 0xd80c07cd676f8394, 0x9afce626ce85b507, +) + + +# ─── CRC-64 hash (matches Archive::Load → CRC64(filePath)) ─────────────────── + +def crc64_hash(s: str) -> int: + """Compute the CRC-64 of a UTF-8 string, exactly as libultraship does.""" + crc = 0xFFFFFFFFFFFFFFFF + for byte in s.encode("utf-8"): + crc = _CRC64_TABLE[((crc >> 56) ^ byte) & 0xFF] ^ ((crc << 8) & 0xFFFFFFFFFFFFFFFF) + return crc + + +def _extract_path_addr(path: str) -> tuple[int, str]: + """Return (sort_key, display_str) for address-based sorting. + + Priority: + 1. Explicit 0x literal in path → hex, displayed as 0x… + 2. Last path component is all hex chars AND (contains a–f OR is zero-padded + like '060') → interpreted as hex, displayed as 0x… + 3. Last decimal integer anywhere in path → decimal value, displayed as 0x… + All non-empty results are displayed in 0x… form. + """ + # 1. Explicit 0x prefix + m = re.search(r'0[xX]([0-9a-fA-F]+)', path) + if m: + val = int(m.group(1), 16) + return val, f"0x{val:X}" + + # 2. Last path component that looks like a bare hex address + last = path.rstrip("/").rsplit("/", 1)[-1] + if last and re.fullmatch(r"[0-9a-fA-F]+", last, re.IGNORECASE): + has_af = bool(re.search(r"[a-fA-F]", last)) + zero_padded = len(last) > 1 and last[0] == "0" + if has_af or zero_padded: + val = int(last, 16) + return val, f"0x{val:X}" + + # 3. Last decimal integer in path, shown as hex + hits = re.findall(r"\d+", path) + if hits: + val = int(hits[-1]) + return val, f"0x{val:X}" + return 0, "" + + +# ─── binary parsing ─────────────────────────────────────────────────────────── + +def _res_type(data: bytes) -> int: + """Read the ResourceType field from an OTR header (bytes 4-7 LE).""" + if len(data) < 8: + return 0 + return struct.unpack_from(" int: + """Read the version field from an OTR header (bytes 8-11 LE).""" + if len(data) < 12: + return 0 + return struct.unpack_from(" bool: + if len(data) < BODY_OFFSET + 8: + return False + if data[0:1] == b"<": + return False + return _res_type(data) == SAMPLE_RES_TYPE + + +def parse_sample_binary(data: bytes) -> dict | None: + """Parse a Sample binary entry. + + Handles two on-disk versions: + v1 — full entry: codec, medium, unk, size, loop_hash, book_hash, raw[size] + v2 — redirect: canonical_hash (u64) only; audio data lives in the canonical entry + """ + if len(data) < BODY_OFFSET + 8: + return None + + version = _res_version(data) + + if version == 2: + canonical_hash = struct.unpack_from(" dict | None: + """Parse an AdpcmLoop entry from its OTR binary (after 64-byte header). + + Layout (all LE): + start u32 — first looping frame (inclusive) + end u32 — last looping frame (exclusive) + count u32 — loop iterations; 0xFFFFFFFF = infinite + state[16] i16 — ADPCM decoder state at loop point (only if count != 0) + """ + off = BODY_OFFSET + if len(data) < off + 12: + return None + start = struct.unpack_from("= off + 12 + 32: + for i in range(16): + state.append(struct.unpack_from(" dict | None: + """Parse an AdpcmBook entry from its OTR binary (after 64-byte header). + + Layout (all LE): + order u32 — predictor order (history depth per half-frame) + numPredictors u32 — number of codebook entries + book_size u32 — = 8 * order * numPredictors + book[book_size] i16 — flat coefficient table; layout [pred][j=0..order][k=0..8] + maps to coef_table[pred][k][j] for the VADPCM decoder + + The coefficients encode how past samples predict the next one. + Each predictor is a set of (order × 8) coefficients that form a prediction + filter for one 8-sample sub-block within a 16-sample ADPCM frame. + """ + off = BODY_OFFSET + if len(data) < off + 12: + return None + order = struct.unpack_from(" list[tuple[int, float, str]]: + """Extract (sample_hash, tuning, slot) triples from an Instrument binary entry. + + Instrument body layout (all LE, no padding): + isRelocated u8 + normalRangeLo u8 + normalRangeHi u8 + adsrDecayIndex u8 + envelope_hash u64 + low_sample_hash u64 tuning_low f32 ← slot "low" + norm_sample_hash u64 tuning_norm f32 ← slot "normal" + high_sample_hash u64 tuning_high f32 ← slot "high" + + Three pitch slots: low (below normalRangeLo), normal, high (above normalRangeHi). + A slot with hash=0 means that pitch range reuses the normal sample. + """ + off = BODY_OFFSET + if len(data) < off + 48: + return [] + pairs = [] + off += 4 # skip 4 header bytes + off += 8 # skip envelope_hash + for slot in _PITCH_SLOTS: + h = struct.unpack_from(" tuple[int, float] | None: + """Extract (sample_hash, tuning) from a Drum binary entry. + + Drum body layout (all LE, no padding): + adsrDecayIndex u8 + pan u8 + isRelocated u8 + sample_hash u64 + tuning f32 + envelope_hash u64 + """ + off = BODY_OFFSET + if len(data) < off + 15: + return None + off += 3 # skip 3 header bytes + h = struct.unpack_from(" dict | None: + """Parse a SoundFont binary entry. + + Layout (all LE, after 64-byte OTR header): + numInstruments u8 + numDrums u8 + sampleBankId1 u8 + sampleBankId2 u8 + inst_crcs[] u64 × numInstruments — CRC64 of each instrument archive path + drum_crcs[] u64 × numDrums — CRC64 of each drum archive path + """ + off = BODY_OFFSET + if len(data) < off + 4: + return None + num_inst = data[off] + num_drums = data[off + 1] + bank_id1 = data[off + 2] + off += 4 + inst_crcs, drum_crcs = [], [] + for _ in range(num_inst): + if len(data) < off + 8: + break + inst_crcs.append(struct.unpack_from(" list: + """Build the 3D prediction table used by _decode_frame. + + flat_book layout (from binary): [pred][j=0..order-1][k=0..7] + Stored as pred * order * 8 + j * 8 + k → coef_table[pred][k][j] + Extra columns (j >= order) are derived and encode cross-frame prediction. + """ + table = [] + for pred in range(num_predictors): + entry = [[0] * (order + 8) for _ in range(8)] + base = pred * order * 8 + for j in range(order): + for k in range(8): + entry[k][j] = flat_book[base + j * 8 + k] + + # Derived entries — replicate readaifccodebook logic exactly + for k in range(1, 8): + entry[k][order] = entry[k - 1][order - 1] + entry[0][order] = 1 << 11 # 2048 + + for k in range(1, 8): + for j in range(8): + if j < k: + entry[j][k + order] = 0 + else: + entry[j][k + order] = entry[j - k][order] + + table.append(entry) + return table + + +def _decode_frame(frame: bytes, state: list, order: int, coef_table: list) -> None: + """Decode one 9-byte ADPCM frame, updating state[0..15] in-place.""" + header = frame[0] + scale = 1 << (header >> 4) + optimalp = header & 0xF + + ix = [0] * 16 + for i in range(0, 16, 2): + c = frame[1 + i // 2] + ix[i] = c >> 4 + ix[i + 1] = c & 0xF + for i in range(16): + if ix[i] >= 8: + ix[i] -= 16 + ix[i] *= scale + + entry = coef_table[optimalp] + in_vec = [0] * (order + 8) + + for half in range(2): + # Seed in_vec with the last `order` decoded samples from the prior half-block + if half == 0: + for i in range(order): + in_vec[i] = state[16 - order + i] + else: + for i in range(order): + in_vec[i] = state[8 - order + i] + + for i in range(8): + ind = half * 8 + i + in_vec[order + i] = ix[ind] + # floor(dot(entry[i], in_vec, length=order+i) / 2048) + dp = sum(entry[i][x] * in_vec[x] for x in range(order + i)) + state[ind] = dp // 2048 + ix[ind] + + +def vadpcm_to_pcm(raw: bytes, book: dict) -> bytes: + """Decode N64 VADPCM bytes to S16 little-endian PCM. + + The output sample rate is whatever rate the ROM encoded the sample at. + Call at 32 kHz if no tuning is known; the engine tunes pitch by sample rate. + """ + order = book["order"] + num_pred = book["num_predictors"] + flat_book = book["book"] + coef_table = _build_coef_table(order, num_pred, flat_book) + + state = [0] * 16 + output = array.array("h") # signed 16-bit + + n_frames = len(raw) // ADPCM_FRAME_BYTES + for f in range(n_frames): + frame = raw[f * ADPCM_FRAME_BYTES: (f + 1) * ADPCM_FRAME_BYTES] + _decode_frame(frame, state, order, coef_table) + for v in state: + output.append(max(-32768, min(32767, v))) + + return output.tobytes() + + +# ─── archive helpers ────────────────────────────────────────────────────────── + +def list_samples(archive_path: str, + name_filter: str = "", + codec_filter: int = -1, + bank_filter: str = "") -> list[dict]: + """Single-pass scan: collect samples, loops, books, instruments, drums, and + soundfonts; cross-link everything by CRC-64 hash to infer per-sample tuning, + bank membership, and instrument usage.""" + loop_by_hash: dict[int, dict] = {} + book_by_hash: dict[int, dict] = {} + tuning_lists: dict[int, list[float]] = {} + pitch_roles: dict[int, set[str]] = {} + font_by_inst_crc: dict[int, str] = {} # inst_crc64 → font_path + font_by_drum_crc: dict[int, str] = {} # drum_crc64 → font_path + inst_slot_data: dict[int, list[tuple[str, str, float]]] = {} # hash → [(inst_path, slot, tuning)] + drum_slot_data: dict[int, list[tuple[str, float]]] = {} # hash → [(drum_path, tuning)] + raw_samples: list[tuple[str, bytes]] = [] + + def _add_tuning(sample_hash: int, tuning: float): + tuning_lists.setdefault(sample_hash, []).append(tuning) + + with zipfile.ZipFile(archive_path, "r") as z: + for name in z.namelist(): + data = z.read(name) + if len(data) < BODY_OFFSET + 4 or data[0:1] == b"<": + continue + rt = _res_type(data) + if rt == SAMPLE_RES_TYPE: + raw_samples.append((name, data)) + elif rt == LOOP_RES_TYPE: + parsed = parse_loop_binary(data) + if parsed is not None: + loop_by_hash[crc64_hash(name)] = parsed + elif rt == BOOK_RES_TYPE: + parsed = parse_book_binary(data) + if parsed is not None: + book_by_hash[crc64_hash(name)] = parsed + elif rt == FONT_RES_TYPE: + parsed = parse_soundfont_binary(data) + if parsed: + for crc in parsed["inst_crcs"]: + if crc: + font_by_inst_crc[crc] = name + for crc in parsed["drum_crcs"]: + if crc: + font_by_drum_crc[crc] = name + elif rt == INST_RES_TYPE: + for h, t, slot in parse_instrument_tunings(data): + _add_tuning(h, t) + pitch_roles.setdefault(h, set()).add(slot) + inst_slot_data.setdefault(h, []).append((name, slot, t)) + elif rt == DRUM_RES_TYPE: + pair = parse_drum_tuning(data) + if pair: + _add_tuning(pair[0], pair[1]) + pitch_roles.setdefault(pair[0], set()).add("drum") + drum_slot_data.setdefault(pair[0], []).append((name, pair[1])) + + results = [] + pending_redirects: list[tuple[str, dict]] = [] # (name, partial_info) + + for name, data in raw_samples: + if name_filter and name_filter.lower() not in name.lower(): + continue + info = parse_sample_binary(data) + if info is None: + continue + + if info["is_redirect"]: + pending_redirects.append((name, info)) + continue + + if codec_filter >= 0 and info["codec"] != codec_filter: + continue + h = crc64_hash(name) + info["path"] = name + info["hash"] = h + addr, addr_str = _extract_path_addr(name) + info["addr"] = addr + info["addr_str"] = addr_str + info["loop_data"] = loop_by_hash.get(info["loop_hash"]) + info["book_data"] = book_by_hash.get(info["book_hash"]) + info["pitch_roles"] = sorted( + pitch_roles.get(h, set()), + key=lambda r: _PITCH_ORDER.index(r) if r in _PITCH_ORDER else 99) + + # Resolve tuning: prefer the value closest to 1.0 as the "normal pitch" reference + all_t = tuning_lists.get(h, []) + if all_t: + info["tuning"] = min(all_t, key=lambda t: abs(t - 1.0)) + info["all_tunings"] = sorted(set(all_t)) + info["sample_rate"] = round(info["tuning"] * AUDIO_REF_HZ) + else: + info["tuning"] = None + info["all_tunings"] = [] + info["sample_rate"] = None + + # Bank + instrument provenance + banks: set[str] = set() + used_by: list[str] = [] + provenance: list[dict] = [] + slot_tunings: dict[str, float] = {} + for ipath, slot, t in inst_slot_data.get(h, []): + font = font_by_inst_crc.get(crc64_hash(ipath), "") + if font: + banks.add(font) + used_by.append(f"{_font_short(font) if font else '?'}:{_path_tail(ipath)}({slot[0].upper()})") + provenance.append({"font": font, "inst_path": ipath, "slot": slot, "tuning": t}) + slot_tunings.setdefault(slot, t) + for dpath, t in drum_slot_data.get(h, []): + font = font_by_drum_crc.get(crc64_hash(dpath), "") + if font: + banks.add(font) + used_by.append(f"{_font_short(font) if font else '?'}:{_path_tail(dpath)}(D)") + provenance.append({"font": font, "inst_path": dpath, "slot": "drum", "tuning": t}) + slot_tunings.setdefault("drum", t) + info["banks"] = sorted(banks) + info["used_by"] = sorted(used_by) + info["provenance"] = provenance + info["slot_tunings"] = slot_tunings + + if bank_filter and bank_filter not in banks: + continue + + results.append(info) + + # Resolve v2 redirects: copy canonical's audio fields, override path-specific ones. + canonical_by_hash = {s["hash"]: s for s in results} + for name, rinfo in pending_redirects: + canonical = canonical_by_hash.get(rinfo["canonical_hash"]) + if canonical is None: + continue + if codec_filter >= 0 and canonical["codec"] != codec_filter: + continue + h = crc64_hash(name) + info = dict(canonical) + info["path"] = name + info["hash"] = h + info["is_redirect"] = True + info["canonical_hash"] = rinfo["canonical_hash"] + info["canonical_path"] = canonical["path"] + addr, addr_str = _extract_path_addr(name) + info["addr"] = addr + info["addr_str"] = addr_str + # Instruments/drums now reference the canonical hash directly, so the + # redirect's own hash is unreferenced. Use whatever pitch_roles the + # redirect itself has (old archives where instruments still pointed here), + # falling back to the canonical's roles for freshly-extracted archives. + own_roles = pitch_roles.get(h, set()) + if own_roles: + info["pitch_roles"] = sorted( + own_roles, + key=lambda r: _PITCH_ORDER.index(r) if r in _PITCH_ORDER else 99) + # else: keep canonical's pitch_roles (already copied via dict(canonical)) + all_t = tuning_lists.get(h, []) + if all_t: + info["tuning"] = min(all_t, key=lambda t: abs(t - 1.0)) + info["all_tunings"] = sorted(set(all_t)) + info["sample_rate"] = round(info["tuning"] * AUDIO_REF_HZ) + # else: keep canonical's tuning (already copied via dict(canonical)) + # Provenance for redirects: check if this redirect path is referenced by its own + # instruments/drums (older archives), otherwise inherit canonical's provenance. + own_banks: set[str] = set() + own_used: list[str] = [] + own_prov: list[dict] = [] + own_slot_t: dict[str, float] = {} + for ipath, slot, t in inst_slot_data.get(h, []): + font = font_by_inst_crc.get(crc64_hash(ipath), "") + if font: + own_banks.add(font) + own_used.append(f"{_font_short(font) if font else '?'}:{_path_tail(ipath)}({slot[0].upper()})") + own_prov.append({"font": font, "inst_path": ipath, "slot": slot, "tuning": t}) + own_slot_t.setdefault(slot, t) + for dpath, t in drum_slot_data.get(h, []): + font = font_by_drum_crc.get(crc64_hash(dpath), "") + if font: + own_banks.add(font) + own_used.append(f"{_font_short(font) if font else '?'}:{_path_tail(dpath)}(D)") + own_prov.append({"font": font, "inst_path": dpath, "slot": "drum", "tuning": t}) + own_slot_t.setdefault("drum", t) + if own_banks: + info["banks"] = sorted(own_banks) + info["used_by"] = sorted(own_used) + info["provenance"] = own_prov + info["slot_tunings"] = own_slot_t + if bank_filter and bank_filter not in info.get("banks", []): + continue + results.append(info) + + results.sort(key=lambda x: x["path"]) + return results + + +def list_sequences(archive_path: str) -> list[dict]: + """Scan an archive for sequences. + + Supports three source formats: + - AudioTable (ATBL) + SEQC: the main game archive layout written by Torch. + The ATBL encodes the full 66-entry table including alias entries (size==0). + ATBL CRCs match CRC64(path) of the corresponding SEQC entry. + Alias entries share a CRC with a non-alias entry → same path. + - Binary V2 (SEQC): mod-packed format; not covered by an ATBL. + - XML V0 ( root): mod XML descriptors (raw or streamed). + """ + _medium_map = {0: "Ram", 1: "Unk", 2: "Cart", 3: "Disk", 5: "RamUnloaded"} + _cache_map = {0: "Temporary", 1: "Persistent", 2: "Either", 3: "Permanent"} + + results: list[dict] = [] + seen_paths: set[str] = set() + + with zipfile.ZipFile(archive_path, "r") as z: + all_names = z.namelist() + + # ── pass 1: build CRC→path map for SEQC entries ───────────────────── + # ATBL stores CRC64(path) of each referenced SEQC entry as its "romAddr". + # (Note: the embedded seqNumber in the SEQC body is the ROM-offset order, + # NOT the ATBL table index. Use the CRC for matching, not seqNumber.) + seqc_crc_to_info: dict[int, dict] = {} + for name in all_names: + data = z.read(name) + if len(data) < BODY_OFFSET + 4 or data[0:1] == b"<": + continue + if _res_type(data) != SEQ_RES_TYPE: + continue + off = BODY_OFFSET + seq_data_size = struct.unpack_from(" len(data): + continue + med_byte = data[off + 1] + cache_byte = data[off + 2] + seqc_crc_to_info[crc64_hash(name)] = dict( + path = name, + med_byte = med_byte, + cache_byte = cache_byte, + size = seq_data_size, + ) + seen_paths.add(name) + + # ── pass 2: ATBL-driven scan — all entries including aliases ───────── + # Aliases (size==0) have the same CRC as their canonical entry; the lookup + # via seqc_crc_to_info naturally returns the canonical path for both. + for name in all_names: + data = z.read(name) + if len(data) < BODY_OFFSET + 10 or data[0:1] == b"<": + continue + if _res_type(data) != ATBL_RES_TYPE: + continue + b = data[BODY_OFFSET:] + table_count = struct.unpack_from(" descriptors) ────────────────────────── + for name in all_names: + if not name.endswith(".xml"): + continue + data = z.read(name) + if not data or data[0:1] != b"<": + continue + try: + root = ET.fromstring(data.decode("utf-8", errors="replace")) + except Exception: + continue + if root.tag != "Sequence": + continue + try: + seq_index = int(root.get("Index", -1)) + except (ValueError, TypeError): + seq_index = -1 + seq_name = _SEQ_ID_NAMES[seq_index] if 0 <= seq_index < len(_SEQ_ID_NAMES) else "?" + streamed = root.get("Streamed", "false").lower() == "true" + results.append(dict( + path = name, + seq_index = seq_index, + seq_name = seq_name, + format = "Streamed" if streamed else "XML", + streamed = streamed, + medium = root.get("Medium", ""), + cache = root.get("CachePolicy", ""), + size = int(root.get("Size", 0) or 0), + looped = root.get("Looped", "true").lower() == "true", + stereo = root.get("Stereo", "false").lower() == "false", + length_ms = int(root.get("Length", 0) or 0), + audio_path = root.get("Path", ""), + is_alias = False, + )) + + results.sort(key=lambda s: ( + s["seq_index"], + {"Blob": 0, "Alias": 1, "Binary": 2, "XML": 3, "Streamed": 4}.get(s["format"], 5), + )) + return results + + +def read_sample(archive_path: str, asset_path: str) -> tuple[dict | None, bytes | None]: + """Read one sample entry; no loop/book resolution.""" + with zipfile.ZipFile(archive_path, "r") as z: + if asset_path not in z.namelist(): + return None, None + data = z.read(asset_path) + return parse_sample_binary(data), data + + +def read_sample_full(archive_path: str, + asset_path: str) -> tuple[dict | None, dict | None, dict | None]: + """Read one sample plus its loop, book, and tuning by scanning the same archive. + + Transparently follows v2 redirect entries to their canonical sample. + """ + target_hash = crc64_hash(asset_path) + + with zipfile.ZipFile(archive_path, "r") as z: + if asset_path not in z.namelist(): + return None, None, None + data = z.read(asset_path) + info = parse_sample_binary(data) + if info is None: + return None, None, None + + # Follow redirect: find canonical entry by CRC64 hash + if info.get("is_redirect"): + canonical_hash = info["canonical_hash"] + for name in z.namelist(): + if crc64_hash(name) == canonical_hash: + cdata = z.read(name) + cinfo = parse_sample_binary(cdata) + if cinfo and not cinfo.get("is_redirect"): + cinfo["canonical_path"] = name + info = cinfo + info["is_redirect"] = True + info["canonical_hash"] = canonical_hash + info["canonical_path"] = name + break + if info.get("is_redirect") and not info.get("canonical_path"): + return None, None, None + + loop: dict | None = None + book: dict | None = None + all_tunings: list[float] = [] + pitch_role_set: set[str] = set() + + for name in z.namelist(): + entry = z.read(name) + if len(entry) < BODY_OFFSET + 4 or entry[0:1] == b"<": + continue + rt = _res_type(entry) + h = crc64_hash(name) + if rt == LOOP_RES_TYPE and h == info["loop_hash"]: + loop = parse_loop_binary(entry) + elif rt == BOOK_RES_TYPE and h == info["book_hash"]: + book = parse_book_binary(entry) + elif rt == INST_RES_TYPE: + for sh, t, slot in parse_instrument_tunings(entry): + if sh == target_hash: + all_tunings.append(t) + pitch_role_set.add(slot) + elif rt == DRUM_RES_TYPE: + pair = parse_drum_tuning(entry) + if pair and pair[0] == target_hash: + all_tunings.append(pair[1]) + pitch_role_set.add("drum") + + info["loop_data"] = loop + info["book_data"] = book + info["hash"] = crc64_hash(asset_path) + info["pitch_roles"] = sorted( + pitch_role_set, + key=lambda r: _PITCH_ORDER.index(r) if r in _PITCH_ORDER else 99) + addr, addr_str = _extract_path_addr(asset_path) + info["addr"] = addr + info["addr_str"] = addr_str + info["all_tunings"] = sorted(set(all_tunings)) + if all_tunings: + info["tuning"] = min(all_tunings, key=lambda t: abs(t - 1.0)) + info["sample_rate"] = round(info["tuning"] * AUDIO_REF_HZ) + else: + info["tuning"] = None + info["sample_rate"] = None + return info, loop, book + + +# ─── shared helpers ─────────────────────────────────────────────────────────── + +def _fmt_size(n: int) -> str: + return f"{n / 1024:.1f} KB" if n >= 1024 else f"{n} B" + + +def _fmt_pitch_short(roles: list[str]) -> str: + if not roles: + return "" + abbr = {"low": "L", "normal": "N", "high": "H", "drum": "D"} + return "+".join(abbr.get(r, r[0].upper()) for r in roles) + + +def _fmt_pitch_long(roles: list[str]) -> str: + if not roles: + return "—" + return ", ".join(r.capitalize() for r in roles) + + +def _font_short(path: str) -> str: + """Extract the hex-address suffix from a SoundFont archive path for display.""" + m = re.search(r"sound_font[_/]?([0-9A-Fa-f]+)$", path, re.IGNORECASE) + if m: + return m.group(1) + last = path.rsplit("/", 1)[-1] + return last[-10:] if last else path + + +def _path_tail(path: str) -> str: + """Return the last path component.""" + return path.rsplit("/", 1)[-1] + + +def _fmt_duration(pcm_samples: int, rate: int = MIXER_RATE_HZ) -> str: + secs = pcm_samples / rate + return f"{secs:.3f}s" + + +def _write_wav(pcm: bytes, path: str, channels: int = 1, rate: int = MIXER_RATE_HZ): + with wave.open(path, "wb") as w: + w.setnchannels(channels) + w.setsampwidth(2) + w.setframerate(rate) + w.writeframes(pcm) + + +def _count_frames(path: str, sample_rate: int) -> int: + """Return number of audio frames (samples per channel) in the file, or 0 on failure.""" + ext = os.path.splitext(path)[1].lower() + if ext == ".wav": + try: + with wave.open(path, "rb") as w: + return w.getnframes() + except Exception: + pass + if shutil.which("ffprobe"): + try: + out = subprocess.check_output( + ["ffprobe", "-v", "quiet", "-print_format", "json", + "-show_streams", "-select_streams", "a:0", path], + stderr=subprocess.DEVNULL) + s = json.loads(out)["streams"][0] + if s.get("nb_samples") not in (None, "N/A", ""): + return int(s["nb_samples"]) + if s.get("duration"): + # Use the stream's own declared sample_rate for the conversion, not the + # caller-supplied sample_rate, which may have been relabeled by asetrate. + actual_rate = int(s.get("sample_rate") or sample_rate) + return int(float(s["duration"]) * actual_rate) + except Exception: + pass + return 0 + + +def _probe_audio(path: str) -> tuple[int, int]: + ext = os.path.splitext(path)[1].lower() + if ext == ".wav": + try: + with wave.open(path, "rb") as w: + return w.getframerate(), w.getnchannels() + except Exception: + pass + if shutil.which("ffprobe"): + try: + out = subprocess.check_output( + ["ffprobe", "-v", "quiet", "-print_format", "json", + "-show_streams", "-select_streams", "a:0", path], + stderr=subprocess.DEVNULL) + s = json.loads(out)["streams"][0] + return int(s["sample_rate"]), int(s["channels"]) + except Exception: + pass + raise RuntimeError("Cannot detect audio metadata — install ffprobe.") + + +def _resample_audio(audio_path: str, target_rate: int) -> str: + """Relabel audio to target_rate Hz using ffmpeg (speed-change, not pitch-preserving). + + Uses asetrate so the PCM samples are kept as-is but the WAV header reports + target_rate. The engine then reads source samples at (target_rate/32000)×32000 + positions per second, which lowers the pitch by that same ratio — matching the + original N64 instrument tuning convention. + """ + tmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False) + tmp.close() + atexit.register(os.unlink, tmp.name) + subprocess.run( + ["ffmpeg", "-y", "-i", audio_path, + "-af", f"asetrate={target_rate}", tmp.name], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + check=True, + ) + print(f"Relabeled audio to {target_rate} Hz (speed-change) at {tmp.name}") + return tmp.name + + +def _resample_to_32k_mono(audio_path: str) -> bytes: + """Pitch-preserving resample to 32 kHz mono WAV, returned as raw bytes. + + Used for instrument samples in the N64 font pipeline so that + mSample.tuning = 32000*1/32000 = 1.0 — the engine plays back at the + reference pitch with no rate mismatch in loop-end / size calculations. + Requires ffmpeg; raises RuntimeError if unavailable. + """ + if not shutil.which("ffmpeg"): + raise RuntimeError("ffmpeg is required for instrument sample resampling.") + tmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False) + tmp.close() + atexit.register(os.unlink, tmp.name) + subprocess.run( + ["ffmpeg", "-y", "-i", audio_path, + "-af", "aresample=32000", + "-ar", "32000", + "-ac", "1", + tmp.name], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + check=True, + ) + with open(tmp.name, "rb") as f: + return f.read() + + +def _make_xml(audio_arch_path: str, fmt: str, tuning: float, unk: int, + loop: dict | None = None) -> str: + """Build the XML descriptor for a custom-format sample replacement. + + loop — optional dict with keys start, end, count (already scaled to the + new file's sample rate). Omit predictor states: they are ADPCM-only + and ignored by the engine for S16 PCM replacements. + """ + root = ET.Element("Sample") + root.set("Version", "0") + root.set("Codec", "S16") + root.set("Medium", "Ram") + root.set("bit26", str(unk)) + root.set("Tuning", f"{tuning:.6f}") + root.set("Size", "0") + root.set("Relocated", "0") + root.set("Path", audio_arch_path) + root.set("CustomFormat", fmt) + if loop is not None: + lel = ET.SubElement(root, "ADPCMLoop") + lel.set("Start", str(loop["start"])) + lel.set("End", str(loop["end"])) + lel.set("Count", str(loop["count"])) + raw = ET.tostring(root, encoding="unicode") + dom = xml.dom.minidom.parseString(raw) + return dom.toprettyxml(indent=" ").replace('\n', "") + + +def _upsert_mod_o2r(mod_path: str, entries: dict[str, bytes]): + """Write or update a mod .o2r archive, merging new entries over existing ones.""" + existing: dict[str, bytes] = {} + if os.path.isfile(mod_path): + with zipfile.ZipFile(mod_path, "r") as z: + for name in z.namelist(): + existing[name] = z.read(name) + existing.update(entries) + with zipfile.ZipFile(mod_path, "w", compression=zipfile.ZIP_DEFLATED) as z: + for name, data in existing.items(): + z.writestr(name, data) + + +def _build_seq_font_map(archive_path: str) -> dict[int, int]: + """Parse ast_audio/audio_seq_font_table → {seq_index: font_id}. + + Table body (after 64-byte OTR header + 8-byte body header): + u16 BE offsets[numSeqs] — offset[i] points into this same array + font lists — each list: u8 numFonts, u8 fontId[numFonts] + The last fontId in each list is the seqPlayer defaultFont. + numSeqs is inferred from offsets[0] // 2 (offsets[0] = first data byte past table). + """ + result: dict[int, int] = {} + with zipfile.ZipFile(archive_path, "r") as z: + names = z.namelist() + tname = next((n for n in names if "seq_font_table" in n), None) + if tname is None: + return result + raw = z.read(tname) + if len(raw) < BODY_OFFSET + 10: + return result + tbl = raw[BODY_OFFSET + 8:] # skip OTR header + 8-byte body header + if len(tbl) < 2: + return result + first_off = struct.unpack_from(">H", tbl, 0)[0] + num_seqs = first_off // 2 + for i in range(num_seqs): + idx = i * 2 + if idx + 2 > len(tbl): + break + offset = struct.unpack_from(">H", tbl, idx)[0] + if offset >= len(tbl): + continue + num_fonts = tbl[offset] + if num_fonts == 0 or offset + num_fonts >= len(tbl): + continue + result[i] = tbl[offset + num_fonts] # last fontId = defaultFont + return result + + +def _build_font_path_map(archive_path: str) -> dict[int, str]: + """Return {font_id: sfnt_archive_path} by cross-referencing the soundfont ATBL + against SFNT entries in the archive. + + ATBL entry layout (20 bytes each, LE): + u64 romAddr — CRC64 of the SFNT archive path + u32 size + u8 medium, u8 cache, u16 shortData1, u16 shortData2, u16 pad + """ + crc_to_sfnt: dict[int, str] = {} + font_crcs: dict[int, int] = {} # fontId → CRC64 + + with zipfile.ZipFile(archive_path, "r") as z: + names = z.namelist() + + # Map CRC64(path) → path for every SFNT entry + for name in names: + data = z.read(name) + if len(data) < BODY_OFFSET + 4 or data[0:1] == b"<": + continue + if _res_type(data) == FONT_RES_TYPE: + crc_to_sfnt[crc64_hash(name)] = name + + # Find the soundfont ATBL by path name + sfnt_atbl = next((n for n in names if "soundfont_table" in n + or "sound_font_table" in n), None) + if sfnt_atbl is None: + # Fallback: pick ATBL whose name contains "font" + for name in names: + data = z.read(name) + if len(data) < BODY_OFFSET + 10 or data[0:1] == b"<": + continue + if _res_type(data) != ATBL_RES_TYPE: + continue + b = data[BODY_OFFSET:] + tc = struct.unpack_from(" len(b): + break + crc = struct.unpack_from(" dict | None: + """Return loop points scaled from orig_rate to new_rate, or None if not looping.""" + if loop_data is None: + return None + scale = new_rate / orig_rate + return dict( + start=round(loop_data["start"] * scale), + end=round(loop_data["end"] * scale), + count=loop_data["count"], + ) + + +def _snap_loop_to_zero_crossings(wav_bytes: bytes, loop_start: int, loop_end: int, + search_sec: float = 0.005) -> tuple[int, int]: + """Adjust loop_start / loop_end for a click-free loop splice. + + For S16 PCM the engine splices sample[loop_end-1] directly to + sample[loop_start] on every loop iteration. A click-free splice requires: + 1. Value continuity — samples[loop_end-1] ≈ samples[loop_start] + 2. Slope continuity — derivative direction matches at both points + (both rising or both falling) + + Strategy (in order of preference): + A. Zero-crossing pairs with matching slope — both amplitude and slope + are near-optimal; search ±search_sec around each point. + B. Amplitude+slope search — if no zero-crossing pair satisfies both + constraints, scan the full ±search_sec window for the pair with + minimum |samples[end-1] - samples[start]| and matching slope sign. + This catches cases where the best splice point is not near zero. + C. Original positions — returned unchanged if nothing better is found. + + Audio data is never modified. loop_start / loop_end are in + channel-sample units. + """ + import io as _io, wave as _wave, array as _array + + try: + with _wave.open(_io.BytesIO(wav_bytes)) as w: + n = w.getnframes() + ch = w.getnchannels() + sw = w.getsampwidth() + rate = w.getframerate() + raw = w.readframes(n) + except Exception: + return loop_start, loop_end + + if sw != 2: + return loop_start, loop_end + + samples = _array.array('h', raw) + total = len(samples) + + loop_start = max(1, min(loop_start, total - 2)) + loop_end = max(loop_start + 2, min(loop_end, total - 1)) + + window = max(2, round(rate * ch * search_sec)) + + def _find_crossings(center: int, backward: bool) -> list[tuple[int, str]]: + """Return zero-crossing positions near center, sorted by distance.""" + seen: set[int] = set() + results: list[tuple[int, str, int]] = [] + for dist in range(window + 1): + for direction in ((-1 if backward else 1), (1 if backward else -1)): + idx = center + direction * dist + if idx < ch or idx >= total or idx in seen: + continue + seen.add(idx) + prev, cur = samples[idx - ch], samples[idx] + if prev < 0 and cur >= 0: + results.append((idx, 'rising', dist)) + elif prev >= 0 and cur < 0: + results.append((idx, 'falling', dist)) + results.sort(key=lambda x: x[2]) + return [(i, s) for i, s, _ in results] + + # ── Strategy A: zero-crossing pairs with matching slope ────────────────── + # loop_end crossing: samples[loop_end-1] is the last pre-loop sample. + # A zero crossing AT loop_end means samples[loop_end-1] is near zero. + end_crossings = _find_crossings(loop_end, backward=True) + start_crossings = _find_crossings(loop_start, backward=False) + + best_A: tuple[int, int] | None = None + best_score_A = float('inf') + + for end_idx, end_slope in end_crossings: + for start_idx, start_slope in start_crossings: + if end_slope != start_slope or start_idx >= end_idx: + continue + diff = abs(int(samples[end_idx - 1]) - int(samples[start_idx])) + score = diff + abs(end_idx - loop_end) + abs(start_idx - loop_start) + if score < best_score_A: + best_score_A = score + best_A = (start_idx, end_idx) + + if best_A and best_score_A < 200: + # Good zero-crossing pair found — use it directly. + return best_A + + # ── Strategy B: amplitude + slope search over full window ──────────────── + # Scan every position in the search window; score = amplitude jump with a + # heavy penalty for slope direction mismatch. This finds the globally best + # splice even when neither endpoint is near zero. + best_B: tuple[int, int] | None = None + best_score_B = float('inf') + + s_lo = max(ch, loop_start - window) + s_hi = min(total - 2, loop_start + window) + e_lo = max(ch + 1, loop_end - window) + e_hi = min(total - 1, loop_end + window) + + for ps in range(s_lo, s_hi + 1): + slope_s = samples[ps + ch] - samples[ps] + val_s = samples[ps] + for pe in range(max(e_lo, ps + 2), e_hi + 1): + slope_e = samples[pe - 1] - samples[pe - 1 - ch] + amp = abs(int(samples[pe - 1]) - int(val_s)) + penalty = 0 if (slope_s * slope_e > 0) else 4000 + score = amp + penalty + if score < best_score_B: + best_score_B = score + best_B = (ps, pe) + + # Prefer strategy A if it found anything at all; otherwise use B. + if best_A and best_B: + return best_A if best_score_A <= best_score_B else best_B + if best_B: + return best_B + if best_A: + return best_A + + return loop_start, loop_end + + +def _do_replace(archive_path: str, asset_path: str, + audio_path: str, out_dir: str, + loop_override: dict | None = None) -> dict: + sample_rate, channels = _probe_audio(audio_path) + + # Use full scan to get loop data and original sample rate. + info, loop, _book = read_sample_full(archive_path, asset_path) + unk = info["unk"] if info else 0 + orig_rate = _effective_rate(info) if info else MIXER_RATE_HZ + + # Speed-change to orig_rate: relabels the audio so mSample.tuning = orig_rate/32000. + if orig_rate and orig_rate != sample_rate and shutil.which("ffmpeg"): + audio_path = _resample_audio(audio_path, orig_rate) + sample_rate, channels = _probe_audio(audio_path) + + tuning = (sample_rate * channels) / AUDIO_REF_HZ + + orig_frames = info["pcm_samples"] if info else 0 + new_frames = _count_frames(audio_path, sample_rate) + orig_dur = orig_frames / orig_rate if orig_rate and orig_frames else 0.0 + new_dur = new_frames / sample_rate if sample_rate and new_frames else 0.0 + shorter = orig_dur > 0.0 and new_dur > 0.0 and new_dur < orig_dur + + # If the caller has manually edited the loop in the GUI, use that instead. + # The override values are in mono decoded-PCM sample indices (the unit the + # loop editor uses, which matches the original archive loop_data units). + # The engine's samplePosInt advances through *channel-sample* units, so for + # a stereo replacement each mono sample index must be multiplied by channels. + if loop_override is not None: + if channels > 1: + scaled_loop = dict(loop_override, + start=loop_override["start"] * channels, + end=loop_override["end"] * channels) + else: + scaled_loop = dict(loop_override) + else: + # Scale loop points into channel-sample units (the unit samplePosInt uses + # in audio_synthesis.c: bytePos = samplePosInt * 2). + # + # orig_end / orig_frames gives the fractional position in the original mono + # ADPCM stream. The new file has new_frames frames-per-channel, so the + # same fraction maps to new_frames * channels channel samples. + # Multiply effective_rate by channels so _scale_loop's scale factor becomes + # new_frames * channels / orig_frames instead of new_frames / orig_frames. + if loop and orig_frames > 0 and new_frames > 0: + effective_rate = round(new_frames * channels * orig_rate / orig_frames) + scaled_loop = _scale_loop(loop, orig_rate, effective_rate) + elif loop: + # Fallback when frame counts are unavailable: preserve absolute time by + # scaling only by channels (so endPos lands in channel-sample units). + scaled_loop = _scale_loop(loop, orig_rate, sample_rate * channels) + else: + scaled_loop = None + + # Clamp loop end so that endPos * 2 (= bytePos) never exceeds bookSample->size. + # max_end is already in channel-sample units. + if scaled_loop is not None and new_frames > 0: + max_end = new_frames * channels + if scaled_loop["end"] > max_end: + scaled_loop["end"] = max_end + + # CODEC_S16 synthesis always dereferences loopInfo — guard against null. + # If the original had no loop data, emit a non-looping sentinel (count=0) + # so mSample.loop is never nullptr when the engine calls AudioSynth_ProcessNote. + if scaled_loop is None and new_frames > 0: + scaled_loop = dict(start=0, end=new_frames * channels, count=0, + predictor_state=[0] * 16) + + ext = os.path.splitext(audio_path)[1].lower().lstrip(".") + audio_arch = asset_path + "." + ext + + with open(audio_path, "rb") as f: + audio_bytes = f.read() + + # For looping WAV replacements where the user explicitly set loop points via + # the waveform editor (loop_override), snap to zero crossings so the PCM + # splice is waveform-continuous. When loop points were derived automatically + # by proportional scaling from the original ADPCM data, do NOT snap: the + # scaled position is already the best estimate and snapping with even a small + # window can move the point hundreds of samples away. + if ext == "wav" and loop_override is not None and scaled_loop and scaled_loop.get("count", 0) != 0: + snapped_start, snapped_end = _snap_loop_to_zero_crossings( + audio_bytes, scaled_loop["start"], scaled_loop["end"]) + scaled_loop = dict(scaled_loop, start=snapped_start, end=snapped_end) + + xml_content = _make_xml(audio_arch, ext, tuning, unk, loop=scaled_loop) + + mod_name = os.path.splitext(os.path.basename(archive_path))[0] + mod_o2r = os.path.join(out_dir, f"{mod_name}_audio_replacements.o2r") + + _upsert_mod_o2r(mod_o2r, { + asset_path: xml_content.encode(), + audio_arch: audio_bytes, + }) + return dict(sample_rate=sample_rate, channels=channels, + tuning=tuning, mod_o2r=mod_o2r, + loop=scaled_loop, orig_rate=orig_rate, + orig_dur=orig_dur, new_dur=new_dur, shorter=shorter) + + +# ─── project store ──────────────────────────────────────────────────────────── + +BUNDLE_EXT = ".ssproj" + + +def _project_default_path(archive_path: str) -> str: + return os.path.splitext(archive_path)[0] + "_project" + BUNDLE_EXT + + +def load_project(project_path: str) -> dict: + """Load a project file (JSON) or bundle (.ssproj ZIP). + Returns dict: archive, out_dir, replacements, seq_replacements — all absolute paths. + For bundles, audio is extracted to a temp dir that is cleaned up on exit.""" + if zipfile.is_zipfile(project_path): + return _load_bundle(project_path) + + with open(project_path, encoding="utf-8") as f: + data = json.load(f) + base = os.path.dirname(os.path.abspath(project_path)) + + def _abs(p: str) -> str: + return p if os.path.isabs(p) else os.path.normpath(os.path.join(base, p)) + + archive = _abs(data.get("archive", "")) + out_dir = _abs(data.get("out_dir", ".")) + replacements = {a: _abs(p) for a, p in data.get("replacements", {}).items()} + seq_replacements = {a: _abs(p) for a, p in data.get("seq_replacements", {}).items()} + return dict(archive=archive, out_dir=out_dir, + replacements=replacements, seq_replacements=seq_replacements) + + +def _load_bundle(bundle_path: str) -> dict: + """Load a .ssproj bundle ZIP. All files are extracted to a temp directory.""" + with zipfile.ZipFile(bundle_path, "r") as z: + data = json.loads(z.read("project.json").decode("utf-8")) + tmp = tempfile.mkdtemp(prefix="ssproj_") + atexit.register(shutil.rmtree, tmp, ignore_errors=True) + z.extractall(tmp) + + base = os.path.dirname(os.path.abspath(bundle_path)) + + archive_internal = data.get("archive", "") + embedded = os.path.join(tmp, archive_internal) + if os.path.isfile(embedded): + archive = embedded + else: + candidate = os.path.normpath(os.path.join(base, archive_internal)) + archive = candidate if os.path.isfile(candidate) else os.path.abspath(archive_internal) + + out_dir = data.get("out_dir", ".") + if not os.path.isabs(out_dir): + out_dir = os.path.normpath(os.path.join(base, out_dir)) + + replacements = { + asset: os.path.join(tmp, internal) + for asset, internal in data.get("replacements", {}).items() + } + seq_replacements = { + asset: os.path.join(tmp, internal) + for asset, internal in data.get("seq_replacements", {}).items() + } + return dict(archive=archive, out_dir=out_dir, + replacements=replacements, seq_replacements=seq_replacements) + + + +def save_project_bundle(bundle_path: str, archive: str, out_dir: str, + replacements: dict[str, str], + seq_replacements: dict[str, str] | None = None) -> int: + """Save a fully self-contained .ssproj bundle (ZIP). + Embeds the base archive and all replacement audio files. + Returns the total number of audio files embedded.""" + + def _dedup_map(items: dict[str, str], prefix: str, + used: set[str]) -> dict[str, str]: + result: dict[str, str] = {} + for asset, audio_abs in items.items(): + fname = os.path.basename(audio_abs) + stem, ext = os.path.splitext(fname) + candidate = fname + n = 1 + while candidate in used: + candidate = f"{stem}_{n}{ext}" + n += 1 + used.add(candidate) + result[asset] = f"{prefix}/{candidate}" + return result + + used: set[str] = set() + audio_map = _dedup_map(replacements, "audio", used) + seq_map = _dedup_map(seq_replacements or {}, "seq_audio", used) + + archive_internal = os.path.basename(archive) + + metadata = { + "version": 3, + "archive": archive_internal, + "out_dir": out_dir or ".", + "replacements": audio_map, + "seq_replacements": seq_map, + } + + with zipfile.ZipFile(bundle_path, "w", compression=zipfile.ZIP_DEFLATED) as z: + z.writestr("project.json", json.dumps(metadata, indent=2)) + z.write(archive, archive_internal) + for asset, audio_abs in replacements.items(): + z.write(audio_abs, audio_map[asset]) + for asset, audio_abs in (seq_replacements or {}).items(): + z.write(audio_abs, seq_map[asset]) + + return len(replacements) + + +# ─── alias store ────────────────────────────────────────────────────────────── + +def _aliases_path(archive_path: str) -> str: + return os.path.splitext(archive_path)[0] + "_aliases.json" + + +def load_aliases(archive_path: str) -> dict[str, str]: + p = _aliases_path(archive_path) + if os.path.isfile(p): + try: + with open(p, encoding="utf-8") as f: + data = json.load(f) + return data.get("aliases", data) if isinstance(data, dict) else {} + except Exception: + pass + return {} + + +def save_aliases(archive_path: str, aliases: dict[str, str]) -> None: + with open(_aliases_path(archive_path), "w", encoding="utf-8") as f: + json.dump({"version": 1, "aliases": aliases}, f, indent=2) + + +def export_aliases_to(aliases: dict[str, str], out_path: str) -> None: + with open(out_path, "w", encoding="utf-8") as f: + json.dump({"version": 1, "aliases": aliases}, f, indent=2) + + +def _play_pcm_wav(pcm: bytes, sample_rate: int = MIXER_RATE_HZ, + volume: float = 1.0): + """Write PCM to a temp WAV and play (blocking). + + Uses afplay on macOS (volume via -v 0.0-1.0+), falls back to ffplay. + volume — linear gain in [0.0, 1.0]. + """ + with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tf: + tmp = tf.name + try: + _write_wav(pcm, tmp, rate=sample_rate) + vol = max(0.0, float(volume)) + if sys.platform == "darwin" and shutil.which("afplay"): + subprocess.run(["afplay", "-v", f"{vol:.4f}", tmp], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + elif shutil.which("ffplay"): + vol_int = max(0, min(100, int(round(vol * 100)))) + subprocess.run(["ffplay", "-nodisp", "-autoexit", + "-volume", str(vol_int), tmp], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + check=True) + else: + raise RuntimeError("No audio player found — install ffmpeg or ensure afplay is available.") + finally: + try: + os.unlink(tmp) + except OSError: + pass + + +def _play_audio_file(path: str): + """Play an audio file directly (blocking). Uses afplay on macOS, ffplay elsewhere.""" + if sys.platform == "darwin" and shutil.which("afplay"): + subprocess.run(["afplay", path], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + elif shutil.which("ffplay"): + subprocess.run(["ffplay", "-nodisp", "-autoexit", path], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + else: + raise RuntimeError("No audio player found — install ffmpeg or ensure afplay is available.") + + +def _effective_rate(info: dict) -> int: + """Return the best-known playback sample rate for a sample. + + For ADPCM the real recording rate comes from instrument/drum tuning: + sample_rate = round(tuning * 32000) + Falls back to MIXER_RATE_HZ (32000) when tuning is unknown. + """ + sr = info.get("sample_rate") + return sr if sr else MIXER_RATE_HZ + + +def _decode_sample(info: dict, + slot_tuning: float | None = None) -> tuple[bytes, int] | None: + """Return (S16 LE PCM, sample_rate) for a sample, or None if not playable. + + slot_tuning — when provided, overrides the default tuning so the sample plays + back at the pitch for a specific instrument slot (Low/Normal/High/Drum). + """ + codec = info.get("codec") + rate = round(slot_tuning * AUDIO_REF_HZ) if slot_tuning else _effective_rate(info) + if codec == 5: + return info["raw"], rate + if codec == 0: + book = info.get("book_data") + if book is None: + return None + return vadpcm_to_pcm(info["raw"], book), rate + return None + + +# ─── sequence import helpers ───────────────────────────────────────────────── + +# Names for seqId 0-66 (matches BgmSeqIds in include/bgm.h) +_SEQ_ID_NAMES = [ + "SFX", "VOICE", "CORNERIA", "METEO", "TITANIA", "SECTOR X", "ZONESS", + "AREA 6", "VENOM 1", "SECTOR Y", "FORTUNA", "SOLAR", "BOLSE", "KATINA", + "AQUAS", "SECTOR Z", "MACBETH", "ANDROSS", "BOSS CO 1", "BOSS ME", + "BOSS TI", "BOSS SX", "BOSS ZO", "BOSS A6", "BOSS VE", "BOSS SY", + "UNK_26", "BOSS SO", "BOSS BO", "BOSS KA", "BOSS AQ", "BOSS SZ", + "BOSS MA", "BOSS ANDROSS", "TITLE", "OPENING", "MENU", "CO_INTRO", + "GOOD END", "DEATH", "GAME OVER", "UNK_41", "STAFF ROLL", "STAR WOLF", + "INTRO S", "INTRO M", "VERSUS", "VS HURRY", "BOSS CO 2", "BAD END", + "ME_INTRO", "INTRO_51", "UNK_52", "UNK_53", "KATT", "BILL", "VS_MENU", + "UNK_57", "WARP ZONE", "UNK_59", "WORLD MAP", "AND BRAIN", "TO ANDROSS", + "TRAINING", "VE CLEAR", "BOSS RESUME", "VOICE LYLAT", +] + +# Combobox values: "0 — SFX", "1 — VOICE", etc. +_SEQ_ID_COMBO_VALUES = [f"{i} — {n}" for i, n in enumerate(_SEQ_ID_NAMES)] + + +def _seq_disassemble(data: bytes) -> str: + """Delegate to import_sequence.disassemble() loaded at runtime.""" + import importlib.util, pathlib + spec = importlib.util.spec_from_file_location( + "import_sequence", + pathlib.Path(__file__).parent / "import_sequence.py") + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod.disassemble(bytearray(data)) + + +def _seq_make_xml_raw(asset_path_no_ext: str, binary_ext: str, + seq_size: int, seq_index: int, + medium: str, cache_policy: str) -> str: + """Build non-streamed Sequence XML (ResourceFactoryXMLSequenceV0).""" + import xml.etree.ElementTree as _ET, xml.dom.minidom as _dom + binary_path = f"{asset_path_no_ext}.{binary_ext}" + root = _ET.Element("Sequence") + root.set("Version", "0") + root.set("Medium", medium) + root.set("CachePolicy", cache_policy) + root.set("Size", str(seq_size)) + root.set("Index", str(seq_index)) + root.set("Streamed", "false") + root.set("Path", binary_path) + raw = _ET.tostring(root, encoding="unicode") + dom = _dom.parseString(raw) + return dom.toprettyxml(indent=" ", encoding=None).replace('\n', "") + + +def _seq_make_xml_streamed(asset_path_no_ext: str, audio_ext: str, + seq_index: int, medium: str, cache_policy: str, + looped: bool, stereo: bool, length_ms: int, + embed_path: bool = True) -> str: + """Build streamed Sequence XML (ResourceFactoryXMLSequenceV0 Streamed=true).""" + import xml.etree.ElementTree as _ET, xml.dom.minidom as _dom + root = _ET.Element("Sequence") + root.set("Version", "0") + root.set("Medium", medium) + root.set("CachePolicy", cache_policy) + root.set("Index", str(seq_index)) + root.set("Streamed", "true") + root.set("Looped", "true" if looped else "false") + root.set("Stereo", "true" if stereo else "false") + root.set("Length", str(length_ms)) + if embed_path: + root.set("Path", f"{asset_path_no_ext}.{audio_ext}") + raw = _ET.tostring(root, encoding="unicode") + dom = _dom.parseString(raw) + return dom.toprettyxml(indent=" ", encoding=None).replace('\n', "") + + +def _seq_make_sample_xml(audio_arch_path: str, audio_ext: str, + loop: dict | None = None) -> str: + """Build Sample XML for a 32 kHz mono instrument WAV. + + loop — optional dict {start, end, count} in mono frame units. + When present an element is embedded so the N64 synthesis + engine loops the sample (CODEC_S16 always dereferences loopInfo). + When absent the engine will crash, so the caller must always supply + at least a sentinel non-looping loop. + """ + root = ET.Element("Sample") + root.set("Version", "0") + root.set("Codec", "S16") + root.set("Medium", "Ram") + root.set("bit26", "0") + root.set("Size", "0") + root.set("CustomFormat", audio_ext.lower()) + root.set("Path", audio_arch_path) + if loop is not None: + lel = ET.SubElement(root, "ADPCMLoop") + lel.set("Start", str(loop["start"])) + lel.set("End", str(loop["end"])) + lel.set("Count", str(loop["count"])) + raw = ET.tostring(root, encoding="unicode") + dom = xml.dom.minidom.parseString(raw) + return dom.toprettyxml(indent=" ", encoding=None).replace('\n', "") + + +def _seq_make_font_xml(sample_asset_path: str) -> str: + """Build SoundFont XML with one instrument that plays the given sample. + + Data1=65535 → sampleBankId1=0xFF, sampleBankId2=0xFF (SAMPLES_NONE). + Data2=256 → numInstruments=1, numDrums=0. + The instrument covers the full pitch range (0-127) with a basic ADSR. + SampleRef points to the Sample XML archive path so the engine resolves it + through the normal ResourceGetDataByCrc pipeline. + """ + root = ET.Element("SoundFont") + root.set("Version", "0") + root.set("Data1", "65535") + root.set("Data2", "256") + + insts = ET.SubElement(root, "Instruments") + inst = ET.SubElement(insts, "Instrument") + inst.set("IsValid", "1") + inst.set("Loaded", "0") + inst.set("NormalRangeLo", "0") + inst.set("NormalRangeHi", "127") + inst.set("ReleaseRate", "120") + + # Envelope values must be pre-swapped for BSWAP16 (audio_effects.c always + # calls BSWAP16 on the raw s16 stored in EnvelopePointData, because the + # original N64 binary data was big-endian). + # To get engine delay=1 tick : XML Delay="256" (BSWAP16(0x0100)=0x0001=1) + # To get engine arg=32767 : XML Arg="-129" (BSWAP16(0xFF7F)=0x7FFF=32767) + # ADSR_HANG (-1) is symmetric under BSWAP16 (0xFFFF stays 0xFFFF), so + # Delay="-1" works as-is. + envs = ET.SubElement(inst, "Envelopes") + e1 = ET.SubElement(envs, "Envelope") + e1.set("Delay", "256") # engine: 1-tick attack + e1.set("Arg", "-129") # engine: 32767 = full volume → SQ(1.0) = 1.0 + e2 = ET.SubElement(envs, "Envelope") + e2.set("Delay", "-1") # ADSR_HANG: sustain at current level until note-off + e2.set("Arg", "0") + + sound = ET.SubElement(inst, "NormalNotesSound") + sound.set("Tuning", "1.0") + sound.set("SampleRef", sample_asset_path) + + raw = ET.tostring(root, encoding="unicode") + dom = xml.dom.minidom.parseString(raw) + return dom.toprettyxml(indent=" ", encoding=None).replace('\n', "") + + +# ─── CLI subcommands ────────────────────────────────────────────────────────── + +def _loop_str(info: dict) -> str: + ld = info.get("loop_data") + if not info["has_loop"]: + return "none" + if ld is None: + return f"yes (hash 0x{info['loop_hash']:016X}, data unavailable)" + cnt = "∞" if ld["count"] == LOOP_INFINITE else str(ld["count"]) + return f"yes start={ld['start']} end={ld['end']} count={cnt}" + + +def _book_str(info: dict) -> str: + bd = info.get("book_data") + if not info["has_book"]: + return "none" + if bd is None: + return f"yes (hash 0x{info['book_hash']:016X}, data unavailable)" + return f"order={bd['order']} predictors={bd['num_predictors']}" + + +def cmd_list(args): + samples = list_samples(args.archive, + args.filter or "", + args.codec if args.codec is not None else -1) + if not samples: + print("No matching samples found.") + return + aliases = load_aliases(args.archive) + w = max((len(s["path"]) for s in samples), default=12) + aliased = {s["path"]: aliases[s["path"]] for s in samples if s["path"] in aliases} + if aliased: + aw = max((len(v) for v in aliased.values()), default=5) + aw = max(aw, 5) + hdr = (f"{'Asset path':{w}} {'Alias':{aw}} " + f"{'Codec':12} {'Size':>10} {'Duration':>9} Loop Book") + else: + aw = 0 + hdr = f"{'Asset path':{w}} {'Codec':12} {'Size':>10} {'Duration':>9} Loop Book" + print(hdr); print("-" * len(hdr)) + for s in samples: + dur = _fmt_duration(s["pcm_samples"]) if s["pcm_samples"] else "—" + codec = CODEC_NAMES.get(s["codec"], "?") + if aliased: + alias = aliased.get(s["path"], "") + print(f"{s['path']:{w}} {alias:{aw}} {codec:12} " + f"{_fmt_size(s['size']):>10} {dur:>9} " + f"{'yes' if s['has_loop'] else 'no ':4} " + f"{'yes' if s['has_book'] else 'no'}") + else: + print(f"{s['path']:{w}} {codec:12} " + f"{_fmt_size(s['size']):>10} {dur:>9} " + f"{'yes' if s['has_loop'] else 'no ':4} " + f"{'yes' if s['has_book'] else 'no'}") + counts = {} + for s in samples: + k = CODEC_NAMES.get(s["codec"], f"UNK({s['codec']})") + counts[k] = counts.get(k, 0) + 1 + print(f"\nTotal: {len(samples)} ({', '.join(f'{v} {k}' for k,v in sorted(counts.items()))})") + + +def cmd_info(args): + info, loop, book = read_sample_full(args.archive, args.asset) + if info is None: + sys.exit(f"error: sample '{args.asset}' not found.") + + aliases = load_aliases(args.archive) + alias = aliases.get(args.asset, "") + print(f"Path : {args.asset}") + if alias: + print(f"Alias : {alias}") + print(f"Codec : {info['codec']} ({CODEC_NAMES.get(info['codec'], '?')})", end="") + if info["codec"] == 0: + print(" — Nintendo N64 VADPCM 4:1 (9 bytes → 16 S16 samples/frame)") + elif info["codec"] == 5: + print(" — S16 PCM (port custom audio)") + else: + print() + print(f"Medium : {info['medium']} ({MEDIUM_NAMES.get(info['medium'], '?')})") + print(f"Unk bit : {info['unk']}") + print(f"Raw size : {info['size']:,} bytes ({_fmt_size(info['size'])})") + + rate = _effective_rate(info) + if info["tuning"] is not None: + all_t = info.get("all_tunings", [info["tuning"]]) + tuning_str = f"{info['tuning']:.6f}" + if len(all_t) > 1: + tuning_str += " (others: " + ", ".join(f"{t:.4f}" for t in all_t if t != info["tuning"]) + ")" + print(f"Tuning : {tuning_str}") + print(f"Rate : ~{rate} Hz (= tuning × 32000)") + else: + print(f"Tuning : unknown (not referenced by any instrument/drum in this archive)") + print(f"Rate : {MIXER_RATE_HZ} Hz (fallback — may sound pitched up or down)") + + if info["codec"] == 0 and info["adpcm_frames"]: + print(f"Frames : {info['adpcm_frames']:,} ADPCM frames → " + f"{info['pcm_samples']:,} PCM samples " + f"(~{_fmt_duration(info['pcm_samples'], rate)} @ {rate} Hz)") + elif info["pcm_samples"]: + print(f"Samples : {info['pcm_samples']:,} S16 " + f"(~{_fmt_duration(info['pcm_samples'], rate)} @ {rate} Hz)") + + # Loop + print(f"\nLoop : {_loop_str(info)}") + if loop and loop["state"]: + st = " ".join(str(v) for v in loop["state"]) + print(f" Predictor state: [{st}]") + + # Book + print(f"Book : {_book_str(info)}") + if book: + n_coef = book["order"] * book["num_predictors"] * 8 + print(f" {n_coef} total coefficients " + f"(order={book['order']} × predictors={book['num_predictors']} × 8)") + + +def cmd_export(args): + info, _, book = read_sample_full(args.archive, args.asset) + if info is None: + sys.exit(f"error: sample '{args.asset}' not found.") + + base = os.path.basename(args.asset) + decode = getattr(args, "decode", False) + + rate = _effective_rate(info) + if info["codec"] == 5: + out = args.out or (base + ".wav") + _write_wav(info["raw"], out, rate=rate) + print(f"Exported S16 PCM → WAV: {out} ({info['pcm_samples']:,} samples @ {rate} Hz)") + + elif info["codec"] == 0 and (decode or args.out and args.out.endswith(".wav")): + if book is None: + sys.exit("error: no book found — cannot decode ADPCM.") + print("Decoding ADPCM…", end=" ", flush=True) + pcm = vadpcm_to_pcm(info["raw"], book) + out = args.out or (base + ".wav") + _write_wav(pcm, out, rate=rate) + rate_note = f"{rate} Hz" if info["tuning"] else f"{rate} Hz (tuning unknown, may be wrong pitch)" + print(f"done.\nExported decoded WAV: {out} ({info['pcm_samples']:,} samples @ {rate_note})") + + else: + out = args.out or (base + ".bin") + with open(out, "wb") as f: + f.write(info["raw"]) + print(f"Exported raw {CODEC_NAMES.get(info['codec'], '?')}: {out} ({info['size']:,} B)") + + +def cmd_play(args): + if not shutil.which("ffplay"): + sys.exit("error: ffplay not found — install ffmpeg.") + info, _, book = read_sample_full(args.archive, args.asset) + if info is None: + sys.exit(f"error: sample '{args.asset}' not found.") + + rate = _effective_rate(info) + codec = info["codec"] + if codec == 5: + _play_pcm_wav(info["raw"], rate) + elif codec == 0: + if book is None: + sys.exit("error: no book found — cannot decode ADPCM for playback.") + print("Decoding ADPCM…", end=" ", flush=True) + pcm = vadpcm_to_pcm(info["raw"], book) + rate_note = f"{rate} Hz" if info["tuning"] else f"{rate} Hz (tuning unknown)" + print(f"playing at {rate_note}…") + _play_pcm_wav(pcm, rate) + else: + sys.exit(f"Playback not supported for codec {CODEC_NAMES.get(codec, codec)}.") + + +def cmd_replace(args): + if not os.path.isfile(args.input): + sys.exit(f"error: input file not found: {args.input}") + ext = os.path.splitext(args.input)[1].lower().lstrip(".") + if ext not in ("wav", "ogg", "mp3"): + sys.exit(f"error: unsupported format '.{ext}'. Use wav, ogg, or mp3.") + out_dir = os.path.abspath(args.out_dir) if args.out_dir else os.path.dirname(args.archive) + os.makedirs(out_dir, exist_ok=True) + r = _do_replace(args.archive, args.asset, args.input, out_dir) + print(f"Sample rate : {r['sample_rate']} Hz | Channels: {r['channels']} | Tuning: {r['tuning']:.4f}") + if r.get("loop"): + lp = r["loop"] + cnt = "∞" if lp["count"] == LOOP_INFINITE else str(lp["count"]) + print(f"Loop : start={lp['start']} end={lp['end']} count={cnt}" + f" (scaled from {r['orig_rate']} Hz → {r['sample_rate']} Hz)") + else: + print("Loop : none") + if r.get("shorter"): + print(f"WARNING : replacement is shorter than original " + f"({r['new_dur']:.3f}s vs {r['orig_dur']:.3f}s) — " + f"silence will pad the end in-game") + print(f"Mod archive : {r['mod_o2r']}") + print(f"Place {os.path.basename(r['mod_o2r'])} in the mods/ folder to apply.") + + +def cmd_batch_replace(args): + """Replace multiple samples in one pass from a folder or JSON mapping file.""" + if args.dir: + folder = os.path.abspath(args.dir) + audio_map: dict[str, str] = {} + for fname in os.listdir(folder): + ext = os.path.splitext(fname)[1].lower() + if ext in (".wav", ".ogg", ".mp3"): + key = os.path.splitext(fname)[0].lower() + audio_map[key] = os.path.join(folder, fname) + + samples = list_samples(args.archive) + aliases = load_aliases(args.archive) + mapping: dict[str, str] = {} + for s in samples: + p = s["path"] + bname = os.path.basename(p).lower() + alias = aliases.get(p, "") + alias_key = alias.lower().replace(" ", "_") if alias else None + hit = audio_map.get(bname) or (alias_key and audio_map.get(alias_key)) + if hit: + mapping[p] = hit + if not mapping: + sys.exit("No filename matches found in folder.") + elif args.mapping: + with open(args.mapping, encoding="utf-8") as f: + data = json.load(f) + mapping = data.get("mapping", data) if isinstance(data, dict) else data + if not isinstance(mapping, dict): + sys.exit("error: mapping JSON must be an object { asset_path: audio_file, … }") + else: + sys.exit("error: supply --dir or --mapping") + + out_dir = os.path.abspath(args.out_dir) if args.out_dir else os.path.dirname( + os.path.abspath(args.archive)) + os.makedirs(out_dir, exist_ok=True) + + errors: list[str] = [] + warnings: list[str] = [] + n = len(mapping) + for i, (sample_path, audio_path) in enumerate(mapping.items()): + tag = f"[{i + 1}/{n}]" + print(f"{tag} {os.path.basename(sample_path)} ← {os.path.basename(audio_path)}", end=" ") + try: + r = _do_replace(args.archive, sample_path, audio_path, out_dir) + if r.get("shorter"): + print(f"⚠ (shorter: {r['new_dur']:.3f}s vs {r['orig_dur']:.3f}s)") + warnings.append(f"{sample_path}: {r['new_dur']:.3f}s < {r['orig_dur']:.3f}s original") + else: + print("✓") + except Exception as e: + print(f"✗ ({e})") + errors.append(f"{sample_path}: {e}") + + mod_name = os.path.splitext(os.path.basename(args.archive))[0] + mod_o2r = os.path.join(out_dir, f"{mod_name}_audio_replacements.o2r") + print(f"\nMod archive : {mod_o2r}") + print(f"Place it in the mods/ folder to apply.") + if warnings: + print(f"\n{len(warnings)} warning(s) — replacements shorter than originals:") + for w in warnings: + print(f" ⚠ {w}") + if errors: + print(f"\n{len(errors)} error(s):") + for e in errors: + print(f" {e}") + sys.exit(1) + + +def cmd_save_project(args): + """Add or update a replacement entry in a project bundle.""" + proj = args.project or _project_default_path(args.archive) + + # Load existing project state to merge replacements + replacements: dict[str, str] = {} + archive = os.path.abspath(args.archive) + out_dir = args.out_dir or "" + if os.path.isfile(proj): + try: + existing = load_project(proj) + replacements = existing["replacements"] + out_dir = out_dir or existing["out_dir"] or "" + except Exception: + pass + + replacements[args.asset] = os.path.abspath(args.input) + n = save_project_bundle(proj, archive, out_dir, replacements) + print(f"Project : {proj}") + print(f" {args.asset} → {args.input}") + print(f" ({n} audio file(s) + base archive embedded)") + + +def cmd_apply_project(args): + """Re-apply all replacements recorded in a project file.""" + proj = load_project(args.project) + archive = proj["archive"] + out_dir = args.out_dir or proj["out_dir"] or os.path.dirname(os.path.abspath(archive)) + replacements = proj["replacements"] + + if not replacements: + print("No replacements in project.") + return + if not os.path.isfile(archive): + sys.exit(f"error: archive not found: {archive}") + os.makedirs(out_dir, exist_ok=True) + + errors: list[str] = [] + warnings: list[str] = [] + n = len(replacements) + for i, (asset, audio) in enumerate(replacements.items()): + tag = f"[{i + 1}/{n}]" + print(f"{tag} {os.path.basename(asset)} ← {os.path.basename(audio)}", end=" ") + if not os.path.isfile(audio): + msg = f"audio file not found: {audio}" + print(f"✗ ({msg})") + errors.append(f"{asset}: {msg}") + continue + try: + r = _do_replace(archive, asset, audio, out_dir) + if r.get("shorter"): + print(f"⚠ (shorter: {r['new_dur']:.3f}s vs {r['orig_dur']:.3f}s)") + warnings.append(f"{asset}: {r['new_dur']:.3f}s < {r['orig_dur']:.3f}s original") + else: + print("✓") + except Exception as e: + print(f"✗ ({e})") + errors.append(f"{asset}: {e}") + + mod_name = os.path.splitext(os.path.basename(archive))[0] + mod_o2r = os.path.join(out_dir, f"{mod_name}_audio_replacements.o2r") + print(f"\nMod archive : {mod_o2r}") + print(f"Place it in the mods/ folder to apply.") + if warnings: + print(f"\n{len(warnings)} warning(s) — replacements shorter than originals:") + for w in warnings: + print(f" ⚠ {w}") + if errors: + print(f"\n{len(errors)} error(s):") + for e in errors: + print(f" {e}") + sys.exit(1) + + +def cmd_alias(args): + aliases = load_aliases(args.archive) + if args.alias is None: + print(aliases.get(args.asset, "")) + elif args.alias: + aliases[args.asset] = args.alias + save_aliases(args.archive, aliases) + print(f"Alias set: {args.asset!r} → {args.alias!r}") + else: + if args.asset in aliases: + del aliases[args.asset] + save_aliases(args.archive, aliases) + print(f"Alias removed: {args.asset!r}") + else: + print(f"No alias for: {args.asset!r}") + + +def cmd_export_aliases(args): + aliases = load_aliases(args.archive) + base = os.path.splitext(args.archive)[0] + out = args.out or (base + "_aliases_export.json") + export_aliases_to(aliases, out) + print(f"Exported {len(aliases)} alias(es) → {out}") + + +# ─── GUI ───────────────────────────────────────────────────────────────────── + +def cmd_gui(args): + try: + import tkinter as tk + from tkinter import filedialog, messagebox, ttk + except ImportError: + sys.exit("error: tkinter is not available in this Python install.") + + # ── colour palette (Catppuccin Mocha) ───────────────────────────────────── + BG = "#1e1e2e" + BG2 = "#181825" + BG3 = "#313244" + FG = "#cdd6f4" + FG_DIM = "#6c7086" + ACCENT = "#89b4fa" + WARN = "#f38ba8" + SEL_BG = "#45475a" + FONT = ("Helvetica", 11) + FONT_SML = ("Helvetica", 9) + FONT_MON = ("Menlo", 10) if sys.platform == "darwin" else ("Consolas", 10) + + # ── waveform / loop-point editor ────────────────────────────────────────── + class _WaveformEditor(tk.Toplevel): + """Audacity-style waveform view with draggable loop-start / loop-end markers. + + Parameters + ---------- + parent : tk widget + sample : the sample info dict (must have 'raw', 'codec', 'loop_data', + and optionally 'book_data') + pcm : S16 LE mono PCM bytes already decoded by the caller + rate : playback sample rate in Hz + on_save : callable(new_loop_data: dict) called when the user saves + orig_pcm : optional S16 LE mono PCM of the original (vanilla) sample + orig_rate : sample rate of orig_pcm in Hz + orig_loop : optional loop_data dict for the original sample + """ + + _WAVEFORM_H = 200 # canvas height in pixels + _RULER_H = 24 # ruler strip above waveform + _HANDLE_R = 6 # half-width of marker line (used for hit zone) + _HANDLE_W = 14 # grip pill width + _HANDLE_PH = 36 # grip pill height + _MIN_ZOOM = 8 # minimum samples per pixel + _MAX_ZOOM = 0.25 # maximum samples per pixel (= 4 px/sample) + # ── canvas background + _COL_BG = "#0d0d14" + # ── waveforms + _COL_WAVE = "#5b9cf6" # cool blue — replacement + _COL_WAVE_LN = "#89b4fa" # brighter blue outline / center line + _COL_WAVE2 = "#e06c75" # muted red — original (vanilla) + _COL_WAVE2_LN= "#f38ba8" # pink outline + # ── loop region + _COL_LOOP = "#1e2a3a" # dark teal tint + _COL_LOOP_BD = "#2d4a6a" # loop region border + # ── markers + _COL_START = "#98c379" # green — loop-start + _COL_START_DK= "#2d4030" # dark green fill for handle body + _COL_END = "#e5c07b" # amber — loop-end (was red, now distinct from orig) + _COL_END_DK = "#3d3010" # dark amber fill + # ── playback cursor + _COL_CURSOR = "#f8f8f2" # near-white + # ── ruler + _COL_RULER = "#4a4a6a" + _COL_RULER_H = "#a8a8c8" + # ── zero line / grid + _COL_GRID = "#1a1a2e" + _COL_ZERO = "#2a2a3e" # zero-crossing line + + def __init__(self, parent, *, sample: dict, pcm: bytes, rate: int, + on_save, + orig_pcm: bytes | None = None, + orig_rate: int | None = None, + orig_loop: dict | None = None): + super().__init__(parent) + self.title("Loop Editor — " + os.path.basename(sample["path"])) + self.configure(bg=BG) + self.resizable(True, True) + self.minsize(720, 460) + + self._sample = sample + self._rate = rate + self._on_save = on_save + + # PCM as array of signed shorts (mono) — replacement + import array as _array + self._samples = _array.array('h', pcm) + self._n = len(self._samples) + + # Original (vanilla) waveform — may be None if not available + self._orig_samples: _array.array | None = None + self._orig_rate = orig_rate or rate + self._orig_loop = orig_loop # loop_data dict or None + if orig_pcm: + self._orig_samples = _array.array('h', orig_pcm) + + # Loop points (in sample indices, mono channel) + ld = sample.get("loop_data") or {} + self._loop_start = int(ld.get("start", 0)) + self._loop_end = int(ld.get("end", max(0, self._n - 1))) + self._loop_count = ld.get("count", LOOP_INFINITE) + self._loop_state = ld.get("state", [0] * 16) + # Clamp + self._loop_start = max(0, min(self._loop_start, self._n - 1)) + self._loop_end = max(self._loop_start + 1, + min(self._loop_end, self._n)) + + # View state + self._view_start = 0 # first visible sample index + self._spp = max(self.__clamp_spp(self._n / 900), self._MAX_ZOOM) + # samples per pixel — set so full waveform fits in ~900 px initially + + # Overlay toggle — show original waveform on top + self._show_orig = tk.BooleanVar(value=orig_pcm is not None) + + # Drag state + self._drag_target: str | None = None # "start" | "end" | None + self._drag_offset_px = 0 + + # Playback — which source is playing: "loop" or "orig" + self._play_proc: subprocess.Popen | None = None + self._play_thread: threading.Thread | None = None + self._play_which: str = "loop" # "loop" | "orig" + self._play_stop_evt = threading.Event() + self._cursor_pos: int = -1 # sample index, -1 = not playing + self._play_start_time: float = 0.0 + self._play_loop_start: int = 0 + self._play_loop_len: int = 0 + self._play_attack_len: int = 0 # samples in the attack pass (0 = no attack) + self._play_tmp_attack: str | None = None + self._cursor_after_id: str | None = None + + # Interaction state + self._drag_target: str | None = None + self._pan_mode: bool = False + self._shift_mode: bool = False + self._pan_start_x: int = 0 + self._pan_start_view:int = 0 + self._last_dragged: str = "start" # for arrow-key nudge focus + self._shift_at_drag: int = 0 + + # Original waveform shift (in orig-sample units, positive = shift right) + self._orig_shift: int = 0 + + self._build_ui() + self._redraw() + self.protocol("WM_DELETE_WINDOW", self._on_close) + + def _on_close(self): + self._action_stop() + self.destroy() + + # ── helpers ─────────────────────────────────────────────────────────── + + def _clamp_spp(self, spp: float) -> float: + return max(self._MAX_ZOOM, min(float(self._MIN_ZOOM), spp)) + + # alias so inner lambdas can call self._clamp_spp or self.__class__._clamp_spp + _WaveformEditor__clamp_spp = _clamp_spp # will be set correctly as a method + + def _sample_to_x(self, idx: int) -> float: + """Convert a sample index to a canvas x coordinate.""" + return (idx - self._view_start) / self._spp + + def _x_to_sample(self, x: float) -> int: + """Convert a canvas x coordinate to the nearest sample index.""" + return int(round(x * self._spp + self._view_start)) + + def _visible_range(self) -> tuple[int, int]: + w = self._canvas.winfo_width() or 900 + end = int(self._view_start + w * self._spp) + return self._view_start, min(end, self._n) + + # ── UI construction ─────────────────────────────────────────────────── + + def _build_ui(self): + # ── toolbar row 1: playback ─────────────────────────────────────── + tb = ttk.Frame(self, padding=(8, 6, 8, 2)) + tb.pack(fill="x") + + self._btn_play_loop = ttk.Button( + tb, text="▶ Play Loop", + command=lambda: self._action_play("loop")) + self._btn_play_loop.pack(side="left", padx=(0, 4)) + + self._btn_play_orig = ttk.Button( + tb, text="▶ Play Original", + command=lambda: self._action_play("orig"), + state="normal" if self._orig_samples is not None else "disabled") + self._btn_play_orig.pack(side="left", padx=(0, 4)) + + self._btn_stop = ttk.Button(tb, text="■ Stop", + command=self._action_stop, + state="disabled") + self._btn_stop.pack(side="left", padx=(0, 6)) + + # Volume slider — read at play-start; afplay accepts 0.0-1.0+ + ttk.Label(tb, text="Vol:", foreground=FG_DIM, + font=FONT_SML).pack(side="left", padx=(0, 2)) + self._vol_var = tk.DoubleVar(value=1.0) + ttk.Scale(tb, from_=0.0, to=2.0, orient="horizontal", + variable=self._vol_var, length=80).pack(side="left") + + ttk.Separator(tb, orient="vertical").pack(side="left", + fill="y", padx=(6, 8)) + + # Overlay checkbox — only visible when orig waveform is available + if self._orig_samples is not None: + ttk.Checkbutton( + tb, text="Show Original", + variable=self._show_orig, + command=self._redraw).pack(side="left", padx=(0, 8)) + ttk.Separator(tb, orient="vertical").pack( + side="left", fill="y", padx=(0, 8)) + + self._btn_snap = ttk.Button(tb, text="⊞ Snap to Zero", + command=self._action_snap) + self._btn_snap.pack(side="left", padx=(0, 8)) + + # Original shift controls — only shown when orig waveform exists + if self._orig_samples is not None: + ttk.Separator(tb, orient="vertical").pack( + side="left", fill="y", padx=(0, 8)) + ttk.Label(tb, text="Orig shift:", foreground=FG_DIM, + font=FONT_SML).pack(side="left", padx=(0, 2)) + self._shift_var = tk.StringVar(value="0") + self._shift_entry = ttk.Entry(tb, textvariable=self._shift_var, + width=8, font=FONT_MON) + self._shift_entry.pack(side="left", padx=(0, 2)) + self._shift_entry.bind("", lambda *_: self._commit_shift()) + self._shift_entry.bind("", lambda *_: self._commit_shift()) + ttk.Button(tb, text="◀", width=2, + command=lambda: self._nudge_shift(-1)).pack(side="left") + ttk.Button(tb, text="▶", width=2, + command=lambda: self._nudge_shift(1)).pack( + side="left", padx=(1, 4)) + ttk.Button(tb, text="Reset", + command=self._reset_shift).pack(side="left", padx=(0, 8)) + + ttk.Separator(tb, orient="vertical").pack(side="left", + fill="y", padx=(0, 8)) + + # Loop count + ttk.Label(tb, text="Loop:", foreground=FG_DIM, + font=FONT_SML).pack(side="left", padx=(0, 4)) + self._loop_count_var = tk.StringVar( + value="∞" if self._loop_count == LOOP_INFINITE else str(self._loop_count)) + self._loop_count_entry = ttk.Entry(tb, textvariable=self._loop_count_var, + width=6, font=FONT_MON) + self._loop_count_entry.pack(side="left", padx=(0, 12)) + + ttk.Separator(tb, orient="vertical").pack(side="left", + fill="y", padx=(0, 8)) + + # Zoom + ttk.Label(tb, text="Zoom:", foreground=FG_DIM, + font=FONT_SML).pack(side="left", padx=(0, 4)) + ttk.Button(tb, text="−", width=2, + command=lambda: self._zoom_step(2.0)).pack(side="left") + ttk.Button(tb, text="+", width=2, + command=lambda: self._zoom_step(0.5)).pack(side="left", + padx=(2, 12)) + ttk.Button(tb, text="Fit", + command=self._zoom_fit).pack(side="left", padx=(0, 12)) + + # Save / Cancel + ttk.Button(tb, text="✕ Cancel", + command=self.destroy).pack(side="right", padx=(4, 0)) + self._btn_save = ttk.Button(tb, text="✔ Save Loop Points", + style="Accent.TButton", + command=self._action_save) + self._btn_save.pack(side="right", padx=(0, 4)) + + # ── position readout ────────────────────────────────────────────── + info = ttk.Frame(self, padding=(8, 0, 8, 2)) + info.pack(fill="x") + self._info_var = tk.StringVar(value="") + ttk.Label(info, textvariable=self._info_var, + foreground=FG_DIM, font=FONT_SML).pack(side="left") + + # ── canvas ──────────────────────────────────────────────────────── + canvas_frame = ttk.Frame(self, padding=(8, 0, 8, 0)) + canvas_frame.pack(fill="both", expand=True) + canvas_frame.rowconfigure(0, weight=1) + canvas_frame.columnconfigure(0, weight=1) + + total_h = self._RULER_H + self._WAVEFORM_H + self._canvas = tk.Canvas(canvas_frame, bg=self._COL_BG, + height=total_h, highlightthickness=0, + cursor="crosshair") + self._canvas.grid(row=0, column=0, sticky="nsew") + + self._hbar = ttk.Scrollbar(canvas_frame, orient="horizontal", + command=self._on_hscroll) + self._hbar.grid(row=1, column=0, sticky="ew") + + self._canvas.bind("", lambda _e: self._redraw()) + self._canvas.bind("", self._on_press) + self._canvas.bind("", self._on_drag) + self._canvas.bind("", self._on_release) + self._canvas.bind("", self._on_wheel) + self._canvas.bind("", self._on_wheel) + self._canvas.bind("", self._on_wheel) + self._canvas.bind("", self._on_pan_start) + self._canvas.bind("", self._on_pan_drag) + + # Keyboard bindings (focus the canvas so key events reach it) + self._canvas.focus_set() + self._canvas.bind("", self._on_key) + self.bind("", self._on_key) + + # ── legend when both waveforms shown ───────────────────────────── + if self._orig_samples is not None: + leg = ttk.Frame(self, padding=(8, 2, 8, 0)) + leg.pack(fill="x") + tk.Label(leg, text="■", fg=self._COL_WAVE, bg=BG, + font=FONT_SML).pack(side="left") + tk.Label(leg, text="Replacement", fg=FG_DIM, bg=BG, + font=FONT_SML).pack(side="left", padx=(2, 12)) + tk.Label(leg, text="■", fg=self._COL_WAVE2, bg=BG, + font=FONT_SML).pack(side="left") + tk.Label(leg, text="Original (vanilla)", fg=FG_DIM, bg=BG, + font=FONT_SML).pack(side="left", padx=(2, 16)) + tk.Label(leg, + text="Drag=pan • Ctrl+drag=shift original • " + "Ctrl+scroll=zoom • ←/→=nudge marker • " + "Shift+←/→=nudge×10 • Home/End=jump", + fg=FG_DIM, bg=BG, font=FONT_SML).pack(side="left") + + # ── status bar with loop point entries ─────────────────────────── + sb = ttk.Frame(self, padding=(8, 4, 8, 8)) + sb.pack(fill="x") + + ttk.Label(sb, text="Start:", foreground=self._COL_START, + font=FONT_SML).pack(side="left") + self._start_var = tk.StringVar(value=str(self._loop_start)) + self._start_entry = ttk.Entry(sb, textvariable=self._start_var, + width=10, font=FONT_MON) + self._start_entry.pack(side="left", padx=(4, 16)) + self._start_entry.bind("", lambda *_: self._commit_entries()) + self._start_entry.bind("", lambda *_: self._commit_entries()) + + ttk.Label(sb, text="End:", foreground=self._COL_END, + font=FONT_SML).pack(side="left") + self._end_var = tk.StringVar(value=str(self._loop_end)) + self._end_entry = ttk.Entry(sb, textvariable=self._end_var, + width=10, font=FONT_MON) + self._end_entry.pack(side="left", padx=(4, 16)) + self._end_entry.bind("", lambda *_: self._commit_entries()) + self._end_entry.bind("", lambda *_: self._commit_entries()) + + ttk.Label(sb, text="Duration:", + foreground=FG_DIM, font=FONT_SML).pack(side="left") + self._dur_var = tk.StringVar(value="") + ttk.Label(sb, textvariable=self._dur_var, + foreground=FG, font=FONT_MON).pack(side="left", padx=(4, 0)) + + self._update_status() + + + # ── drawing ─────────────────────────────────────────────────────────── + + def _redraw(self): + c = self._canvas + w = c.winfo_width() or 900 + h = c.winfo_height() or (self._RULER_H + self._WAVEFORM_H) + wave_h = h - self._RULER_H + + c.delete("all") + + v0, v1 = self._visible_range() + + # ── loop region highlight ────────────────────────────────────── + lsx = self._sample_to_x(self._loop_start) + lex = self._sample_to_x(self._loop_end) + if lex > lsx: + c.create_rectangle(lsx, self._RULER_H, lex, h, + fill=self._COL_LOOP, + outline=self._COL_LOOP_BD, + width=1, tags="loop_bg") + + # ── helper: draw one waveform envelope ──────────────────────── + def _draw_wave(samps, n_samps, color, tag, + spp_override=None, offset=0): + """Draw filled waveform envelope for samps[]. + + spp_override / offset: allow a different samples-per-pixel and + a sample-index shift so the original waveform can be aligned to + the replacement by matching their loop regions. + """ + spp = spp_override if spp_override is not None else self._spp + # visible range in *this* array's coordinate space + a0 = int(self._view_start * spp / self._spp) + offset + a1 = int(a0 + w * spp) + a0 = max(0, a0); a1 = min(a1, n_samps) + if a1 <= a0: + return + bucket = max(1, int((a1 - a0) / max(1, w))) + mid = self._RULER_H + wave_h / 2 + scale = wave_h / 2 / 32768.0 + pts_hi, pts_lo = [], [] + i = 0 + while True: + s0 = a0 + i * bucket + s1 = min(s0 + bucket, a1) + if s0 >= a1: + break + s0c = max(0, min(s0, n_samps - 1)) + s1c = max(1, min(s1, n_samps)) + chunk = samps[s0c:s1c] + lo = min(chunk) if chunk else 0 + hi = max(chunk) if chunk else 0 + # x in canvas coordinates: map from orig-array index back to + # replacement canvas space + canvas_idx = (s0 - offset) * self._spp / spp + x = (canvas_idx - self._view_start) / self._spp + pts_hi.append((x, mid - hi * scale)) + pts_lo.append((x, mid - lo * scale)) + i += 1 + if len(pts_hi) >= 2: + poly = pts_hi + list(reversed(pts_lo)) + flat = [coord for pt in poly for coord in pt] + c.create_polygon(flat, fill=color, outline="", tags=tag) + + # Draw replacement waveform first (underneath) + _draw_wave(self._samples, self._n, self._COL_WAVE, "wave") + c.create_line(0, self._RULER_H + wave_h / 2, w, + self._RULER_H + wave_h / 2, + fill=self._COL_ZERO, tags="wave_mid") + + if self._orig_samples is not None and self._show_orig.get(): + orig_n = len(self._orig_samples) + orig_off = self._orig_shift # in orig-sample units (same spp as repl) + # Draw at the same spp as replacement so both are time-aligned: + # equal canvas pixels per sample means equal canvas pixels per second + # (both streams share the same sample rate after normalisation). + _draw_wave(self._orig_samples, orig_n, + self._COL_WAVE2, "wave_orig", + spp_override=self._spp, offset=orig_off) + + # Draw orig loop markers at the same spp (no proportional remap) + if self._orig_loop: + ol_s = self._orig_loop.get("start", 0) + ol_e = self._orig_loop.get("end", orig_n) + for ol, lbl in ((ol_s - orig_off, "OS"), + (ol_e - orig_off, "OE")): + ox = self._sample_to_x(ol) + if 0 <= ox <= w: + c.create_line(ox, self._RULER_H, ox, h, + fill=self._COL_WAVE2_LN, width=1, + dash=(3, 5), tags="orig_marker") + c.create_text(ox + 3, self._RULER_H + 14, + text=lbl, anchor="nw", + fill=self._COL_WAVE2_LN, + font=FONT_SML, tags="orig_marker") + + # ── ruler ──────────────────────────────────────────────────── + self._draw_ruler(w) + + # ── loop markers ──────────────────────────────────────────── + self._draw_marker(self._loop_start, self._COL_START, self._COL_START_DK, "S", "start") + self._draw_marker(self._loop_end, self._COL_END, self._COL_END_DK, "E", "end") + + # ── playback cursor ────────────────────────────────────────── + if self._cursor_pos >= 0: + cx = self._sample_to_x(self._cursor_pos) + if 0 <= cx <= w: + r = self._HANDLE_R - 2 + c.create_line(cx, self._RULER_H, cx, h, + fill=self._COL_CURSOR, width=1, + tags="cursor") + c.create_polygon(cx - r, self._RULER_H, + cx + r, self._RULER_H, + cx, self._RULER_H + r * 2, + fill=self._COL_CURSOR, outline="", + tags="cursor") + + # ── scrollbar sync ─────────────────────────────────────────── + frac_lo = self._view_start / max(1, self._n) + frac_hi = min(1.0, (self._view_start + w * self._spp) / max(1, self._n)) + self._hbar.set(frac_lo, frac_hi) + + + def _draw_ruler(self, w: int): + c = self._canvas + # Choose a tick spacing so we get roughly one tick per 80–120 px + # in whole-number sample counts. + samples_visible = w * self._spp + raw_step = samples_visible / max(1, w / 90) + # Round to a nice power-of-two or power-of-ten boundary + import math as _math + exp = _math.floor(_math.log10(max(1, raw_step))) + base = 10 ** exp + for mult in (1, 2, 5, 10): + if base * mult >= raw_step: + tick_step = base * mult + break + else: + tick_step = base * 10 + tick_step = max(1, int(tick_step)) + + c.create_rectangle(0, 0, w, self._RULER_H, + fill=BG2, outline="", tags="ruler") + + first_tick = (self._view_start // tick_step) * tick_step + idx = first_tick + while True: + x = self._sample_to_x(idx) + if x > w: + break + if x >= 0: + c.create_line(x, self._RULER_H - 6, x, self._RULER_H, + fill=self._COL_RULER, tags="ruler") + label = f"{idx:,}" + if self._rate: + secs = idx / self._rate + label += f" {secs:.3f}s" + c.create_text(x + 3, self._RULER_H // 2, + text=label, anchor="w", + fill=self._COL_RULER_H, font=FONT_SML, + tags="ruler") + idx += tick_step + + def _draw_marker(self, sample_idx: int, color: str, color_dk: str, + label: str, tag: str): + """Draw a marker: full-height line + centre grip pill + label. + + The grip pill sits at mid-height so it's easy to grab with the mouse. + color_dk is the darker fill used for the pill body. + """ + c = self._canvas + h = c.winfo_height() or (self._RULER_H + self._WAVEFORM_H) + x = self._sample_to_x(sample_idx) + hw = self._HANDLE_W // 2 # half pill width + ph = self._HANDLE_PH # pill height + mid = self._RULER_H + (h - self._RULER_H) // 2 + + # Full-height vertical line + c.create_line(x, self._RULER_H, x, h, + fill=color, width=2, tags=(tag, "marker")) + + # Grip pill (rounded rectangle approximated with a rectangle + two ovals) + px0, py0 = x - hw, mid - ph // 2 + px1, py1 = x + hw, mid + ph // 2 + r = hw # corner radius = half-width → full semicircles + c.create_rectangle(px0, py0 + r, px1, py1 - r, + fill=color_dk, outline=color, width=1, + tags=(tag, "marker", tag + "_handle")) + c.create_oval(px0, py0, px1, py0 + r * 2, + fill=color_dk, outline=color, width=1, + tags=(tag, "marker", tag + "_handle")) + c.create_oval(px0, py1 - r * 2, px1, py1, + fill=color_dk, outline=color, width=1, + tags=(tag, "marker", tag + "_handle")) + + # Small tick marks inside the pill for grip texture + for dy in (-ph // 6, 0, ph // 6): + c.create_line(x - hw + 3, mid + dy, x + hw - 3, mid + dy, + fill=color, width=1, + tags=(tag, "marker")) + + # Label above the pill + c.create_text(x + hw + 3, mid - ph // 2 - 2, + text=label, anchor="sw", + fill=color, font=FONT_SML, tags=(tag, "marker")) + + # ── interaction ─────────────────────────────────────────────────────── + + def _nearest_marker(self, x: float) -> str | None: + """Return 'start', 'end', or None based on which marker is closer to x.""" + xs = self._sample_to_x(self._loop_start) + xe = self._sample_to_x(self._loop_end) + ds = abs(x - xs) + de = abs(x - xe) + threshold = max(self._HANDLE_W, 14) # match pill half-width + if ds <= threshold or de <= threshold: + return "start" if ds <= de else "end" + return None + + def _on_press(self, event): + ctrl = (event.state & 0x4) != 0 + if ctrl and self._orig_samples is not None: + # Ctrl+drag shifts the original waveform + self._drag_target = None + self._pan_mode = False + self._shift_mode = True + self._pan_start_x = event.x + self._shift_at_drag = self._orig_shift + self._canvas.config(cursor="hand2") + return + self._shift_mode = False + target = self._nearest_marker(event.x) + if target: + self._drag_target = target + self._pan_mode = False + self._canvas.config(cursor="sb_h_double_arrow") + else: + # Left-click on empty canvas = pan + self._drag_target = None + self._pan_mode = True + self._pan_start_x = event.x + self._pan_start_view = self._view_start + self._canvas.config(cursor="fleur") + + def _on_drag(self, event): + if getattr(self, '_shift_mode', False): + dx = event.x - self._pan_start_x + # dx pixels → sample delta (same spp as replacement) + delta = int(-dx * self._spp) + orig_n = len(self._orig_samples) if self._orig_samples else 1 + new_shift = self._shift_at_drag + delta + self._orig_shift = max(-orig_n, min(new_shift, orig_n)) + if hasattr(self, '_shift_var'): + self._shift_var.set(str(self._orig_shift)) + self._redraw() + return + if self._pan_mode: + dx = event.x - self._pan_start_x + vs = max(0, int(self._pan_start_view - dx * self._spp)) + self._view_start = vs + self._redraw() + return + if self._drag_target is None: + return + idx = self._x_to_sample(event.x) + idx = max(0, min(idx, self._n)) + if self._drag_target == "start": + self._loop_start = min(idx, self._loop_end - 1) + self._last_dragged = "start" + else: + self._loop_end = max(idx, self._loop_start + 1) + self._last_dragged = "end" + self._sync_entries() + self._redraw() + self._update_status() + + def _on_release(self, _event): + self._drag_target = None + self._pan_mode = False + self._shift_mode = False + self._canvas.config(cursor="crosshair") + + def _on_wheel(self, event): + # Ctrl + wheel → zoom; plain wheel → pan horizontally + ctrl = (event.state & 0x4) != 0 + if event.num == 4: + delta = 1 + elif event.num == 5: + delta = -1 + else: + delta = event.delta + + if ctrl: + # Zoom around mouse position + idx_center = self._x_to_sample(event.x) + factor = 0.7 if delta > 0 else 1.0 / 0.7 + self._spp = self._clamp_spp(self._spp * factor) + self._view_start = max(0, int(idx_center - event.x * self._spp)) + else: + # Pan horizontally + w = self._canvas.winfo_width() or 900 + step = w * self._spp * 0.15 * (-1 if delta > 0 else 1) + self._view_start = max( + 0, min(int(self._view_start + step), + int(self._n - w * self._spp))) + self._redraw() + + def _on_hscroll(self, *args): + cmd = args[0] + w = self._canvas.winfo_width() or 900 + visible = w * self._spp + if cmd == "moveto": + self._view_start = int(float(args[1]) * self._n) + elif cmd == "scroll": + amount = int(args[1]) + unit = args[2] + step = visible * 0.1 if unit == "units" else visible * 0.9 + self._view_start = int(self._view_start + amount * step) + self._view_start = max(0, min(self._view_start, + int(self._n - visible))) + self._redraw() + + def _on_pan_start(self, event): + """Middle-mouse pan (kept for backward compat).""" + self._pan_start_x = event.x + self._pan_start_view = self._view_start + + def _on_pan_drag(self, event): + dx = event.x - self._pan_start_x + self._view_start = max(0, int(self._pan_start_view - dx * self._spp)) + self._redraw() + + def _on_key(self, event): + """Keyboard navigation. + + Arrow keys (no mod) nudge the focused marker (start if neither + focused → start; end if end-entry focused). + Shift+arrow nudges by 10× the step. + Ctrl+Left/Right pans the view. + Home → jump view to loop start. + End → jump view to loop end. + """ + key = event.keysym + shift = (event.state & 0x1) != 0 + ctrl = (event.state & 0x4) != 0 + step = 10 if shift else 1 + w = self._canvas.winfo_width() or 900 + + if key in ("Left", "Right"): + sign = -1 if key == "Left" else 1 + if ctrl: + # Pan view + self._view_start = max( + 0, min(int(self._view_start + sign * step * self._spp * 20), + int(self._n - w * self._spp))) + self._redraw() + else: + # Nudge whichever marker is "active" (end-entry focused → end) + focused = str(self.focus_get()) + if "end_entry" in focused or self._last_dragged == "end": + self._loop_end = max( + self._loop_start + 1, + min(self._loop_end + sign * step, self._n)) + else: + self._loop_start = max( + 0, min(self._loop_start + sign * step, + self._loop_end - 1)) + self._sync_entries() + self._update_status() + self._redraw() + + elif key == "Home": + # Scroll so loop_start is at 10% from left + self._view_start = max( + 0, int(self._loop_start - w * self._spp * 0.1)) + self._redraw() + elif key == "End": + self._view_start = max( + 0, int(self._loop_end - w * self._spp * 0.9)) + self._redraw() + self._update_status() + + def _on_release(self, _event): + self._drag_target = None + self._canvas.config(cursor="crosshair") + + def _on_wheel(self, event): + # Delta: positive = scroll up = zoom in (macOS/Windows) + if event.num == 4: + delta = 1 + elif event.num == 5: + delta = -1 + else: + delta = event.delta + # Zoom around the mouse position + x_center = event.x + idx_center = self._x_to_sample(x_center) + factor = 0.7 if delta > 0 else 1.0 / 0.7 + self._spp = self._clamp_spp(self._spp * factor) + # Keep idx_center under the mouse + self._view_start = max(0, int(idx_center - x_center * self._spp)) + self._redraw() + + def _on_hscroll(self, *args): + cmd = args[0] + w = self._canvas.winfo_width() or 900 + visible = w * self._spp + if cmd == "moveto": + self._view_start = int(float(args[1]) * self._n) + elif cmd == "scroll": + amount = int(args[1]) + unit = args[2] + step = visible * 0.1 if unit == "units" else visible * 0.9 + self._view_start = int(self._view_start + amount * step) + self._view_start = max(0, min(self._view_start, + int(self._n - visible))) + self._redraw() + + def _on_pan_start(self, event): + self._pan_start_x = event.x + self._pan_start_view = self._view_start + + def _on_pan_drag(self, event): + dx = event.x - self._pan_start_x + self._view_start = max(0, int(self._pan_start_view - dx * self._spp)) + self._redraw() + + def _zoom_step(self, factor: float): + w = self._canvas.winfo_width() or 900 + center = self._view_start + (w * self._spp) / 2 + self._spp = self._clamp_spp(self._spp * factor) + self._view_start = max(0, int(center - (w * self._spp) / 2)) + self._redraw() + + def _zoom_fit(self): + w = self._canvas.winfo_width() or 900 + self._spp = self._clamp_spp(self._n / max(1, w)) + self._view_start = 0 + self._redraw() + + # ── entry sync ──────────────────────────────────────────────────────── + + def _commit_shift(self): + """Apply the shift value typed in the entry box.""" + try: + v = int(self._shift_var.get().strip()) + except (ValueError, AttributeError): + self._shift_var.set(str(self._orig_shift)) + return + if self._orig_samples is not None: + orig_n = len(self._orig_samples) + self._orig_shift = max(-orig_n, min(v, orig_n)) + self._shift_var.set(str(self._orig_shift)) + self._redraw() + + def _nudge_shift(self, delta: int): + """Shift the original waveform by delta samples (same units as replacement).""" + if self._orig_samples is None: + return + # 1 button press moves ~1 screen pixel worth of samples + step = max(1, int(self._spp)) + orig_n = len(self._orig_samples) + self._orig_shift = max(-orig_n, + min(self._orig_shift + delta * step, orig_n)) + self._shift_var.set(str(self._orig_shift)) + self._redraw() + + def _reset_shift(self): + self._orig_shift = 0 + if hasattr(self, '_shift_var'): + self._shift_var.set("0") + self._redraw() + + def _sync_entries(self): + self._start_var.set(str(self._loop_start)) + self._end_var.set(str(self._loop_end)) + + def _commit_entries(self): + try: + s = int(self._start_var.get().strip()) + e = int(self._end_var.get().strip()) + except ValueError: + self._sync_entries() + return + s = max(0, min(s, self._n - 1)) + e = max(s + 1, min(e, self._n)) + self._loop_start = s + self._loop_end = e + self._sync_entries() + self._update_status() + self._redraw() + + def _update_status(self): + loop_len = self._loop_end - self._loop_start + dur_str = _fmt_duration(loop_len, self._rate) if self._rate else f"{loop_len:,} smps" + self._dur_var.set(f"{loop_len:,} samples ({dur_str})") + + # ── actions ─────────────────────────────────────────────────────────── + + def _action_snap(self): + """Snap loop points to nearest zero crossings in the decoded PCM.""" + import io as _io + # Re-wrap PCM as a WAV in memory so _snap_loop_to_zero_crossings can read it + buf = _io.BytesIO() + import wave as _wave + with _wave.open(buf, "wb") as wf: + wf.setnchannels(1) + wf.setsampwidth(2) + wf.setframerate(self._rate) + wf.writeframes(self._samples.tobytes()) + wav_bytes = buf.getvalue() + new_s, new_e = _snap_loop_to_zero_crossings( + wav_bytes, self._loop_start, self._loop_end) + self._loop_start = new_s + self._loop_end = new_e + self._sync_entries() + self._update_status() + self._redraw() + + @staticmethod + def _resample_pcm(pcm: bytes, src_rate: int, dst_rate: int) -> bytes: + """Pitch-preserving resample of mono S16-LE PCM from src_rate to dst_rate. + + Uses ffmpeg (aresample filter) when available, so both replacement and + original waveforms play at the exact same musical pitch regardless of + their raw sample rates. Falls back to a simple linear interpolation + when ffmpeg is not installed. + """ + if src_rate == dst_rate or not pcm: + return pcm + import tempfile as _tmp2, wave as _w2 + # Write raw PCM to a temp WAV at src_rate + tf_in = _tmp2.NamedTemporaryFile(suffix=".wav", delete=False) + tf_out = _tmp2.NamedTemporaryFile(suffix=".wav", delete=False) + tf_in.close(); tf_out.close() + try: + _write_wav(pcm, tf_in.name, rate=src_rate) + if shutil.which("ffmpeg"): + subprocess.run( + ["ffmpeg", "-y", "-i", tf_in.name, + "-af", f"aresample={dst_rate}", + "-ar", str(dst_rate), + tf_out.name], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + check=True) + with _w2.open(tf_out.name, "rb") as wf: + return wf.readframes(wf.getnframes()) + else: + # Python linear interpolation fallback + import array as _ar2 + src = _ar2.array('h', pcm) + ratio = src_rate / dst_rate + n_out = int(len(src) / ratio) + out = _ar2.array('h', [0] * n_out) + for i in range(n_out): + f = i * ratio + lo = int(f); hi = min(lo + 1, len(src) - 1) + t = f - lo + out[i] = int(src[lo] * (1 - t) + src[hi] * t) + return out.tobytes() + finally: + for p in (tf_in.name, tf_out.name): + try: os.unlink(p) + except OSError: pass + + # Target output rate — both replacement and original are normalized here + # before playback so they sound at identical pitch in afplay / ffplay. + _PLAY_OUT_RATE = 44100 + + def _action_play(self, which: str = "loop"): + """Start looped playback of 'loop' (replacement loop region) or 'orig'. + + Both sources are resampled to _PLAY_OUT_RATE (44100 Hz) before playback + so they sound at the same musical pitch regardless of their raw sample + rates. Uses afplay on macOS (supports -v volume float), falls back to + ffplay. Looping is implemented in a watcher thread that restarts the + process until _action_stop() sets _play_stop_evt. + """ + if self._play_proc is not None: + return + + # Determine which PCM and rate to play + if which == "orig": + if self._orig_samples is None: + return + loop_samples = self._orig_samples + rate = self._orig_rate + if self._orig_loop: + ls = max(0, int(self._orig_loop.get("start", 0))) + le = min(len(loop_samples), + int(self._orig_loop.get("end", len(loop_samples)))) + else: + ls, le = 0, len(loop_samples) + # Map orig indices back to replacement canvas indices for cursor + cursor_base = int(ls * self._n / max(1, len(loop_samples))) + cursor_scale = self._n / max(1, len(loop_samples)) + else: + loop_samples = self._samples + rate = self._rate + ls, le = self._loop_start, self._loop_end + cursor_base = ls + cursor_scale = 1.0 + + loop_len = max(1, le - ls) + vol = max(0.0, float(self._vol_var.get())) + + # Normalize to common output rate so both sources play at the same pitch + play_rate = self._PLAY_OUT_RATE + + # Write two temp WAVs mirroring exactly what the engine does: + # attack.wav — full sample 0→le, played ONCE on the first pass + # sustain.wav — loop region ls→le, repeated forever after + # For "orig" playback there is no pre-loop attack, so attack == sustain. + import tempfile as _tmp, time as _time + + has_attack = (which != "orig" and ls > 0) + + if has_attack: + attack_raw = loop_samples[0:le].tobytes() + attack_pcm = self._resample_pcm(attack_raw, rate, play_rate) + tf_a = _tmp.NamedTemporaryFile(suffix=".wav", delete=False) + self._play_tmp_attack = tf_a.name + tf_a.close() + _write_wav(attack_pcm, self._play_tmp_attack, rate=play_rate) + else: + self._play_tmp_attack = None + + sustain_raw = loop_samples[ls:le].tobytes() + sustain_pcm = self._resample_pcm(sustain_raw, rate, play_rate) + tf_s = _tmp.NamedTemporaryFile(suffix=".wav", delete=False) + self._play_tmp = tf_s.name + tf_s.close() + _write_wav(sustain_pcm, self._play_tmp, rate=play_rate) + + # Choose player + use_afplay = sys.platform == "darwin" and shutil.which("afplay") + use_ffplay = not use_afplay and shutil.which("ffplay") + if not use_afplay and not use_ffplay: + messagebox.showwarning( + "No audio player", + "afplay (macOS) or ffplay (ffmpeg) is required for playback.", + parent=self) + try: + os.unlink(self._play_tmp) + except OSError: + pass + return + + self._play_which = which + self._play_stop_evt.clear() + self._play_start_time = _time.monotonic() + self._play_loop_start = cursor_base + self._play_loop_len = int(loop_len * cursor_scale) + self._play_loop_rate = rate + # Attack length in replacement-sample units (0 if no pre-loop region) + self._play_attack_len = int(ls * cursor_scale) if has_attack else 0 + + self._btn_play_loop.state(["disabled"]) + self._btn_play_orig.state(["disabled"]) + self._btn_stop.state(["!disabled"]) + + label = "Original" if which == "orig" else "Loop" + path = self._sample["path"] + self._info_var.set( + f"▶ {label} {os.path.basename(path)}" + f" start={ls:,} end={le:,} vol={vol:.2f}") + self.title(f"▶ {label} {os.path.basename(path)}") + + def _launch(path): + if use_afplay: + return subprocess.Popen( + ["afplay", "-v", f"{vol:.4f}", path], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + else: + vol_int = max(0, min(100, int(round(vol * 100)))) + return subprocess.Popen( + ["ffplay", "-nodisp", "-loop", "1", + "-volume", str(vol_int), path], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + # First pass: play attack (0→le) once if there is a pre-loop region + if self._play_tmp_attack: + self._play_proc = _launch(self._play_tmp_attack) + else: + self._play_proc = _launch(self._play_tmp) + + def _watch(): + """Play attack once then loop sustain until stopped.""" + first = True + while not self._play_stop_evt.is_set(): + self._play_proc.wait() + if self._play_stop_evt.is_set(): + break + if first and self._play_tmp_attack: + # Attack finished — switch cursor to sustain start + self._play_start_time = _time.monotonic() + first = False + # Always loop the sustain WAV from here on + self._play_proc = _launch(self._play_tmp) + for f in [self._play_tmp_attack, self._play_tmp]: + if f: + try: + os.unlink(f) + except OSError: + pass + self._play_tmp_attack = None + self.after(0, self._play_done) + + self._play_thread = threading.Thread(target=_watch, daemon=True) + self._play_thread.start() + self._tick_cursor() + + def _action_stop(self): + self._play_stop_evt.set() + proc = self._play_proc + if proc is not None: + try: + proc.terminate() + except Exception: + pass + + def _tick_cursor(self): + """Advance the playback cursor and schedule the next tick (~60 fps).""" + if self._play_proc is None: + return + import time as _time + elapsed = _time.monotonic() - self._play_start_time + rate = getattr(self, "_play_loop_rate", self._rate) + atk_len = getattr(self, "_play_attack_len", 0) + + if atk_len > 0: + # During attack pass: cursor runs 0 → loop_end (atk_len + loop_len) + atk_samples = int(elapsed * rate) + full_len = atk_len + self._play_loop_len + if atk_samples < full_len: + self._cursor_pos = atk_samples + else: + # Attack done — cursor is now in sustain + sustain_elapsed = elapsed - full_len / rate + pos_in_loop = int(sustain_elapsed * rate) % max(1, self._play_loop_len) + self._cursor_pos = self._play_loop_start + pos_in_loop + else: + pos_in_loop = int(elapsed * rate) % max(1, self._play_loop_len) + self._cursor_pos = self._play_loop_start + pos_in_loop + + self._redraw() + self._cursor_after_id = self.after(16, self._tick_cursor) + + def _play_done(self): + if self._cursor_after_id: + try: + self.after_cancel(self._cursor_after_id) + except Exception: + pass + self._cursor_after_id = None + self._play_proc = None + self._play_thread = None + self._cursor_pos = -1 + self._play_stop_evt.clear() + try: + if not self.winfo_exists(): + return + self._btn_play_loop.state(["!disabled"]) + if self._orig_samples is not None: + self._btn_play_orig.state(["!disabled"]) + self._btn_stop.state(["disabled"]) + self._info_var.set("") + self.title("Loop Editor — " + os.path.basename(self._sample["path"])) + self._redraw() + except Exception: + pass + + + def _action_save(self): + # Parse loop count from entry + raw = self._loop_count_var.get().strip() + if raw in ("∞", "inf", "-1", ""): + count = LOOP_INFINITE + else: + try: + count = max(0, int(raw)) + except ValueError: + count = LOOP_INFINITE + + new_loop = dict( + start=self._loop_start, + end=self._loop_end, + count=count, + state=list(self._loop_state), + ) + self._on_save(new_loop) + self.destroy() + + # ── main window ─────────────────────────────────────────────────────────── + class App(tk.Tk): + def __init__(self): + super().__init__() + self.title("Starship Sample Editor") + self.configure(bg=BG) + self.geometry("1380x780") + self.minsize(960, 560) + + self._samples: list[dict] = [] + self._filtered: list[dict] = [] + self._archive_path: str = "" + self._loading: bool = False + self._aliases: dict[str, str] = {} + self._alias_current_path: str = "" + self._batch_mapping: dict[str, str] = {} + self._node_map: dict[str, dict] = {} # iid → {sample, slot, tuning, leaf} + self._iids_by_path: dict[str, list[str]] = {} # path → [leaf iids] + self._project_path: str = "" + + self._build_styles() + self._build_ui() + + initial = getattr(args, "archive", None) + if initial and os.path.isfile(initial): + self._archive_var.set(initial) + self.after(100, self._load_archive) + + # ── style ───────────────────────────────────────────────────────────── + def _build_styles(self): + s = ttk.Style(self) + s.theme_use("clam") + s.configure(".", + background=BG, foreground=FG, + fieldbackground=BG3, troughcolor=BG2, + selectbackground=SEL_BG, selectforeground=FG, + font=FONT) + s.configure("TFrame", background=BG) + s.configure("TLabel", background=BG, foreground=FG) + s.configure("TButton", background=BG3, foreground=FG, + relief="flat", padding=(8, 4)) + s.map("TButton", + background=[("active", ACCENT), ("pressed", ACCENT)], + foreground=[("active", BG2)]) + s.configure("Accent.TButton", background=ACCENT, foreground=BG2) + s.map("Accent.TButton", + background=[("active", FG), ("pressed", FG)], + foreground=[("active", BG2)]) + s.configure("Warn.TButton", background=WARN, foreground=BG2) + s.configure("TEntry", + fieldbackground=BG3, foreground=FG, insertcolor=FG, relief="flat") + s.configure("TCombobox", + fieldbackground=BG3, foreground=FG, + selectbackground=SEL_BG, relief="flat") + s.map("TCombobox", + fieldbackground=[("readonly", BG3)], + foreground=[("readonly", FG)]) + s.configure("Treeview", + background=BG2, foreground=FG, + fieldbackground=BG2, rowheight=22, + borderwidth=0, relief="flat") + s.configure("Treeview.Heading", + background=BG3, foreground=ACCENT, + relief="flat", font=(*FONT[:1], FONT[1], "bold")) + s.map("Treeview", + background=[("selected", SEL_BG)], + foreground=[("selected", FG)]) + s.configure("Vertical.TScrollbar", + background=BG3, troughcolor=BG2, + arrowcolor=FG_DIM, relief="flat", width=10) + s.configure("TNotebook", + background=BG2, borderwidth=0, tabmargins=0) + s.configure("TNotebook.Tab", + background=BG3, foreground=FG_DIM, + padding=(14, 4), font=FONT, borderwidth=0) + s.map("TNotebook.Tab", + background=[("selected", BG), ("active", SEL_BG)], + foreground=[("selected", FG), ("active", FG)]) + + # ── UI layout ───────────────────────────────────────────────────────── + def _build_ui(self): + # top bar + top = ttk.Frame(self, padding=(10, 8, 10, 6)) + top.pack(fill="x") + ttk.Label(top, text="Archive", foreground=FG_DIM).pack(side="left") + self._archive_var = tk.StringVar() + ttk.Entry(top, textvariable=self._archive_var, + width=44).pack(side="left", padx=(6, 4)) + ttk.Button(top, text="Browse…", + command=self._browse_archive).pack(side="left", padx=(0, 4)) + ttk.Button(top, text="Load", style="Accent.TButton", + command=self._load_archive).pack(side="left", padx=(0, 16)) + ttk.Label(top, text="Output", foreground=FG_DIM).pack(side="left") + self._outdir_var = tk.StringVar() + ttk.Entry(top, textvariable=self._outdir_var, + width=28).pack(side="left", padx=(6, 4)) + ttk.Button(top, text="…", + command=self._pick_outdir).pack(side="left") + ttk.Separator(top, orient="vertical").pack(side="left", fill="y", padx=(10, 8)) + ttk.Button(top, text="Open Project", + command=self._action_open_project).pack(side="left", padx=(0, 4)) + self._btn_save_project_top = ttk.Button(top, text="Save Project", + command=self._action_save_project) + self._btn_save_project_top.pack(side="left", padx=(0, 8)) + self._btn_save_project_top.state(["disabled"]) + ttk.Separator(top, orient="vertical").pack(side="left", fill="y", padx=(0, 8)) + self._btn_write_all = ttk.Button(top, text="Write All (0)", + style="Accent.TButton", + command=self._action_write_all) + self._btn_write_all.pack(side="left", padx=(0, 4)) + self._btn_write_all.state(["disabled"]) + + # filter / action bar + fbar = ttk.Frame(self, padding=(10, 0, 10, 6)) + fbar.pack(fill="x") + ttk.Label(fbar, text="Filter", foreground=FG_DIM).pack(side="left") + self._filter_var = tk.StringVar() + self._filter_var.trace_add("write", self._on_filter_change) + ttk.Entry(fbar, textvariable=self._filter_var, + width=24).pack(side="left", padx=(6, 10)) + ttk.Label(fbar, text="Codec", foreground=FG_DIM).pack(side="left") + self._codec_var = tk.StringVar(value="All") + codec_box = ttk.Combobox( + fbar, textvariable=self._codec_var, width=14, + state="readonly", + values=["All"] + [f"{v} ({k})" for k, v in sorted(CODEC_NAMES.items())]) + codec_box.pack(side="left", padx=(6, 10)) + codec_box.bind("<>", lambda _: self._on_filter_change()) + ttk.Label(fbar, text="Bank", foreground=FG_DIM).pack(side="left") + self._bank_var = tk.StringVar(value="All") + self._bank_box = ttk.Combobox( + fbar, textvariable=self._bank_var, width=14, + state="readonly", values=["All"]) + self._bank_box.pack(side="left", padx=(6, 10)) + self._bank_box.bind("<>", lambda _: self._on_filter_change()) + self._btn_scan = ttk.Button(fbar, text="Scan Folder…", + command=self._action_scan_folder) + self._btn_scan.pack(side="left", padx=(0, 10)) + self._btn_scan.state(["disabled"]) + self._status_var = tk.StringVar(value="Open an archive to begin.") + ttk.Label(fbar, textvariable=self._status_var, + foreground=FG_DIM, font=FONT_SML).pack(side="right") + + # main area — tabbed: Samples | Sequences + nb = ttk.Notebook(self) + nb.pack(fill="both", expand=True, padx=10, pady=(0, 10)) + + pane = ttk.Frame(nb, padding=(0, 4, 0, 0)) + nb.add(pane, text=" Samples ") + pane.columnconfigure(0, weight=3) + pane.columnconfigure(1, weight=1, minsize=330) + pane.rowconfigure(0, weight=1) + + seq_tab = ttk.Frame(nb, padding=(0, 4, 0, 0)) + nb.add(seq_tab, text=" Sequences ") + self._build_seq_tab(seq_tab) + + # sample list + list_frame = ttk.Frame(pane) + list_frame.grid(row=0, column=0, sticky="nsew", padx=(0, 6)) + list_frame.rowconfigure(0, weight=1) + list_frame.columnconfigure(0, weight=1) + + cols = ("alias", "path", "addr", "file", "codec", "size", "dur", "loop", "book", "pitch") + self._tree = ttk.Treeview(list_frame, columns=cols, + show="tree headings", selectmode="browse") + self._tree.heading("alias", text="Alias", + command=lambda: self._sort_by("alias")) + self._tree.heading("path", text="Asset path", + command=lambda: self._sort_by("path")) + self._tree.heading("addr", text="Addr", + command=lambda: self._sort_by("addr")) + self._tree.heading("file", text="Replace With") + self._tree.heading("codec", text="Codec", + command=lambda: self._sort_by("codec")) + self._tree.heading("size", text="Size", + command=lambda: self._sort_by("size")) + self._tree.heading("dur", text="Duration", + command=lambda: self._sort_by("pcm_samples")) + self._tree.heading("loop", text="Loop") + self._tree.heading("book", text="Book") + self._tree.heading("pitch", text="Pitch", + command=lambda: self._sort_by("pitch")) + self._tree.column("#0", width=260, stretch=True) # tree label column + self._tree.column("alias", width=0, stretch=False) # hidden, kept for compat + self._tree.column("path", width=0, stretch=False) # hidden, kept for compat + self._tree.column("addr", width=88, stretch=False, anchor="e") + self._tree.column("file", width=160, stretch=False) + self._tree.column("codec", width=90, stretch=False, anchor="center") + self._tree.column("size", width=80, stretch=False, anchor="e") + self._tree.column("dur", width=76, stretch=False, anchor="e") + self._tree.column("loop", width=46, stretch=False, anchor="center") + self._tree.column("book", width=46, stretch=False, anchor="center") + self._tree.column("pitch", width=56, stretch=False, anchor="center") + + vsb = ttk.Scrollbar(list_frame, orient="vertical", + command=self._tree.yview) + self._tree.configure(yscrollcommand=vsb.set) + self._tree.tag_configure("redirect", foreground=FG_DIM) + self._tree.grid(row=0, column=0, sticky="nsew") + vsb.grid(row=0, column=1, sticky="ns") + + self._tree.bind("<>", self._on_select) + self._tree.bind("", self._on_double_click) + self._tree.bind("", self._on_heading_menu) + self._tree.bind("", self._on_heading_menu) + + # detail panel + detail = ttk.Frame(pane, padding=(10, 0, 0, 0)) + detail.grid(row=0, column=1, sticky="nsew") + detail.columnconfigure(1, weight=1) + + ttk.Label(detail, text="Sample Details", + foreground=ACCENT, + font=(*FONT[:1], FONT[1]+1, "bold")).grid( + row=0, column=0, columnspan=2, sticky="w", pady=(0, 8)) + + self._detail_labels: dict[str, tk.StringVar] = {} + detail_rows = [ + ("Path", "path"), + ("Canonical", "canonical"), + ("Addr", "addr"), + ("Hash", "hash"), + ("Pitch", "pitch"), + ("Banks", "banks"), + ("Used by", "used_by"), + ("Codec", "codec"), + ("Medium", "medium"), + ("Size", "size"), + ("Duration", "duration"), + ("Loop", "loop"), + ("Book", "book"), + ] + for i, (label, key) in enumerate(detail_rows, start=1): + ttk.Label(detail, text=label, foreground=FG_DIM, + font=FONT_SML).grid(row=i, column=0, sticky="nw", + padx=(0, 8), pady=2) + var = tk.StringVar(value="—") + self._detail_labels[key] = var + ttk.Label(detail, textvariable=var, foreground=FG, + font=FONT_MON, wraplength=235, + justify="left").grid(row=i, column=1, sticky="nw", pady=2) + + # Alias — editable entry, auto-saved on Return / focus change + alias_row = len(detail_rows) + 1 + ttk.Label(detail, text="Alias", foreground=FG_DIM, + font=FONT_SML).grid(row=alias_row, column=0, sticky="nw", + padx=(0, 8), pady=(8, 2)) + self._alias_var = tk.StringVar() + self._alias_entry = ttk.Entry(detail, textvariable=self._alias_var, + font=FONT_MON) + self._alias_entry.grid(row=alias_row, column=1, sticky="ew", pady=(8, 2)) + self._alias_entry.bind("", lambda *_: self._save_alias()) + self._alias_entry.bind("", lambda *_: self._save_alias()) + self._alias_entry.state(["disabled"]) + + btn_row = len(detail_rows) + 4 + ttk.Frame(detail, height=1).grid(row=btn_row - 1, column=0, columnspan=2, + sticky="ew", pady=(10, 8)) + + self._btn_play = ttk.Button(detail, text="▶ Play", + command=self._action_play) + self._btn_play.grid(row=btn_row, column=0, columnspan=2, + sticky="ew", pady=2) + + self._btn_loop_editor = ttk.Button(detail, text="◈ Loop Editor…", + command=self._action_loop_editor) + self._btn_loop_editor.grid(row=btn_row+1, column=0, columnspan=2, + sticky="ew", pady=2) + + self._btn_export = ttk.Button(detail, text="↓ Export", + command=self._action_export) + self._btn_export.grid(row=btn_row+2, column=0, columnspan=2, + sticky="ew", pady=2) + + self._btn_assign = ttk.Button(detail, text="↔ Assign Audio…", + command=self._assign_audio) + self._btn_assign.grid(row=btn_row+3, column=0, columnspan=2, + sticky="ew", pady=2) + + self._btn_clear = ttk.Button(detail, text="✕ Clear Assigned Audio", + command=self._clear_audio) + self._btn_clear.grid(row=btn_row+4, column=0, columnspan=2, + sticky="ew", pady=2) + + self._btn_export_aliases = ttk.Button(detail, text="⬆ Export Aliases…", + command=self._action_export_aliases) + self._btn_export_aliases.grid(row=btn_row+5, column=0, columnspan=2, + sticky="ew", pady=(10, 2)) + + for btn in (self._btn_play, self._btn_loop_editor, self._btn_export, + self._btn_assign, self._btn_clear, self._btn_export_aliases): + btn.state(["disabled"]) + + # ── loading ─────────────────────────────────────────────────────────── + def _browse_archive(self): + path = filedialog.askopenfilename( + title="Open o2r archive", + filetypes=[("Starship archive", "*.o2r *.otr"), ("All", "*")]) + if path: + self._archive_var.set(path) + self._load_archive() + + def _load_archive(self): + path = self._archive_var.get().strip() + if not path or not os.path.isfile(path): + self._status_var.set("Archive not found.") + return + if self._loading: + return + self._archive_path = path + self._samples.clear() + self._filtered.clear() + self._aliases = {} + self._alias_current_path = "" + self._batch_mapping = {} + self._seq_mapping = {} + if not self._outdir_var.get(): + self._outdir_var.set(os.path.dirname(os.path.abspath(path))) + self._tree.delete(*self._tree.get_children()) + self._clear_detail() + self._btn_scan.state(["disabled"]) + self._btn_write_all.state(["disabled"]) + self._btn_export_aliases.state(["disabled"]) + self._bank_var.set("All") + self._bank_box.configure(values=["All"]) + self._status_var.set("Loading…") + self._loading = True + threading.Thread(target=self._load_thread, daemon=True).start() + + def _load_thread(self): + try: + samples = list_samples(self._archive_path) + self.after(0, self._load_done, samples, None) + except Exception as e: + self.after(0, self._load_done, [], str(e)) + + def _load_done(self, samples: list[dict], error: str | None): + self._loading = False + if error: + self._status_var.set(f"Error: {error}") + return + self._samples = samples + self._aliases = load_aliases(self._archive_path) + self._btn_scan.state(["!disabled"]) + self._btn_export_aliases.state(["!disabled"]) + self._btn_save_project_top.state(["!disabled"]) + all_banks = sorted({b for s in samples for b in s.get("banks", [])}, + key=lambda p: _font_short(p)) + self._bank_box.configure(values=["All"] + all_banks) + self._bank_var.set("All") + self._apply_filter() + self._refresh_seq_tree() + + # ── filtering ───────────────────────────────────────────────────────── + def _on_filter_change(self, *_): + self._apply_filter() + + def _get_codec_num(self) -> int: + sel = self._codec_var.get() + if sel != "All": + try: + return int(sel.split("(")[1].rstrip(")")) + except Exception: + pass + return -1 + + def _apply_filter(self, *_): + self._refresh_tree() + + def _refresh_tree(self): + self._tree.delete(*self._tree.get_children()) + self._node_map.clear() + self._iids_by_path.clear() + + text = self._filter_var.get().lower() + codec_num = self._get_codec_num() + bank_sel = self._bank_var.get() + + def _matches(s: dict, p: dict | None) -> bool: + """Return True if (sample, provenance_entry) passes all active filters.""" + if codec_num >= 0 and s["codec"] != codec_num: + return False + if not text: + return True + # Build all searchable strings for this leaf + checks = [ + s["path"], + self._aliases.get(s["path"], ""), + CODEC_NAMES.get(s["codec"], ""), + s.get("addr_str", ""), + ] + if p: + checks += [ + p["font"], + _font_short(p["font"]), + p["inst_path"], + _path_tail(p["inst_path"]), + p["slot"], + ] + return any(text in f.lower() for f in checks if f) + + # Build tree: font_path → inst_path → [(sample, slot, tuning)] + font_inst: dict[str, dict[str, list]] = {} + unassigned: list[dict] = [] + + for s in self._samples: + prov = s.get("provenance", []) + if not prov: + # Unassigned — check against sample fields only + if bank_sel == "All" and _matches(s, None): + unassigned.append(s) + continue + for p in prov: + if bank_sel != "All" and p["font"] != bank_sel: + continue + if not _matches(s, p): + continue + f = p["font"] + i = p["inst_path"] + font_inst.setdefault(f, {}).setdefault(i, []).append( + (s, p["slot"], p["tuning"])) + + leaf_counter = [0] + leaf_total = [0] + + def _insert_leaf(parent: str, s: dict, slot: str | None, tuning: float | None): + iid = f"leaf:{leaf_counter[0]}" + leaf_counter[0] += 1 + leaf_total[0] += 1 + alias = self._aliases.get(s["path"], "") + basename = os.path.basename(s["path"]) + label = f"{alias} ({basename})" if alias and alias != basename else basename + slot_tag = f" [{slot[0].upper()}]" if slot else "" + fmap = self._batch_mapping.get(s["path"], "") + dur = _fmt_duration(s["pcm_samples"]) if s["pcm_samples"] else "—" + is_redir = s.get("is_redirect", False) + codec_c = ("→ " if is_redir else "") + CODEC_NAMES.get(s["codec"], f"?({s['codec']})") + eff_rate = round(tuning * AUDIO_REF_HZ) if tuning else _effective_rate(s) + self._tree.insert(parent, "end", iid=iid, + text=label + slot_tag, + tags=("redirect",) if is_redir else (), + values=( + alias, + s["path"], + s.get("addr_str", ""), + os.path.basename(fmap) if fmap else "", + codec_c, + _fmt_size(s["size"]), + dur, + "✓" if s["has_loop"] else "", + "✓" if s["has_book"] else "", + _fmt_pitch_short([slot] if slot else s.get("pitch_roles", [])), + )) + self._node_map[iid] = { + "leaf": True, "sample": s, "slot": slot, "tuning": tuning} + self._iids_by_path.setdefault(s["path"], []).append(iid) + + _SLOT_ORDER = {"low": 0, "normal": 1, "high": 2, "drum": 3} + + for font_path in sorted(font_inst, key=_font_short): + font_iid = f"font:{font_path}" + self._tree.insert("", "end", iid=font_iid, open=True, + text=f"Bank {_font_short(font_path)}") + self._node_map[font_iid] = {"leaf": False} + + for inst_path in sorted(font_inst[font_path]): + inst_iid = f"inst:{font_path}:{inst_path}" + self._tree.insert(font_iid, "end", iid=inst_iid, open=True, + text=_path_tail(inst_path)) + self._node_map[inst_iid] = {"leaf": False} + + entries = font_inst[font_path][inst_path] + entries.sort(key=lambda e: _SLOT_ORDER.get(e[1], 99)) + for s, slot, tuning in entries: + _insert_leaf(inst_iid, s, slot, tuning) + + if unassigned: + u_iid = "__unassigned__" + self._tree.insert("", "end", iid=u_iid, open=not text, + text="Unassigned") + self._node_map[u_iid] = {"leaf": False} + for s in sorted(unassigned, key=lambda x: x["path"]): + _insert_leaf(u_iid, s, None, None) + + # Collect unique samples visible in the tree (for batch scan / replace) + seen: set[str] = set() + self._filtered = [] + for nd in self._node_map.values(): + if nd.get("leaf"): + p = nd["sample"]["path"] + if p not in seen: + seen.add(p) + self._filtered.append(nd["sample"]) + + n = leaf_total[0] + total = len(self._samples) + self._status_var.set( + f"{n} shown / {total} total" if n != total else f"{n} samples") + + # ── sort context menu ───────────────────────────────────────────────── + def _on_heading_menu(self, event): + region = self._tree.identify("region", event.x, event.y) + if region != "heading": + return + menu = tk.Menu(self, tearoff=0) + menu.configure(bg=BG3, fg=FG, activebackground=SEL_BG, + activeforeground=FG, relief="flat") + for label, col in ( + ("Sort by Path (A → Z)", "path"), + ("Sort by Alias (A → Z)", "alias"), + ("Sort by Address (↑)", "addr"), + ("Sort by CRC64 Hash (↑)", "hash"), + ("Sort by Pitch (L → N → H → D)", "pitch"), + ("Sort by Bank", "bank"), + ("Sort by Codec", "codec"), + ("Sort by Size", "size"), + ("Sort by Duration", "pcm_samples"), + ): + menu.add_command(label=label, + command=lambda c=col: self._sort_by(c)) + menu.post(event.x_root, event.y_root) + + # ── sorting ─────────────────────────────────────────────────────────── + _sort_asc = True + _sort_col = "path" + + def _sort_by(self, col: str): + if self._sort_col == col: + self._sort_asc = not self._sort_asc + else: + self._sort_col = col + self._sort_asc = True + if col == "alias": + self._filtered.sort( + key=lambda s: self._aliases.get(s["path"], "").lower(), + reverse=not self._sort_asc) + elif col == "addr": + self._filtered.sort( + key=lambda s: s.get("addr", 0), + reverse=not self._sort_asc) + elif col == "hash": + self._filtered.sort( + key=lambda s: s.get("hash", 0), + reverse=not self._sort_asc) + elif col == "pitch": + self._filtered.sort( + key=lambda s: ( + [_PITCH_ORDER.index(r) if r in _PITCH_ORDER else 99 + for r in s.get("pitch_roles", [])] or [99] + ), + reverse=not self._sort_asc) + elif col == "bank": + self._filtered.sort( + key=lambda s: sorted(_font_short(b) for b in s.get("banks", [])) or [""], + reverse=not self._sort_asc) + else: + key_map = {"path": "path", "codec": "codec", + "size": "size", "pcm_samples": "pcm_samples"} + key = key_map.get(col, "path") + self._filtered.sort(key=lambda s: s[key], reverse=not self._sort_asc) + self._refresh_tree() + + # ── selection ───────────────────────────────────────────────────────── + def _selected_sample(self) -> tuple[dict | None, str | None, float | None]: + """Return (sample, slot, slot_tuning) for the selected leaf, or (None, None, None).""" + sel = self._tree.selection() + if not sel: + return None, None, None + nd = self._node_map.get(sel[0]) + if nd and nd.get("leaf"): + s = nd["sample"] + slot = nd["slot"] + t = nd["tuning"] + if t is None: + t = _effective_rate(s) / AUDIO_REF_HZ if s.get("tuning") else None + return s, slot, t + return None, None, None + + def _on_select(self, _event): + self._commit_alias() + s, slot, slot_tuning = self._selected_sample() + if s is None: + self._clear_detail() + return + + self._alias_current_path = s["path"] + self._alias_var.set(self._aliases.get(s["path"], "")) + self._alias_entry.state(["!disabled"]) + + self._detail_labels["path"].set(s["path"]) + self._detail_labels["canonical"].set( + s.get("canonical_path") or "—") + self._detail_labels["addr"].set(s.get("addr_str") or "—") + self._detail_labels["hash"].set( + f"0x{s['hash']:016X}" if s.get("hash") is not None else "—") + pitch_label = slot.capitalize() if slot else _fmt_pitch_long(s.get("pitch_roles", [])) + self._detail_labels["pitch"].set(pitch_label) + banks = s.get("banks", []) + self._detail_labels["banks"].set( + "\n".join(_font_short(b) for b in banks) if banks else "—") + used_by = s.get("used_by", []) + self._detail_labels["used_by"].set( + "\n".join(used_by[:8]) + ("\n…" if len(used_by) > 8 else "") + if used_by else "—") + codec_str = CODEC_NAMES.get(s["codec"], f"?({s['codec']})") + if s.get("is_redirect"): + codec_str = "→ " + codec_str + self._detail_labels["codec"].set(codec_str) + self._detail_labels["medium"].set( + f"{MEDIUM_NAMES.get(s['medium'], '?')} ({s['medium']})") + self._detail_labels["size"].set(f"{s['size']:,} bytes") + + # Duration + sample rate — use slot-specific tuning when available + rate = round(slot_tuning * AUDIO_REF_HZ) if slot_tuning else _effective_rate(s) + if s["pcm_samples"]: + prefix = f"{s['adpcm_frames']:,} frames × 16 = " if s["adpcm_frames"] else "" + if slot_tuning is not None: + rate_note = f"~{rate} Hz [{slot or 'normal'}]" + elif s.get("tuning") is not None: + rate_note = f"~{rate} Hz" + if len(s.get("all_tunings", [])) > 1: + rate_note += f" ({len(s['all_tunings'])} tunings)" + else: + rate_note = f"{MIXER_RATE_HZ} Hz (unknown)" + self._detail_labels["duration"].set( + f"{prefix}{s['pcm_samples']:,} smps\n" + f"~{_fmt_duration(s['pcm_samples'], rate)} @ {rate_note}") + else: + self._detail_labels["duration"].set("—") + + # Loop + ld = s.get("loop_data") + if not s["has_loop"]: + self._detail_labels["loop"].set("none") + elif ld is None: + self._detail_labels["loop"].set( + f"yes\n(hash 0x{s['loop_hash']:016X}\ndata unavailable)") + else: + cnt = "∞" if ld["count"] == LOOP_INFINITE else str(ld["count"]) + self._detail_labels["loop"].set( + f"start {ld['start']:,}\n" + f"end {ld['end']:,}\n" + f"count {cnt}") + + # Book + bd = s.get("book_data") + if not s["has_book"]: + self._detail_labels["book"].set("none") + elif bd is None: + self._detail_labels["book"].set( + f"yes\n(hash 0x{s['book_hash']:016X}\ndata unavailable)") + else: + n_coef = bd["order"] * bd["num_predictors"] * 8 + self._detail_labels["book"].set( + f"order {bd['order']}\n" + f"predictors {bd['num_predictors']}\n" + f"coefficients {n_coef}") + + # Buttons — play is enabled whenever the codec is decodable; + # missing ffplay is reported on click, not silently here. + can_play = (s["codec"] == 5 or + (s["codec"] == 0 and s.get("book_data") is not None)) + for btn in (self._btn_export, self._btn_assign): + btn.state(["!disabled"]) + if can_play: + self._btn_play.state(["!disabled"]) + else: + self._btn_play.state(["disabled"]) + # Loop editor needs a decodable sample that has loop data + if can_play and s.get("has_loop"): + self._btn_loop_editor.state(["!disabled"]) + else: + self._btn_loop_editor.state(["disabled"]) + if s["path"] in self._batch_mapping: + self._btn_clear.state(["!disabled"]) + else: + self._btn_clear.state(["disabled"]) + + def _on_double_click(self, _event): + s, _slot, _t = self._selected_sample() + if s: + self._assign_audio_to(s) + + def _clear_detail(self): + for var in self._detail_labels.values(): + var.set("—") + self._alias_var.set("") + self._alias_current_path = "" + self._alias_entry.state(["disabled"]) + for btn in (self._btn_play, self._btn_loop_editor, self._btn_export, + self._btn_assign, self._btn_clear): + btn.state(["disabled"]) + + # ── alias helpers ───────────────────────────────────────────────────── + def _commit_alias(self): + path = self._alias_current_path + if not path or not self._archive_path: + return + alias = self._alias_var.get().strip() + current = self._aliases.get(path, "") + if alias == current: + return + if alias: + self._aliases[path] = alias + else: + self._aliases.pop(path, None) + save_aliases(self._archive_path, self._aliases) + # Update tree node text for all leaves of this path + for iid in self._iids_by_path.get(path, []): + try: + nd = self._node_map.get(iid, {}) + slot = nd.get("slot") + basename = os.path.basename(path) + label = f"{alias} ({basename})" if alias and alias != basename else basename + slot_tag = f" [{slot[0].upper()}]" if slot else "" + self._tree.item(iid, text=label + slot_tag) + self._tree.set(iid, "alias", alias) + except Exception: + pass + + def _save_alias(self): + self._commit_alias() + + def _action_export_aliases(self): + if not self._aliases: + messagebox.showinfo("No aliases", + "No aliases defined yet.\n\n" + "Select a sample and type an alias in the Alias field.", + parent=self) + return + default_name = (os.path.splitext(os.path.basename(self._archive_path))[0] + + "_aliases.json") + out = filedialog.asksaveasfilename( + title="Export aliases", + defaultextension=".json", + initialfile=default_name, + filetypes=[("JSON", "*.json"), ("All", "*")]) + if out: + export_aliases_to(self._aliases, out) + messagebox.showinfo( + "Exported", + f"Exported {len(self._aliases)} alias(es) to:\n{out}", + parent=self) + + # ── actions ─────────────────────────────────────────────────────────── + def _action_loop_editor(self): + s, _slot, slot_tuning = self._selected_sample() + if s is None: + return + + asset_path = s.get("path", "") + + # Determine replacement WAV path from batch mapping (may be absent) + repl_wav = self._batch_mapping.get(asset_path) + + # ------------------------------------------------------------------ + # "replacement" pcm — what the user is editing loop points for. + # If a WAV replacement exists, decode that. Otherwise fall back to + # the ADPCM sample from the archive (no comparison mode). + # ------------------------------------------------------------------ + import array as _array, wave as _wave_mod, io as _io_mod + + def _downmix_mono(pcm_bytes, n_pcm_samples): + arr = _array.array('h', pcm_bytes) + if n_pcm_samples and len(arr) > n_pcm_samples: + ch = len(arr) // n_pcm_samples + else: + ch = 1 + if ch == 2: + arr = _array.array('h', ( + (arr[i] + arr[i + 1]) >> 1 + for i in range(0, len(arr) - 1, 2) + )) + return arr.tobytes() + + if repl_wav and os.path.isfile(repl_wav): + # Read replacement WAV directly + try: + with _wave_mod.open(repl_wav, "rb") as wf: + repl_rate = wf.getframerate() + repl_ch = wf.getnchannels() + repl_n = wf.getnframes() + repl_raw = wf.readframes(repl_n) + repl_arr = _array.array('h', repl_raw) + if repl_ch == 2: + repl_arr = _array.array('h', ( + (repl_arr[i] + repl_arr[i + 1]) >> 1 + for i in range(0, len(repl_arr) - 1, 2) + )) + repl_pcm = repl_arr.tobytes() + rate = repl_rate + except Exception as exc: + messagebox.showinfo("Cannot read WAV", + f"Failed to read replacement WAV:\n{exc}", + parent=self) + return + else: + # No replacement — show ADPCM only + result = _decode_sample(s, slot_tuning) + if result is None: + messagebox.showinfo( + "Cannot open Loop Editor", + "The sample codec is not supported for waveform display, " + "or book data is missing.", + parent=self) + return + repl_pcm, rate = result + repl_pcm = _downmix_mono(repl_pcm, s.get("pcm_samples", 0)) + + # ------------------------------------------------------------------ + # "original" pcm — the vanilla ADPCM from the base archive. + # Only shown when a WAV replacement exists (otherwise they would be + # the same sample and comparison is meaningless). + # ------------------------------------------------------------------ + orig_pcm = None + orig_rate = None + orig_loop = None + if repl_wav: + try: + orig_info, orig_loop_data, _ = read_sample_full( + self._archive_path, asset_path) + if orig_info is not None and orig_info.get("codec") in (0, 5): + orig_result = _decode_sample(orig_info, slot_tuning) + if orig_result is not None: + orig_pcm_raw, orig_rate = orig_result + orig_pcm = _downmix_mono(orig_pcm_raw, + orig_info.get("pcm_samples", 0)) + orig_loop = orig_loop_data + except Exception: + pass # silently skip — comparison lane just won't show + + def _on_save(new_loop: dict): + s["loop_data"] = new_loop + cnt = "∞" if new_loop["count"] == LOOP_INFINITE else str(new_loop["count"]) + self._detail_labels["loop"].set( + f"start {new_loop['start']:,}\n" + f"end {new_loop['end']:,}\n" + f"count {cnt}") + self._status_var.set( + "Loop points updated — use Replace / Replace All to write to archive.") + + ed = _WaveformEditor(self, sample=s, pcm=repl_pcm, + # Use orig_rate for the replacement when available: + # the WAV was written with asetrate (header relabeled, + # samples unchanged), so its declared rate is wrong for + # direct playback. Both streams must use the same rate + # so afplay plays them at identical pitch. + rate=orig_rate if orig_rate else rate, + on_save=_on_save, + orig_pcm=orig_pcm, + orig_rate=orig_rate, + orig_loop=orig_loop) + ed.transient(self) + ed.grab_set() + + + + def _action_play(self): + s, _slot, slot_tuning = self._selected_sample() + if s is None: + return + result = _decode_sample(s, slot_tuning) + if result is None: + messagebox.showinfo( + "Cannot play", + f"Codec {CODEC_NAMES.get(s['codec'], s['codec'])} is not " + f"supported for playback, or book data is missing.", + parent=self) + return + pcm, rate = result + + use_afplay = sys.platform == "darwin" and shutil.which("afplay") + use_ffplay = not use_afplay and shutil.which("ffplay") + if not use_afplay and not use_ffplay: + if sys.platform == "darwin": + hint = "afplay is built-in — check your PATH, or install ffmpeg." + elif sys.platform.startswith("win"): + hint = "Install ffmpeg and add it to PATH:\n https://ffmpeg.org/download.html" + else: + hint = "Install ffmpeg (e.g. sudo apt install ffmpeg)" + messagebox.showwarning( + "No audio player", + f"No audio player found.\n\n{hint}", + parent=self) + return + + path = s["path"] + self._status_var.set(f"▶ {path}") + + def _run(): + try: + _play_pcm_wav(pcm, rate) + except Exception: + pass + self.after(0, self._status_var.set, + f"{len(self._filtered)} samples") + + threading.Thread(target=_run, daemon=True).start() + + + def _action_export(self): + s, slot, slot_tuning = self._selected_sample() + if not s: + return + + codec = s["codec"] + + eff_rate = round(slot_tuning * AUDIO_REF_HZ) if slot_tuning else _effective_rate(s) + slot_note = f" [{slot}]" if slot and slot != "normal" else "" + + if codec == 5: + out = filedialog.asksaveasfilename( + title="Export sample", defaultextension=".wav", + initialfile=os.path.basename(s["path"]) + ".wav", + filetypes=[("WAV", "*.wav"), ("All", "*")]) + if out: + _write_wav(s["raw"], out, rate=eff_rate) + messagebox.showinfo("Exported", + f"Saved WAV to:\n{out}\n\nRate: {eff_rate} Hz{slot_note}") + + elif codec == 0: + choice = filedialog.asksaveasfilename( + title="Export ADPCM sample", + initialfile=os.path.basename(s["path"]), + filetypes=[("Decoded WAV", "*.wav"), + ("Raw ADPCM binary", "*.bin"), + ("All", "*")]) + if not choice: + return + if choice.lower().endswith(".wav"): + if s.get("book_data") is None: + messagebox.showerror("Error", + "No book data available — cannot decode ADPCM.") + return + self._status_var.set("Decoding ADPCM…") + self.update_idletasks() + pcm = vadpcm_to_pcm(s["raw"], s["book_data"]) + _write_wav(pcm, choice, rate=eff_rate) + self._status_var.set(f"{len(self._filtered)} samples") + rate_note = f"{eff_rate} Hz{slot_note}" + messagebox.showinfo("Exported", + f"Decoded WAV saved to:\n{choice}\n\nSample rate: {rate_note}") + else: + with open(choice, "wb") as f: + f.write(s["raw"]) + messagebox.showinfo("Exported", + f"Raw ADPCM ({_fmt_size(s['size'])}) saved to:\n{choice}") + + else: + out = filedialog.asksaveasfilename( + title="Export raw sample data", + defaultextension=".bin", + initialfile=os.path.basename(s["path"]) + ".bin", + filetypes=[("Raw binary", "*.bin"), ("All", "*")]) + if out: + with open(out, "wb") as f: + f.write(s["raw"]) + messagebox.showinfo("Exported", + f"Saved {_fmt_size(s['size'])} of raw " + f"{CODEC_NAMES.get(codec, '?')} to:\n{out}") + + # ── batch assign / replace ──────────────────────────────────────────── + def _pick_outdir(self): + d = filedialog.askdirectory(parent=self, + title="Select output directory") + if d: + self._outdir_var.set(d) + + def _assign_audio_to(self, s: dict): + path = s["path"] + audio = filedialog.askopenfilename( + parent=self, + title=f"Assign audio to {os.path.basename(path)}", + filetypes=[("Audio files", "*.wav *.ogg *.mp3"), + ("WAV", "*.wav"), ("OGG", "*.ogg"), + ("MP3", "*.mp3"), ("All", "*")]) + if audio: + self._batch_mapping[path] = audio + for iid in self._iids_by_path.get(path, []): + try: + self._tree.set(iid, "file", os.path.basename(audio)) + except Exception: + pass + self._btn_clear.state(["!disabled"]) + self._update_replace_all_btn() + + def _assign_audio(self): + s, _slot, _t = self._selected_sample() + if s: + self._assign_audio_to(s) + self._btn_clear.state(["!disabled"]) + + def _clear_audio(self): + s, _slot, _t = self._selected_sample() + if s is None: + return + path = s["path"] + self._batch_mapping.pop(path, None) + for iid in self._iids_by_path.get(path, []): + try: + self._tree.set(iid, "file", "") + except Exception: + pass + self._btn_clear.state(["disabled"]) + self._update_replace_all_btn() + + def _update_write_all_btn(self): + n = len(self._batch_mapping) + len(self._seq_mapping) + self._btn_write_all.configure(text=f"Write All ({n})") + self._btn_write_all.state(["!disabled"] if n > 0 else ["disabled"]) + + def _update_replace_all_btn(self): + self._update_write_all_btn() + + def _action_write_all(self): + n_samples = len(self._batch_mapping) + n_seqs = len(self._seq_mapping) + if not n_samples and not n_seqs: + return + self._btn_write_all.state(["disabled"]) + if n_seqs: + self._seq_action_write_o2r() + if n_samples: + self._action_replace_all() + else: + self._update_write_all_btn() + + def _action_scan_folder(self): + if not self._samples: + return + folder = filedialog.askdirectory(parent=self, + title="Folder with audio files") + if not folder: + return + audio_map: dict[str, str] = {} + for fname in os.listdir(folder): + ext = os.path.splitext(fname)[1].lower() + if ext in (".wav", ".ogg", ".mp3"): + key = os.path.splitext(fname)[0].lower() + audio_map[key] = os.path.join(folder, fname) + + matched = 0 + for s in self._samples: + p = s["path"] + bname = os.path.basename(p).lower() + alias = self._aliases.get(p, "") + alias_key = alias.lower().replace(" ", "_") if alias else None + hit = audio_map.get(bname) or ( + alias_key and audio_map.get(alias_key)) + if hit: + self._batch_mapping[p] = hit + for iid in self._iids_by_path.get(p, []): + try: + self._tree.set(iid, "file", os.path.basename(hit)) + except Exception: + pass + matched += 1 + + self._update_replace_all_btn() + self._status_var.set( + f"Matched {matched} / {len(self._samples)} from folder.") + + def _action_replace_all(self): + if not self._batch_mapping: + return + out_dir = self._outdir_var.get().strip() + if not out_dir: + out_dir = os.path.dirname(os.path.abspath(self._archive_path)) + os.makedirs(out_dir, exist_ok=True) + items = list(self._batch_mapping.items()) + # Build path → sample dict for loop_override lookup. + # (Each path may appear in multiple slots; take the first hit.) + sample_by_path: dict[str, dict] = {} + for s in self._samples: + p = s["path"] + if p not in sample_by_path: + sample_by_path[p] = s + self._btn_write_all.state(["disabled"]) + self._btn_scan.state(["disabled"]) + + def worker(): + errors: list[str] = [] + n = len(items) + for i, (sp, ap) in enumerate(items): + self.after(0, self._status_var.set, + f"Replacing {i + 1} / {n}…") + try: + sd = sample_by_path.get(sp) + loop_ov = sd.get("loop_data") if sd else None + _do_replace(self._archive_path, sp, ap, out_dir, + loop_override=loop_ov) + def _mark_ok(p=sp, a=ap): + for iid in self._iids_by_path.get(p, []): + try: self._tree.set(iid, "file", "✓ " + os.path.basename(a)) + except Exception: pass + self.after(0, _mark_ok) + except Exception as e: + errors.append(f"{os.path.basename(sp)}: {e}") + def _mark_err(p=sp): + for iid in self._iids_by_path.get(p, []): + try: self._tree.set(iid, "file", "✗") + except Exception: pass + self.after(0, _mark_err) + self.after(0, self._replace_all_done, + n - len(errors), errors, out_dir) + + threading.Thread(target=worker, daemon=True).start() + + def _replace_all_done(self, done: int, + errors: list[str], out_dir: str): + self._btn_scan.state(["!disabled"]) + self._update_write_all_btn() + mod_name = os.path.splitext(os.path.basename(self._archive_path))[0] + mod_o2r = os.path.join(out_dir, + f"{mod_name}_audio_replacements.o2r") + if errors: + self._status_var.set( + f"Done: {done} replaced, {len(errors)} failed.") + messagebox.showerror( + "Errors", + f"{done} replaced, {len(errors)} failed:\n\n" + + "\n".join(errors[:15]) + + ("\n…" if len(errors) > 15 else ""), + parent=self) + else: + self._status_var.set(f"Replaced {done} sample(s).") + messagebox.showinfo( + "Done", + f"Replaced {done} sample(s).\n\n" + f"Mod archive:\n{mod_o2r}\n\n" + f"Place it in the mods/ folder to apply.", + parent=self) + + def _action_open_project(self): + path = filedialog.askopenfilename( + title="Open Project", + filetypes=[(f"Sample editor project (*{BUNDLE_EXT}, *.json)", + f"*{BUNDLE_EXT} *.json"), ("All files", "*.*")], + parent=self) + if not path: + return + try: + proj = load_project(path) + except Exception as e: + messagebox.showerror("Error", f"Could not load project:\n{e}", parent=self) + return + self._project_path = path + self.title(f"Starship Sample Editor — {os.path.basename(path)}") + # Load archive if it's different from the current one + if proj["archive"] and proj["archive"] != self._archive_path: + self._archive_var.set(proj["archive"]) + self._load_archive() + # Populate output dir + if proj["out_dir"]: + self._outdir_var.set(proj["out_dir"]) + # Populate batch mapping (sample replacements) + valid = {a: p for a, p in proj["replacements"].items() if os.path.isfile(p)} + missing = [a for a in proj["replacements"] if a not in valid] + self._batch_mapping.update(valid) + # Update Samples tree "Replace With" column + for asset, audio in valid.items(): + for iid in self._iids_by_path.get(asset, []): + try: + self._tree.set(iid, "file", os.path.basename(audio)) + except Exception: + pass + + # Populate sequence mapping (sequence replacements) + seq_valid = {a: p for a, p in proj.get("seq_replacements", {}).items() + if os.path.isfile(p)} + seq_missing = [a for a in proj.get("seq_replacements", {}) if a not in seq_valid] + self._seq_mapping.update(seq_valid) + for asset, audio in seq_valid.items(): + for iid in self._seq_iids_by_path.get(asset, []): + try: + self._seq_tree.set(iid, "file", os.path.basename(audio)) + except Exception: + pass + + self._update_write_all_btn() + all_missing = missing + seq_missing + msg = f"Loaded project: {len(valid)} sample(s) + {len(seq_valid)} sequence(s)." + if all_missing: + msg += f"\n\n{len(all_missing)} file(s) not found:\n" + msg += "\n".join(f" {a}" for a in all_missing[:10]) + if len(all_missing) > 10: + msg += "\n …" + messagebox.showwarning("Missing Files", msg, parent=self) + else: + self._status_var.set(msg) + + def _action_save_project(self): + if not self._archive_path: + return + init = self._project_path or _project_default_path(self._archive_path) + path = filedialog.asksaveasfilename( + title="Save Project", + initialfile=os.path.splitext(os.path.basename(init))[0], + initialdir=os.path.dirname(init), + defaultextension=BUNDLE_EXT, + filetypes=[(f"Sample editor project (*{BUNDLE_EXT})", f"*{BUNDLE_EXT}"), + ("All files", "*.*")], + parent=self) + if not path: + return + out_dir = self._outdir_var.get().strip() or os.path.dirname( + os.path.abspath(self._archive_path)) + try: + n = save_project_bundle(path, self._archive_path, out_dir, + self._batch_mapping, self._seq_mapping) + except Exception as e: + messagebox.showerror("Error", f"Could not save project:\n{e}", parent=self) + return + self._project_path = path + self.title(f"Starship Sample Editor — {os.path.basename(path)}") + ns = len(self._seq_mapping) + self._status_var.set( + f"Project saved: {n - ns} sample(s) + {ns} sequence(s) → {os.path.basename(path)}") + + # ── Sequences tab ───────────────────────────────────────────────────── + def _build_seq_tab(self, parent): + parent.columnconfigure(0, weight=2) + parent.columnconfigure(1, weight=1, minsize=320) + parent.rowconfigure(0, weight=1) + + self._seq_entries: list[dict] = [] + self._seq_filtered: list[dict] = [] + self._seq_sort_col = "seq_index" + self._seq_sort_rev = False + self._seq_mapping: dict[str, str] = {} + self._seq_iids_by_path: dict[str, list] = {} + self._seq_loop_overrides: dict[str, dict] = {} # seq_path → loop_data + + # ── left: filter bar + write bar + list ─────────────────────────── + left = ttk.Frame(parent, padding=(4, 0, 4, 4)) + left.grid(row=0, column=0, sticky="nsew") + left.columnconfigure(0, weight=1) + left.rowconfigure(1, weight=1) + + # row 0: filter bar + fbar = ttk.Frame(left) + fbar.grid(row=0, column=0, sticky="ew", pady=(0, 4)) + ttk.Label(fbar, text="Filter", foreground=FG_DIM).pack( + side="left", padx=(0, 4)) + self._seq_filter_var = tk.StringVar() + self._seq_filter_var.trace_add("write", lambda *_: self._seq_apply_filter()) + ttk.Entry(fbar, textvariable=self._seq_filter_var).pack( + side="left", fill="x", expand=True, padx=(0, 6)) + self._seq_count_lbl = ttk.Label(fbar, text="", + foreground=FG_DIM, + font=(*FONT[:1], FONT[1] - 1)) + self._seq_count_lbl.pack(side="left") + + # row 1: treeview + tree_frame = ttk.Frame(left) + tree_frame.grid(row=1, column=0, sticky="nsew") + tree_frame.columnconfigure(0, weight=1) + tree_frame.rowconfigure(0, weight=1) + + cols = ("name", "type", "medium", "cache", "size", "file", "path") + self._seq_tree = ttk.Treeview( + tree_frame, columns=cols, show="headings", selectmode="browse") + for col, lbl, w, anc, stretch in [ + ("name", "Name", 140, "w", False), + ("type", "Type", 70, "center", False), + ("medium", "Medium", 55, "center", False), + ("cache", "Cache", 90, "center", False), + ("size", "Size", 62, "e", False), + ("file", "Replace", 90, "w", False), + ("path", "Path", 0, "w", True), + ]: + self._seq_tree.heading(col, text=lbl, + command=lambda c=col: self._seq_sort(c)) + self._seq_tree.column(col, width=w, anchor=anc, stretch=stretch) + self._seq_tree.tag_configure("streamed", foreground=ACCENT) + self._seq_tree.tag_configure("alias", foreground=FG_DIM) + self._seq_tree.grid(row=0, column=0, sticky="nsew") + _vsb = ttk.Scrollbar(tree_frame, orient="vertical", + command=self._seq_tree.yview) + _vsb.grid(row=0, column=1, sticky="ns") + self._seq_tree.configure(yscrollcommand=_vsb.set) + self._seq_tree.bind("<>", self._seq_on_select) + + # ── right: detail panel ─────────────────────────────────────────── + right = ttk.Frame(parent, padding=(10, 0, 8, 4)) + right.grid(row=0, column=1, sticky="nsew") + right.columnconfigure(1, weight=1) + + ttk.Label(right, text="Sequence Details", + foreground=ACCENT, + font=(*FONT[:1], FONT[1] + 1, "bold")).grid( + row=0, column=0, columnspan=2, sticky="w", pady=(0, 8)) + + self._seq_detail_labels: dict[str, tk.StringVar] = {} + detail_rows = [ + ("Path", "path"), + ("Seq ID", "seq_id"), + ("Format", "format"), + ("Medium", "medium"), + ("Cache", "cache"), + ("Size", "size"), + ] + for i, (label, key) in enumerate(detail_rows, start=1): + ttk.Label(right, text=label, foreground=FG_DIM, + font=FONT_SML).grid(row=i, column=0, sticky="nw", + padx=(0, 8), pady=2) + var = tk.StringVar(value="—") + self._seq_detail_labels[key] = var + ttk.Label(right, textvariable=var, foreground=FG, + font=FONT_MON, wraplength=235, + justify="left").grid(row=i, column=1, sticky="nw", pady=2) + + sep_row = len(detail_rows) + 1 + ttk.Frame(right, height=1).grid( + row=sep_row, column=0, columnspan=2, sticky="ew", pady=(10, 8)) + + btn_row = sep_row + 1 + self._seq_btn_play = ttk.Button(right, text="▶ Play", + command=self._seq_action_play) + self._seq_btn_play.grid(row=btn_row, column=0, columnspan=2, + sticky="ew", pady=2) + + self._seq_btn_export = ttk.Button(right, text="↓ Export .m64", + command=self._seq_action_export) + self._seq_btn_export.grid(row=btn_row + 1, column=0, columnspan=2, + sticky="ew", pady=2) + + self._seq_btn_assign = ttk.Button(right, text="↔ Assign Audio…", + command=self._seq_action_assign) + self._seq_btn_assign.grid(row=btn_row + 2, column=0, columnspan=2, + sticky="ew", pady=2) + + self._seq_btn_loop = ttk.Button( + right, text="〜 Loop Editor…", + command=self._seq_action_loop_editor) + self._seq_btn_loop.grid(row=btn_row + 3, column=0, columnspan=2, + sticky="ew", pady=2) + + self._seq_btn_clear = ttk.Button( + right, text="✕ Clear Assigned Audio", + command=self._seq_action_clear_assign) + self._seq_btn_clear.grid(row=btn_row + 4, column=0, columnspan=2, + sticky="ew", pady=2) + + self._seq_status_var = tk.StringVar(value="") + ttk.Label(right, textvariable=self._seq_status_var, + foreground=FG_DIM, + font=(*FONT[:1], FONT[1] - 1), + wraplength=300).grid( + row=btn_row + 5, column=0, columnspan=2, sticky="w", pady=(8, 0)) + + for btn in (self._seq_btn_play, self._seq_btn_export, + self._seq_btn_assign, self._seq_btn_loop, + self._seq_btn_clear): + btn.state(["disabled"]) + + # ── disassembly section ─────────────────────────────────────────── + dsm_sep = btn_row + 6 + ttk.Frame(right, height=1).grid( + row=dsm_sep, column=0, columnspan=2, sticky="ew", pady=(10, 6)) + + dsm_hdr_row = dsm_sep + 1 + dsm_hdr = ttk.Frame(right) + dsm_hdr.grid(row=dsm_hdr_row, column=0, columnspan=2, + sticky="ew", pady=(0, 4)) + dsm_hdr.columnconfigure(0, weight=1) + ttk.Label(dsm_hdr, text="Disassembly", + foreground=FG_DIM, + font=(*FONT[:1], FONT[1], "bold")).grid( + row=0, column=0, sticky="w") + ttk.Button(dsm_hdr, text="Clear", + command=self._seq_clear_text).grid( + row=0, column=1, sticky="e", padx=(4, 0)) + ttk.Button(dsm_hdr, text="Disassemble", + command=self._seq_action_disassemble).grid( + row=0, column=2, sticky="e", padx=(4, 0)) + + dsm_text_row = dsm_hdr_row + 1 + right.rowconfigure(dsm_text_row, weight=1) + txt_frame = ttk.Frame(right) + txt_frame.grid(row=dsm_text_row, column=0, columnspan=2, + sticky="nsew", pady=(0, 4)) + txt_frame.columnconfigure(0, weight=1) + txt_frame.rowconfigure(0, weight=1) + self._seq_text = tk.Text( + txt_frame, font=FONT_MON, bg=BG2, fg=FG, + insertbackground=FG, relief="flat", + wrap="none", state="disabled") + self._seq_text.grid(row=0, column=0, sticky="nsew") + _tvsb = ttk.Scrollbar(txt_frame, orient="vertical", + command=self._seq_text.yview) + _tvsb.grid(row=0, column=1, sticky="ns") + _thsb = ttk.Scrollbar(txt_frame, orient="horizontal", + command=self._seq_text.xview) + _thsb.grid(row=1, column=0, sticky="ew") + self._seq_text.configure(yscrollcommand=_tvsb.set, + xscrollcommand=_thsb.set) + + # ── sequences list helpers ───────────────────────────────────────────── + def _refresh_seq_tree(self): + if not self._archive_path or not os.path.isfile(self._archive_path): + self._seq_entries = [] + self._seq_apply_filter() + return + try: + self._seq_entries = list_sequences(self._archive_path) + except Exception: + self._seq_entries = [] + self._seq_apply_filter() + + def _seq_apply_filter(self): + text = self._seq_filter_var.get().lower() if hasattr(self, "_seq_filter_var") else "" + if not text: + self._seq_filtered = list(self._seq_entries) + else: + self._seq_filtered = [ + s for s in self._seq_entries + if (text in str(s["seq_index"]) + or text in s["seq_name"].lower() + or text in s["path"].lower() + or text in s["medium"].lower() + or text in s["cache"].lower() + or text in ("streamed" if s["streamed"] else "raw")) + ] + self._seq_populate_tree() + + def _seq_sort(self, col: str): + if self._seq_sort_col == col: + self._seq_sort_rev = not self._seq_sort_rev + else: + self._seq_sort_col = col + self._seq_sort_rev = False + self._seq_populate_tree() + + def _seq_populate_tree(self): + _key = { + "name": lambda s: s["seq_name"].lower(), + "type": lambda s: ("streamed" if s["streamed"] else "raw"), + "medium": lambda s: s["medium"].lower(), + "cache": lambda s: s["cache"].lower(), + "size": lambda s: s["size"], + "file": lambda s: self._seq_mapping.get(s["path"], "").lower(), + "path": lambda s: s["path"].lower(), + } + fn = _key.get(self._seq_sort_col, lambda s: s["seq_index"]) + seqs = sorted(self._seq_filtered, key=fn, reverse=self._seq_sort_rev) + self._seq_tree.delete(*self._seq_tree.get_children()) + self._seq_iids_by_path = {} + for s in seqs: + iid = f"{s['seq_index']}:{s['path']}" + fmt = s["format"] + if fmt == "Streamed": + tag = ("streamed",) + elif fmt == "Alias": + tag = ("alias",) + else: + tag = () + file_val = "" + if s["path"] in self._seq_mapping: + file_val = os.path.basename(self._seq_mapping[s["path"]]) + self._seq_tree.insert( + "", "end", iid=iid, + values=( + f"{s['seq_index']} — {s['seq_name']}", + fmt, + s["medium"], + s["cache"], + _fmt_size(s["size"]) if s["size"] else "—", + file_val, + s["path"], + ), + tags=tag) + self._seq_iids_by_path.setdefault(s["path"], []).append(iid) + n = len(seqs) + self._seq_count_lbl.configure( + text=f"{n} sequence{'s' if n != 1 else ''}") + + def _seq_clear_detail(self): + for var in self._seq_detail_labels.values(): + var.set("—") + for btn in (self._seq_btn_play, self._seq_btn_export, + self._seq_btn_assign, self._seq_btn_loop, + self._seq_btn_clear): + btn.state(["disabled"]) + self._seq_status_var.set("") + + def _seq_on_select(self, _=None): + sel = self._seq_tree.selection() + if not sel: + self._seq_clear_detail() + return + iid = sel[0] + entry = next( + (s for s in self._seq_entries + if f"{s['seq_index']}:{s['path']}" == iid), None) + if entry is None: + self._seq_clear_detail() + return + + is_alias = entry.get("is_alias", False) + path = entry["path"] + idx = entry["seq_index"] + name = entry["seq_name"] + fmt = entry["format"] + + self._seq_detail_labels["path"].set(path) + self._seq_detail_labels["seq_id"].set(f"{idx} — {name}") + self._seq_detail_labels["format"].set(fmt) + self._seq_detail_labels["medium"].set(entry["medium"]) + self._seq_detail_labels["cache"].set(entry["cache"]) + self._seq_detail_labels["size"].set( + f"{entry['size']:,} bytes" if entry["size"] else "—") + + if not is_alias: + self._seq_btn_export.state(["!disabled"]) + self._seq_btn_assign.state(["!disabled"]) + else: + self._seq_btn_export.state(["disabled"]) + self._seq_btn_assign.state(["disabled"]) + + # enable Play for anything that has audio (assigned, embedded, or + # streamed audio_path); keep it enabled for raw blobs too so the + # user gets a clear "no audio" message rather than a greyed button + can_play = not is_alias + self._seq_btn_play.state(["!disabled"] if can_play else ["disabled"]) + + has_audio = path in self._seq_mapping + self._seq_btn_loop.state( + ["!disabled"] if (has_audio and not is_alias) else ["disabled"]) + self._seq_btn_clear.state(["!disabled"] if has_audio else ["disabled"]) + + self._seq_status_var.set("") + + # ── seq detail actions ───────────────────────────────────────────────── + def _seq_get_raw_bytes(self, entry: dict) -> bytes | None: + """Extract raw sequence (or audio) bytes from the archive.""" + path = entry["path"] + archive = self._archive_path + if not archive or not os.path.isfile(archive): + return None + fmt = entry["format"] + try: + with zipfile.ZipFile(archive, "r") as z: + raw = z.read(path) + except Exception: + return None + OTR = 64 + if fmt in ("Blob", "Alias"): + if len(raw) < OTR + 4: + return None + size = struct.unpack_from("I", raw, OTR)[0] + return raw[OTR + 4 : OTR + 4 + size] + elif fmt in ("XML", "Streamed"): + audio_path = entry.get("audio_path") + if not audio_path: + return None + try: + with zipfile.ZipFile(archive, "r") as z: + return z.read(audio_path) + except Exception: + return None + return None + + def _seq_action_export(self): + sel = self._seq_tree.selection() + if not sel: + return + iid = sel[0] + entry = next( + (s for s in self._seq_entries + if f"{s['seq_index']}:{s['path']}" == iid), None) + if entry is None: + return + fmt = entry["format"] + if fmt in ("XML", "Streamed"): + def_ext = "" + ftypes = [("Audio files", "*.wav *.ogg *.mp3"), ("All", "*")] + init = os.path.basename(entry["path"]).replace(".xml", "") + else: + def_ext = ".m64" + ftypes = [("N64 sequence binary", "*.m64"), ("All", "*")] + init = os.path.basename(entry["path"]) + ".m64" + out = filedialog.asksaveasfilename( + title="Export sequence", + defaultextension=def_ext, + initialfile=init, + filetypes=ftypes, + parent=self) + if not out: + return + data = self._seq_get_raw_bytes(entry) + if data is None: + messagebox.showerror("Export failed", + "Could not extract sequence data from archive.", parent=self) + return + with open(out, "wb") as f: + f.write(data) + self._seq_status_var.set(f"Exported: {os.path.basename(out)}") + + def _seq_action_play(self): + sel = self._seq_tree.selection() + if not sel: + return + iid = sel[0] + entry = next( + (s for s in self._seq_entries + if f"{s['seq_index']}:{s['path']}" == iid), None) + if entry is None: + return + path = entry["path"] + fmt = entry["format"] + + # 1. prefer explicitly assigned audio replacement + audio_file = self._seq_mapping.get(path) + if audio_file and os.path.isfile(audio_file): + self._seq_status_var.set(f"▶ {os.path.basename(audio_file)}") + def _run_assigned(f=audio_file): + try: + _play_audio_file(f) + except Exception: + pass + self.after(0, self._seq_status_var.set, "") + threading.Thread(target=_run_assigned, daemon=True).start() + return + + # 2. for streamed / XML entries, play the embedded audio file + if fmt in ("Streamed", "XML"): + audio_path = entry.get("audio_path") + if not audio_path: + self._seq_status_var.set( + "Streamed entry has no embedded audio path.") + return + data = self._seq_get_raw_bytes(entry) + if not data: + self._seq_status_var.set( + "Could not extract audio from archive.") + return + ext = os.path.splitext(audio_path)[1] or ".wav" + with tempfile.NamedTemporaryFile(suffix=ext, delete=False) as tf: + tf.write(data) + tmp_path = tf.name + self._seq_status_var.set(f"▶ {os.path.basename(audio_path)}") + def _run_embedded(p=tmp_path): + try: + _play_audio_file(p) + except Exception: + pass + try: + os.unlink(p) + except OSError: + pass + self.after(0, self._seq_status_var.set, "") + threading.Thread(target=_run_embedded, daemon=True).start() + return + + # 3. raw N64 sequence — needs the game audio engine to render + self._seq_status_var.set( + "Raw N64 sequences need the game engine to play. " + "Assign a replacement audio file, or use AudioDebugWindow " + "in-game to preview.") + + def _seq_action_assign(self): + sel = self._seq_tree.selection() + if not sel: + return + iid = sel[0] + entry = next( + (s for s in self._seq_entries + if f"{s['seq_index']}:{s['path']}" == iid), None) + if entry is None: + return + path = entry["path"] + audio = filedialog.askopenfilename( + parent=self, + title=f"Assign audio to {entry['seq_name']}", + filetypes=[("Audio files", "*.wav *.ogg *.mp3"), + ("WAV", "*.wav"), ("OGG", "*.ogg"), + ("MP3", "*.mp3"), ("All", "*")]) + if not audio: + return + self._seq_mapping[path] = audio + self._seq_loop_overrides.pop(path, None) # reset loop when audio changes + for iid2 in self._seq_iids_by_path.get(path, []): + try: + self._seq_tree.set(iid2, "file", os.path.basename(audio)) + except Exception: + pass + self._seq_btn_loop.state(["!disabled"]) + self._seq_btn_clear.state(["!disabled"]) + self._seq_btn_play.state(["!disabled"]) + self._seq_update_write_btn() + + def _seq_action_clear_assign(self): + sel = self._seq_tree.selection() + if not sel: + return + iid = sel[0] + entry = next( + (s for s in self._seq_entries + if f"{s['seq_index']}:{s['path']}" == iid), None) + if entry is None: + return + path = entry["path"] + self._seq_mapping.pop(path, None) + self._seq_loop_overrides.pop(path, None) + for iid2 in self._seq_iids_by_path.get(path, []): + try: + self._seq_tree.set(iid2, "file", "") + except Exception: + pass + self._seq_btn_loop.state(["disabled"]) + self._seq_btn_clear.state(["disabled"]) + can_play = bool(entry.get("audio_path")) + self._seq_btn_play.state(["!disabled"] if can_play else ["disabled"]) + self._seq_update_write_btn() + + def _seq_action_loop_editor(self): + """Open the waveform/loop editor for the sequence's instrument sample. + + Resamples the assigned audio to 32 kHz mono (matching what the engine + decodes from the WAV), then opens _WaveformEditor so the user can drag + loop start/end markers. The saved loop dict is stored in + _seq_loop_overrides and written into the Sample XML by + _seq_action_write_o2r. + """ + sel = self._seq_tree.selection() + if not sel: + return + iid = sel[0] + entry = next( + (s for s in self._seq_entries + if f"{s['seq_index']}:{s['path']}" == iid), None) + if entry is None: + return + + seq_path = entry["path"] + audio_path = self._seq_mapping.get(seq_path) + if not audio_path or not os.path.isfile(audio_path): + messagebox.showinfo( + "No audio assigned", + "Assign a replacement audio file first.", + parent=self) + return + + self._seq_status_var.set("Resampling to 32 kHz mono…") + self.update_idletasks() + + try: + wav_bytes = _resample_to_32k_mono(audio_path) + except Exception as exc: + self._seq_status_var.set(f"Resample failed: {exc}") + return + + # Decode PCM for the waveform display. + import io as _io + try: + with wave.open(_io.BytesIO(wav_bytes)) as _wv: + n_frames = _wv.getnframes() + rate = _wv.getframerate() + pcm_raw = _wv.readframes(n_frames) + except Exception as exc: + self._seq_status_var.set(f"WAV decode failed: {exc}") + return + + # Use any previously saved loop override, otherwise default to the + # full file with infinite repeat. + existing = self._seq_loop_overrides.get(seq_path) + if existing is None: + existing = {"start": 0, "end": n_frames, "count": LOOP_INFINITE} + + # Build a minimal sample-dict that _WaveformEditor accepts. + fake_sample = { + "path": entry["seq_name"], + "loop_data": existing, + } + + def _on_save(new_loop: dict): + self._seq_loop_overrides[seq_path] = new_loop + cnt = ("∞" if new_loop["count"] == LOOP_INFINITE + else str(new_loop["count"])) + self._seq_status_var.set( + f"Loop saved start={new_loop['start']:,} " + f"end={new_loop['end']:,} count={cnt} — " + "click Write .o2r to apply.") + + self._seq_status_var.set("") + ed = _WaveformEditor( + self, + sample=fake_sample, + pcm=pcm_raw, + rate=rate, + on_save=_on_save) + ed.transient(self) + ed.grab_set() + + def _seq_action_disassemble(self): + sel = self._seq_tree.selection() + if not sel: + self._seq_status_var.set("Select a sequence first.") + return + iid = sel[0] + entry = next( + (s for s in self._seq_entries + if f"{s['seq_index']}:{s['path']}" == iid), None) + if entry is None: + return + fmt = entry["format"] + if fmt in ("XML", "Streamed"): + self._seq_status_var.set( + "Streamed sequences have no N64 bytecode to disassemble.") + return + data = self._seq_get_raw_bytes(entry) + if not data: + self._seq_status_var.set("Could not extract sequence data.") + return + try: + text = _seq_disassemble(data) + except Exception as e: + text = f"Disassembly failed:\n{e}" + self._seq_text.configure(state="normal") + self._seq_text.delete("1.0", "end") + self._seq_text.insert("1.0", text) + self._seq_text.configure(state="disabled") + self._seq_status_var.set( + f"Disassembled {_fmt_size(len(data))}") + + def _seq_clear_text(self): + self._seq_text.configure(state="normal") + self._seq_text.delete("1.0", "end") + self._seq_text.configure(state="disabled") + + def _seq_update_write_btn(self): + self._update_write_all_btn() + + def _seq_action_write_o2r(self): + if not self._seq_mapping: + return + out_dir = self._outdir_var.get().strip() + if not out_dir: + out_dir = os.path.dirname(os.path.abspath(self._archive_path)) + os.makedirs(out_dir, exist_ok=True) + + entry_by_path: dict[str, dict] = {s["path"]: s for s in self._seq_entries} + errors: list[str] = [] + written = 0 + + # Build font lookup tables once for the whole export pass. + seq_font_map = _build_seq_font_map(self._archive_path) # seq_idx → font_id + font_path_map = _build_font_path_map(self._archive_path) # font_id → sfnt_arch_path + + for seq_path, audio_path in list(self._seq_mapping.items()): + entry = entry_by_path.get(seq_path) + if entry is None: + errors.append(f"Unknown entry: {seq_path}") + continue + if not os.path.isfile(audio_path): + errors.append(f"Audio file not found: {audio_path}") + continue + try: + with open(audio_path, "rb") as f: + audio_bytes = f.read() + rate, channels = _probe_audio(audio_path) + frames = _count_frames(audio_path, rate) + length_ms = int(frames * 1000 / rate) if rate and frames else 0 + stereo = channels >= 2 + idx = entry["seq_index"] + medium = entry["medium"] + cache = entry["cache"] + ext = os.path.splitext(audio_path)[1].lstrip(".") or "wav" + slug = entry["seq_name"].lower().replace(" ", "_") + audio_asset = f"ast_audio/seq_{idx:02d}_{slug}" + sample_asset = f"{audio_asset}_sample" + + # Sequence XML stored at the original archive path so the + # resource manager's CRC64 lookup matches the base entry. + # embed_path=False: do NOT embed the audio path in the XML. + # When Streamed=true and Path is absent, SequenceFactory generates + # synthetic N64 bytecode (WriteMonoSingleSeq) that plays note 39 + # through instrument 0 of the sequence's default font. That is the + # path that actually reaches the N64 MIDI engine — embedding the real + # audio bytes would make AudioLoad_SyncLoadSeq return raw OGG/WAV/MP3 + # data as the seqData pointer, which the sequencer interprets as + # invalid opcodes and produces silence. + # stereo=False: we export exactly one instrument (index 0); the stereo + # generator uses instruments 0 and 1, which would cause a null-deref + # when instrument 1 is looked up in our single-instrument font. + seq_xml = _seq_make_xml_streamed( + audio_asset, ext, idx, medium, cache, + looped=True, stereo=False, length_ms=length_ms, + embed_path=False) + + # Resample to 32 kHz mono for the instrument sample so + # tuning = 1.0 and the engine's size/loop calculations are exact. + sample_wav_arch = f"{sample_asset}.wav" + sample_wav_bytes = _resample_to_32k_mono(audio_path) + + # Determine loop points for the instrument sample. + # CODEC_S16 synthesis always dereferences loopInfo, so we must + # always emit an element. Default: loop the entire + # file infinitely. A user-edited override is stored in + # self._seq_loop_overrides and snapped to zero crossings. + import io as _io + with wave.open(_io.BytesIO(sample_wav_bytes)) as _wv: + _n_frames = _wv.getnframes() + + loop_override = getattr(self, "_seq_loop_overrides", {}).get(seq_path) + if loop_override is not None: + sample_loop = dict(loop_override) + if sample_loop.get("count", 0) != 0: + _ls, _le = _snap_loop_to_zero_crossings( + sample_wav_bytes, + sample_loop["start"], sample_loop["end"]) + sample_loop = dict(sample_loop, start=_ls, end=_le) + else: + # Default: loop the whole file from frame 0 to end. + sample_loop = { + "start": 0, + "end": _n_frames, + "count": LOOP_INFINITE, + } + + # Sample XML references the resampled 32 kHz mono file. + sample_xml = _seq_make_sample_xml(sample_wav_arch, "wav", + loop=sample_loop) + + mod_entries: dict[str, bytes] = { + seq_path: seq_xml.encode("utf-8"), + f"{audio_asset}.{ext}": audio_bytes, # original for streaming + sample_asset: sample_xml.encode("utf-8"), + sample_wav_arch: sample_wav_bytes, # 32 kHz mono for instrument + } + + # SoundFont XML stored at the original font's archive path + # so Audio_LoadFont (via ResourceGetDataByCrc) picks it up. + font_id = seq_font_map.get(idx) + font_path = font_path_map.get(font_id) if font_id is not None else None + if font_path: + font_xml = _seq_make_font_xml(sample_asset) + mod_entries[font_path] = font_xml.encode("utf-8") + + mod_name = f"seq_{idx:02d}_{slug}.o2r" + mod_path = os.path.join(out_dir, mod_name) + _upsert_mod_o2r(mod_path, mod_entries) + written += 1 + for iid in self._seq_iids_by_path.get(seq_path, []): + try: + self._seq_tree.set( + iid, "file", "✓ " + os.path.basename(audio_path)) + except Exception: + pass + except Exception as e: + errors.append(f"{os.path.basename(seq_path)}: {e}") + for iid in self._seq_iids_by_path.get(seq_path, []): + try: + self._seq_tree.set(iid, "file", "✗") + except Exception: + pass + + if errors: + messagebox.showerror( + "Write errors", + f"Written: {written}\n\nErrors:\n" + "\n".join(errors), + parent=self) + else: + self._seq_status_var.set( + f"Packed {written} sequence(s) → {out_dir}") + + App().mainloop() + + +# ─── entry point ───────────────────────────────────────────────────────────── + +def main(): + parser = argparse.ArgumentParser( + description="Starship sample editor — browse, export, replace audio in o2r archives.", + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + sub = parser.add_subparsers(dest="command") + + p_list = sub.add_parser("list", help="List samples.") + p_list.add_argument("archive") + p_list.add_argument("--filter", metavar="TEXT") + p_list.add_argument("--codec", type=int, metavar="N") + + p_info = sub.add_parser("info", help="Show details for one sample.") + p_info.add_argument("archive") + p_info.add_argument("asset", metavar="ASSET_PATH") + + p_exp = sub.add_parser("export", help="Export sample data.") + p_exp.add_argument("archive") + p_exp.add_argument("asset", metavar="ASSET_PATH") + p_exp.add_argument("--out", metavar="FILE") + p_exp.add_argument("--decode", action="store_true", + help="Decode ADPCM to WAV instead of raw export.") + + p_play = sub.add_parser("play", help="Play a sample (S16 or ADPCM) via ffplay.") + p_play.add_argument("archive") + p_play.add_argument("asset", metavar="ASSET_PATH") + + p_rep = sub.add_parser("replace", help="Replace a sample with custom audio.") + p_rep.add_argument("archive") + p_rep.add_argument("asset", metavar="ASSET_PATH") + p_rep.add_argument("--input", required=True, metavar="AUDIO_FILE") + p_rep.add_argument("--out-dir", metavar="DIR") + + p_bat = sub.add_parser("batch-replace", + help="Replace many samples at once from a folder or mapping file.") + p_bat.add_argument("archive") + src = p_bat.add_mutually_exclusive_group(required=True) + src.add_argument("--dir", metavar="FOLDER", + help="Folder to scan; matches audio files to samples by basename.") + src.add_argument("--mapping", metavar="JSON_FILE", + help="JSON file with { \"asset/path\": \"audio/file.wav\", … }.") + p_bat.add_argument("--out-dir", metavar="DIR", + help="Output directory for the mod o2r (default: archive directory).") + + p_sproj = sub.add_parser("save-project", + help="Add or update a replacement entry in a project file.") + p_sproj.add_argument("archive") + p_sproj.add_argument("asset", metavar="ASSET_PATH") + p_sproj.add_argument("--input", required=True, metavar="AUDIO_FILE", + help="Replacement audio file to record in the project.") + p_sproj.add_argument("--project", metavar="FILE", + help=f"Project file to write (default: _project{BUNDLE_EXT}).") + p_sproj.add_argument("--out-dir", metavar="DIR", + help="Output directory to store in the project.") + + p_aproj = sub.add_parser("apply-project", + help="Re-apply all replacements recorded in a project file.") + p_aproj.add_argument("project", metavar="PROJECT_FILE") + p_aproj.add_argument("--out-dir", metavar="DIR", + help="Override output directory from the project.") + + p_al = sub.add_parser("alias", + help="Get or set a human-readable alias for a sample.") + p_al.add_argument("archive") + p_al.add_argument("asset", metavar="ASSET_PATH") + p_al.add_argument("alias", nargs="?", default=None, metavar="ALIAS", + help="New alias text. Omit to read; pass empty string to remove.") + + p_exal = sub.add_parser("export-aliases", + help="Export all aliases to a JSON file.") + p_exal.add_argument("archive") + p_exal.add_argument("--out", metavar="FILE", + help="Output path (default: _aliases_export.json)") + + p_gui = sub.add_parser("gui", help="Launch graphical interface (default).") + p_gui.add_argument("archive", nargs="?", default=None) + + args = parser.parse_args() + if args.command is None: + args.command = "gui" + args.archive = None + + { + "list": cmd_list, + "info": cmd_info, + "export": cmd_export, + "play": cmd_play, + "replace": cmd_replace, + "batch-replace": cmd_batch_replace, + "save-project": cmd_save_project, + "apply-project": cmd_apply_project, + "alias": cmd_alias, + "export-aliases": cmd_export_aliases, + "gui": cmd_gui, + }[args.command](args) + + +if __name__ == "__main__": + main() diff --git a/workspace/template/.gitignore b/workspace/template/.gitignore new file mode 100644 index 000000000..7c8852551 --- /dev/null +++ b/workspace/template/.gitignore @@ -0,0 +1,3 @@ +build/ +output/* +.DS_Store \ No newline at end of file diff --git a/workspace/template/.vscode/c_cpp_properties.json b/workspace/template/.vscode/c_cpp_properties.json new file mode 100644 index 000000000..fb3857145 --- /dev/null +++ b/workspace/template/.vscode/c_cpp_properties.json @@ -0,0 +1,56 @@ +{ + "configurations": [ + { + "name": "Mac", + "includePath": [ + "${workspaceFolder}/**", + "${workspaceFolder}/../../", + "${workspaceFolder}/../../include", + "${workspaceFolder}/../../src", + "${workspaceFolder}/../../libultraship/src", + "${workspaceFolder}/../../libultraship/include", + "${workspaceFolder}/../../libultraship/include/libultraship" + ], + "defines": [], + "compilerPath": "/usr/bin/clang", + "cStandard": "c17", + "cppStandard": "c++14", + "intelliSenseMode": "macos-clang-arm64" + }, + { + "name": "Linux", + "includePath": [ + "${workspaceFolder}/**", + "${workspaceFolder}/../../", + "${workspaceFolder}/../../include", + "${workspaceFolder}/../../src", + "${workspaceFolder}/../../libultraship/src", + "${workspaceFolder}/../../libultraship/include", + "${workspaceFolder}/../../libultraship/include/libultraship" + ], + "defines": [], + "compilerPath": "/usr/bin/clang", + "cStandard": "c17", + "cppStandard": "c++14", + "intelliSenseMode": "linux-clang-x64" + }, + { + "name": "Windows", + "includePath": [ + "${workspaceFolder}/**", + "${workspaceFolder}/../../", + "${workspaceFolder}/../../include", + "${workspaceFolder}/../../src", + "${workspaceFolder}/../../libultraship/src", + "${workspaceFolder}/../../libultraship/include", + "${workspaceFolder}/../../libultraship/include/libultraship" + ], + "defines": [], + "compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.29.30133/bin/Hostx64/x64/cl.exe", + "cStandard": "c17", + "cppStandard": "c++14", + "intelliSenseMode": "windows-msvc-x64" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/workspace/template/CMakeLists.txt b/workspace/template/CMakeLists.txt new file mode 100644 index 000000000..793bebaf2 --- /dev/null +++ b/workspace/template/CMakeLists.txt @@ -0,0 +1,112 @@ +cmake_minimum_required(VERSION 3.10) +project(ModTemplate) + +find_package(Python3 REQUIRED COMPONENTS Interpreter) + +set(PARENT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../..) +set(LOCAL_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/include) + +set(INCLUDE_DIRS + ${LOCAL_INCLUDE_DIRS} + ${CMAKE_CURRENT_SOURCE_DIR}/src + ${PARENT_DIR} + ${PARENT_DIR}/include + ${PARENT_DIR}/src + ${PARENT_DIR}/libultraship/src + ${PARENT_DIR}/libultraship/include + ${PARENT_DIR}/libultraship/include/libultraship +) + +file(GLOB_RECURSE SRC_FILES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/*.c") +list(FILTER SRC_FILES EXCLUDE REGEX ".*.inc.c") + +set(BUILD_GEN ${CMAKE_CURRENT_SOURCE_DIR}/output/build.gen) +get_filename_component(OUTPUT_DIR ${BUILD_GEN} DIRECTORY) +file(MAKE_DIRECTORY ${OUTPUT_DIR}) + +set(INTERMEDIATE_OUTPUTS "") +set(COPY_OUTPUTS "") +set(DIST_OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/output/dist) + +# Generate preprocessed source file (Leaves sources in output/dist) +foreach(SOURCE_FILE ${SRC_FILES}) + file(RELATIVE_PATH RELATIVE_FILE ${CMAKE_CURRENT_SOURCE_DIR}/src ${SOURCE_FILE}) + set(OUTPUT_FILE ${DIST_OUTPUT}/${RELATIVE_FILE}) + get_filename_component(INTERMEDIATE_DIR ${OUTPUT_FILE} DIRECTORY) + + add_custom_command( + OUTPUT ${OUTPUT_FILE} + COMMAND ${CMAKE_COMMAND} -E make_directory ${INTERMEDIATE_DIR} + COMMAND Python3::Interpreter ${PARENT_DIR}/tools/merge.py + --out ${OUTPUT_FILE} + --includes ${INCLUDE_DIRS} + --src ${SOURCE_FILE} + DEPENDS ${SOURCE_FILE} ${PARENT_DIR}/tools/merge.py + VERBATIM + ) + + list(APPEND INTERMEDIATE_OUTPUTS ${OUTPUT_FILE}) +endforeach() + +# Copy headers into output folder +foreach(INCLUDE_DIR ${LOCAL_INCLUDE_DIRS}) + file(GLOB_RECURSE HEADER_FILES CONFIGURE_DEPENDS "${INCLUDE_DIR}/*.h") + foreach(HEADER_FILE ${HEADER_FILES}) + file(RELATIVE_PATH RELATIVE_HEADER ${INCLUDE_DIR} ${HEADER_FILE}) + + set(OUTPUT_HEADER ${OUTPUT_DIR}/include/${RELATIVE_HEADER}) + + get_filename_component(HEADER_OUTPUT_DIR ${OUTPUT_HEADER} DIRECTORY) + + add_custom_command( + OUTPUT ${OUTPUT_HEADER} + COMMAND ${CMAKE_COMMAND} -E make_directory ${HEADER_OUTPUT_DIR} + COMMAND ${CMAKE_COMMAND} -E copy_if_different ${HEADER_FILE} ${OUTPUT_HEADER} + DEPENDS ${HEADER_FILE} + VERBATIM + ) + + list(APPEND COPY_OUTPUTS ${OUTPUT_HEADER}) + endforeach() +endforeach() + +# Copy assets into output folder +file(GLOB_RECURSE ASSET_FILES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/assets/*") +foreach(ASSET_FILE ${ASSET_FILES}) + file(RELATIVE_PATH RELATIVE_ASSET ${CMAKE_CURRENT_SOURCE_DIR}/assets ${ASSET_FILE}) + + set(OUTPUT_ASSET ${OUTPUT_DIR}/${RELATIVE_ASSET}) + + get_filename_component(ASSET_OUTPUT_DIR ${OUTPUT_ASSET} DIRECTORY) + + add_custom_command( + OUTPUT ${OUTPUT_ASSET} + COMMAND ${CMAKE_COMMAND} -E make_directory ${ASSET_OUTPUT_DIR} + COMMAND ${CMAKE_COMMAND} -E copy_if_different ${ASSET_FILE} ${OUTPUT_ASSET} + DEPENDS ${ASSET_FILE} + VERBATIM + ) + + list(APPEND COPY_OUTPUTS ${OUTPUT_ASSET}) +endforeach() + +# Copy manifest into output folder +set(MANIFEST_FILE ${CMAKE_CURRENT_SOURCE_DIR}/manifest.json) + +set(OUTPUT_MANIFEST ${OUTPUT_DIR}/manifest.json) + +get_filename_component(MANIFEST_OUTPUT_DIR ${OUTPUT_MANIFEST} DIRECTORY) +add_custom_command( + OUTPUT ${OUTPUT_MANIFEST} + COMMAND ${CMAKE_COMMAND} -E make_directory ${MANIFEST_OUTPUT_DIR} + COMMAND ${CMAKE_COMMAND} -E copy_if_different ${MANIFEST_FILE} ${OUTPUT_MANIFEST} + DEPENDS ${MANIFEST_FILE} + VERBATIM +) +list(APPEND COPY_OUTPUTS ${OUTPUT_MANIFEST}) + +string(REPLACE ";" "\n" FORMATTED_FILE_LIST "${INTERMEDIATE_OUTPUTS}") +string(REPLACE "${CMAKE_CURRENT_SOURCE_DIR}/output/" "" FORMATTED_FILE_LIST "${FORMATTED_FILE_LIST}") +file(WRITE ${BUILD_GEN} "${FORMATTED_FILE_LIST}\n") + +add_custom_target(generate_packaged_mod ALL DEPENDS ${INTERMEDIATE_OUTPUTS} ${COPY_OUTPUTS}) \ No newline at end of file diff --git a/workspace/template/README.md b/workspace/template/README.md new file mode 100644 index 000000000..0cfd22424 --- /dev/null +++ b/workspace/template/README.md @@ -0,0 +1,87 @@ +# **Harbour Masters C Mod Template** + +A streamlined template for creating C-based mods for games utilizing the libultraship engine (e.g., Super Mario 64 PC ports). + +This template utilizes a Unity Build (amalgamation) pipeline. It allows you to write clean, modular C code organized across multiple directories, and automatically compiles them down into a single, portable mod.c file. This single-file output is perfectly formatted for dynamic compilation and loading via TCC (Tiny C Compiler) or for easy distribution. + +## **🌟 Features** + +* **Automated Amalgamation:** Uses a custom Python script hooked into CMake to safely merge all your .c and .h files, preventing redefinition errors. +* **Cross-Platform Exports:** Includes HM_API macros to handle the exact ABI export rules so the engine's dynamic linker can always find your ModInit function. +* **Event Hooking:** Includes a working boilerplate for tapping into the engine's event system (e.g., GameFrameUpdate, RenderGamePost). + +## **📂 Directory Structure** + +``` +├── CMakeLists.txt # The build configuration +├── include/ +│ └── mod.h # Core macros (MOD_INIT, MOD_EXIT, HM_API) +├── src/ +│ └── demo.c # Your actual mod logic and event listeners +└── output/ + ├── dist/ # The final c files goes here after building + ├── build.gen # The list of how to build the mod (auto-generated) + └── manifest.json # Metadata for the mod loader +``` + +## **🚀 Getting Started** + +### **Prerequisites** + +* **CMake** (3.10 or higher) +* **Python 3** (used for the amalgamation step) +* The libultraship source headers available in your parent directory structure. + +### **Building the Mod** + +We use an out-of-source build to keep the working directory clean. The CMake script will automatically grab all files in the src/ directory and generate the single mod.c in the output/ folder. + +1. Open your terminal in the project root. +2. Create a build directory and configure the project: + ```Bash + mkdir build + cd build + cmake .. + ``` + +3. Run the build process: + ```Bash + cmake --build . + ``` + +4. Your fully amalgamated mod will be available at output/mod.c, ready to be packaged alongside manifest.json. + +## **🛠️ Writing Your Mod** + +### **The Entry and Exit Points** + +Every mod requires an entry point so the engine knows how to initialize it. Use the provided macros from mod.h: + +```C +#include "mod.h" + +MOD_INIT() { + // Called when the mod is dynamically loaded. + // Register your engine listeners here. +} + +MOD_EXIT() { + // Called when the mod is unloaded or the game closes. + // Unregister your listeners and free memory here. +} +``` + +### **Hooking into Engine Events** + +The template includes a demo.c file showing how to hook into the engine's game loop. + +* **GameFrameUpdate**: Ideal for gameplay logic (e.g., modifying gMarioState). +* **RenderGamePost**: Ideal for drawing custom UI (e.g., using print_text_centered). + +Make sure to store your ListenerIDs globally so you can properly unregister them in MOD_EXIT(). + +### **⚠️ Important Note on Unity Builds (Amalgamation)** + +Because all of your .c files are ultimately merged into a single mod.c file, everything shares the same global scope. + +* **Use static:** If you write a helper function that should only be used internally, **always** prefix it with static. This ensures it won't accidentally collide with functions of the same name in the game engine or other mods once loaded into memory. \ No newline at end of file diff --git a/workspace/template/assets/.gitkeep b/workspace/template/assets/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/workspace/template/include/cimgui.h b/workspace/template/include/cimgui.h new file mode 100644 index 000000000..29940f6e8 --- /dev/null +++ b/workspace/template/include/cimgui.h @@ -0,0 +1,5097 @@ +//This file is automatically generated by generator.lua from https://github.com/cimgui/cimgui +//based on imgui.h file version "1.91.9b" 19191 from Dear ImGui https://github.com/ocornut/imgui +//with imgui_internal.h api +//with imgui_freetype.h api +//docking branch +#ifndef CIMGUI_INCLUDED +#define CIMGUI_INCLUDED +#include +#include +#if defined _WIN32 || defined __CYGWIN__ + #ifdef CIMGUI_NO_EXPORT + #define API + #else + #define API __declspec(dllexport) + #endif +#else + #ifdef __GNUC__ + #define API __attribute__((__visibility__("default"))) + #else + #define API + #endif +#endif + +#if defined __cplusplus + #define EXTERN extern "C" +#else + #include + #include + #define EXTERN extern +#endif + +#define CIMGUI_API EXTERN API +#define CONST const + + +#ifdef _MSC_VER +typedef unsigned __int64 ImU64; +#else +//typedef unsigned long long ImU64; +#endif + + +#ifdef CIMGUI_DEFINE_ENUMS_AND_STRUCTS + +typedef struct ImDrawChannel ImDrawChannel; +typedef struct ImDrawCmd ImDrawCmd; +typedef struct ImDrawData ImDrawData; +typedef struct ImDrawList ImDrawList; +typedef struct ImDrawListSharedData ImDrawListSharedData; +typedef struct ImDrawListSplitter ImDrawListSplitter; +typedef struct ImDrawVert ImDrawVert; +typedef struct ImFont ImFont; +typedef struct ImFontAtlas ImFontAtlas; +typedef struct ImFontBuilderIO ImFontBuilderIO; +typedef struct ImFontConfig ImFontConfig; +typedef struct ImFontGlyph ImFontGlyph; +typedef struct ImFontGlyphRangesBuilder ImFontGlyphRangesBuilder; +typedef struct ImColor ImColor; +typedef struct ImGuiContext ImGuiContext; +typedef struct ImGuiIO ImGuiIO; +typedef struct ImGuiInputTextCallbackData ImGuiInputTextCallbackData; +typedef struct ImGuiKeyData ImGuiKeyData; +typedef struct ImGuiListClipper ImGuiListClipper; +typedef struct ImGuiMultiSelectIO ImGuiMultiSelectIO; +typedef struct ImGuiOnceUponAFrame ImGuiOnceUponAFrame; +typedef struct ImGuiPayload ImGuiPayload; +typedef struct ImGuiPlatformIO ImGuiPlatformIO; +typedef struct ImGuiPlatformImeData ImGuiPlatformImeData; +typedef struct ImGuiPlatformMonitor ImGuiPlatformMonitor; +typedef struct ImGuiSelectionBasicStorage ImGuiSelectionBasicStorage; +typedef struct ImGuiSelectionExternalStorage ImGuiSelectionExternalStorage; +typedef struct ImGuiSelectionRequest ImGuiSelectionRequest; +typedef struct ImGuiSizeCallbackData ImGuiSizeCallbackData; +typedef struct ImGuiStorage ImGuiStorage; +typedef struct ImGuiStoragePair ImGuiStoragePair; +typedef struct ImGuiStyle ImGuiStyle; +typedef struct ImGuiTableSortSpecs ImGuiTableSortSpecs; +typedef struct ImGuiTableColumnSortSpecs ImGuiTableColumnSortSpecs; +typedef struct ImGuiTextBuffer ImGuiTextBuffer; +typedef struct ImGuiTextFilter ImGuiTextFilter; +typedef struct ImGuiViewport ImGuiViewport; +typedef struct ImGuiWindowClass ImGuiWindowClass; +typedef struct ImBitVector ImBitVector; +typedef struct ImRect ImRect; +typedef struct ImGuiTextIndex ImGuiTextIndex; +typedef struct ImDrawDataBuilder ImDrawDataBuilder; +typedef struct ImGuiBoxSelectState ImGuiBoxSelectState; +typedef struct ImGuiColorMod ImGuiColorMod; +typedef struct ImGuiContextHook ImGuiContextHook; +typedef struct ImGuiDataTypeInfo ImGuiDataTypeInfo; +typedef struct ImGuiDeactivatedItemData ImGuiDeactivatedItemData; +typedef struct ImGuiDockContext ImGuiDockContext; +typedef struct ImGuiDockRequest ImGuiDockRequest; +typedef struct ImGuiDockNode ImGuiDockNode; +typedef struct ImGuiDockNodeSettings ImGuiDockNodeSettings; +typedef struct ImGuiErrorRecoveryState ImGuiErrorRecoveryState; +typedef struct ImGuiGroupData ImGuiGroupData; +typedef struct ImGuiInputTextState ImGuiInputTextState; +typedef struct ImGuiInputTextDeactivateData ImGuiInputTextDeactivateData; +typedef struct ImGuiLastItemData ImGuiLastItemData; +typedef struct ImGuiLocEntry ImGuiLocEntry; +typedef struct ImGuiMenuColumns ImGuiMenuColumns; +typedef struct ImGuiMultiSelectState ImGuiMultiSelectState; +typedef struct ImGuiMultiSelectTempData ImGuiMultiSelectTempData; +typedef struct ImGuiNavItemData ImGuiNavItemData; +typedef struct ImGuiMetricsConfig ImGuiMetricsConfig; +typedef struct ImGuiNextWindowData ImGuiNextWindowData; +typedef struct ImGuiNextItemData ImGuiNextItemData; +typedef struct ImGuiOldColumnData ImGuiOldColumnData; +typedef struct ImGuiOldColumns ImGuiOldColumns; +typedef struct ImGuiPopupData ImGuiPopupData; +typedef struct ImGuiSettingsHandler ImGuiSettingsHandler; +typedef struct ImGuiStyleMod ImGuiStyleMod; +typedef struct ImGuiStyleVarInfo ImGuiStyleVarInfo; +typedef struct ImGuiTabBar ImGuiTabBar; +typedef struct ImGuiTabItem ImGuiTabItem; +typedef struct ImGuiTable ImGuiTable; +typedef struct ImGuiTableHeaderData ImGuiTableHeaderData; +typedef struct ImGuiTableColumn ImGuiTableColumn; +typedef struct ImGuiTableInstanceData ImGuiTableInstanceData; +typedef struct ImGuiTableTempData ImGuiTableTempData; +typedef struct ImGuiTableSettings ImGuiTableSettings; +typedef struct ImGuiTableColumnsSettings ImGuiTableColumnsSettings; +typedef struct ImGuiTreeNodeStackData ImGuiTreeNodeStackData; +typedef struct ImGuiTypingSelectState ImGuiTypingSelectState; +typedef struct ImGuiTypingSelectRequest ImGuiTypingSelectRequest; +typedef struct ImGuiWindow ImGuiWindow; +typedef struct ImGuiWindowDockStyle ImGuiWindowDockStyle; +typedef struct ImGuiWindowTempData ImGuiWindowTempData; +typedef struct ImGuiWindowSettings ImGuiWindowSettings; +typedef struct STB_TexteditState STB_TexteditState; +typedef struct ImVector_const_charPtr {int Size;int Capacity;const char** Data;} ImVector_const_charPtr; + +typedef unsigned int ImGuiID; +typedef signed char ImS8; +typedef unsigned char ImU8; +typedef signed short ImS16; +typedef unsigned short ImU16; +typedef signed int ImS32; +typedef unsigned int ImU32; +typedef signed long long ImS64; +typedef unsigned long long ImU64; +struct ImDrawChannel; +struct ImDrawCmd; +struct ImDrawData; +struct ImDrawList; +struct ImDrawListSharedData; +struct ImDrawListSplitter; +struct ImDrawVert; +struct ImFont; +struct ImFontAtlas; +struct ImFontBuilderIO; +struct ImFontConfig; +struct ImFontGlyph; +struct ImFontGlyphRangesBuilder; +struct ImColor; +struct ImGuiContext; +struct ImGuiIO; +struct ImGuiInputTextCallbackData; +struct ImGuiKeyData; +struct ImGuiListClipper; +struct ImGuiMultiSelectIO; +struct ImGuiOnceUponAFrame; +struct ImGuiPayload; +struct ImGuiPlatformIO; +struct ImGuiPlatformImeData; +struct ImGuiPlatformMonitor; +struct ImGuiSelectionBasicStorage; +struct ImGuiSelectionExternalStorage; +struct ImGuiSelectionRequest; +struct ImGuiSizeCallbackData; +struct ImGuiStorage; +struct ImGuiStoragePair; +struct ImGuiStyle; +struct ImGuiTableSortSpecs; +struct ImGuiTableColumnSortSpecs; +struct ImGuiTextBuffer; +struct ImGuiTextFilter; +struct ImGuiViewport; +struct ImGuiWindowClass; +typedef int ImGuiCol; +typedef int ImGuiCond; +typedef int ImGuiDataType; +typedef int ImGuiMouseButton; +typedef int ImGuiMouseCursor; +typedef int ImGuiStyleVar; +typedef int ImGuiTableBgTarget; +typedef int ImDrawFlags; +typedef int ImDrawListFlags; +typedef int ImFontAtlasFlags; +typedef int ImGuiBackendFlags; +typedef int ImGuiButtonFlags; +typedef int ImGuiChildFlags; +typedef int ImGuiColorEditFlags; +typedef int ImGuiConfigFlags; +typedef int ImGuiComboFlags; +typedef int ImGuiDockNodeFlags; +typedef int ImGuiDragDropFlags; +typedef int ImGuiFocusedFlags; +typedef int ImGuiHoveredFlags; +typedef int ImGuiInputFlags; +typedef int ImGuiInputTextFlags; +typedef int ImGuiItemFlags; +typedef int ImGuiKeyChord; +typedef int ImGuiPopupFlags; +typedef int ImGuiMultiSelectFlags; +typedef int ImGuiSelectableFlags; +typedef int ImGuiSliderFlags; +typedef int ImGuiTabBarFlags; +typedef int ImGuiTabItemFlags; +typedef int ImGuiTableFlags; +typedef int ImGuiTableColumnFlags; +typedef int ImGuiTableRowFlags; +typedef int ImGuiTreeNodeFlags; +typedef int ImGuiViewportFlags; +typedef int ImGuiWindowFlags; +typedef unsigned int ImWchar32; +typedef unsigned short ImWchar16; + +#ifdef IMGUI_USE_WCHAR32 +typedef ImWchar32 ImWchar; +#else +typedef ImWchar16 ImWchar; +#endif +#ifdef IMGUI_USE_WCHAR32 +#define IM_UNICODE_CODEPOINT_MAX 0x10FFFF +#else +#define IM_UNICODE_CODEPOINT_MAX 0xFFFF +#endif + +typedef ImS64 ImGuiSelectionUserData; +typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData* data); +typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data); +typedef void* (*ImGuiMemAllocFunc)(size_t sz, void* user_data); +typedef void (*ImGuiMemFreeFunc)(void* ptr, void* user_data); +typedef struct ImVec2 ImVec2; +struct ImVec2 +{ + float x, y; +}; +typedef struct ImVec4 ImVec4; +struct ImVec4 +{ + float x, y, z, w; +}; +typedef ImU64 ImTextureID; +typedef enum { + ImGuiWindowFlags_None = 0, + ImGuiWindowFlags_NoTitleBar = 1 << 0, + ImGuiWindowFlags_NoResize = 1 << 1, + ImGuiWindowFlags_NoMove = 1 << 2, + ImGuiWindowFlags_NoScrollbar = 1 << 3, + ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, + ImGuiWindowFlags_NoCollapse = 1 << 5, + ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, + ImGuiWindowFlags_NoBackground = 1 << 7, + ImGuiWindowFlags_NoSavedSettings = 1 << 8, + ImGuiWindowFlags_NoMouseInputs = 1 << 9, + ImGuiWindowFlags_MenuBar = 1 << 10, + ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, + ImGuiWindowFlags_NoFocusOnAppearing = 1 << 12, + ImGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13, + ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, + ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, + ImGuiWindowFlags_NoNavInputs = 1 << 16, + ImGuiWindowFlags_NoNavFocus = 1 << 17, + ImGuiWindowFlags_UnsavedDocument = 1 << 18, + ImGuiWindowFlags_NoDocking = 1 << 19, + ImGuiWindowFlags_NoNav = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, + ImGuiWindowFlags_NoDecoration = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse, + ImGuiWindowFlags_NoInputs = ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, + ImGuiWindowFlags_DockNodeHost = 1 << 23, + ImGuiWindowFlags_ChildWindow = 1 << 24, + ImGuiWindowFlags_Tooltip = 1 << 25, + ImGuiWindowFlags_Popup = 1 << 26, + ImGuiWindowFlags_Modal = 1 << 27, + ImGuiWindowFlags_ChildMenu = 1 << 28, +}ImGuiWindowFlags_; +typedef enum { + ImGuiChildFlags_None = 0, + ImGuiChildFlags_Borders = 1 << 0, + ImGuiChildFlags_AlwaysUseWindowPadding = 1 << 1, + ImGuiChildFlags_ResizeX = 1 << 2, + ImGuiChildFlags_ResizeY = 1 << 3, + ImGuiChildFlags_AutoResizeX = 1 << 4, + ImGuiChildFlags_AutoResizeY = 1 << 5, + ImGuiChildFlags_AlwaysAutoResize = 1 << 6, + ImGuiChildFlags_FrameStyle = 1 << 7, + ImGuiChildFlags_NavFlattened = 1 << 8, +}ImGuiChildFlags_; +typedef enum { + ImGuiItemFlags_None = 0, + ImGuiItemFlags_NoTabStop = 1 << 0, + ImGuiItemFlags_NoNav = 1 << 1, + ImGuiItemFlags_NoNavDefaultFocus = 1 << 2, + ImGuiItemFlags_ButtonRepeat = 1 << 3, + ImGuiItemFlags_AutoClosePopups = 1 << 4, + ImGuiItemFlags_AllowDuplicateId = 1 << 5, +}ImGuiItemFlags_; +typedef enum { + ImGuiInputTextFlags_None = 0, + ImGuiInputTextFlags_CharsDecimal = 1 << 0, + ImGuiInputTextFlags_CharsHexadecimal = 1 << 1, + ImGuiInputTextFlags_CharsScientific = 1 << 2, + ImGuiInputTextFlags_CharsUppercase = 1 << 3, + ImGuiInputTextFlags_CharsNoBlank = 1 << 4, + ImGuiInputTextFlags_AllowTabInput = 1 << 5, + ImGuiInputTextFlags_EnterReturnsTrue = 1 << 6, + ImGuiInputTextFlags_EscapeClearsAll = 1 << 7, + ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 8, + ImGuiInputTextFlags_ReadOnly = 1 << 9, + ImGuiInputTextFlags_Password = 1 << 10, + ImGuiInputTextFlags_AlwaysOverwrite = 1 << 11, + ImGuiInputTextFlags_AutoSelectAll = 1 << 12, + ImGuiInputTextFlags_ParseEmptyRefVal = 1 << 13, + ImGuiInputTextFlags_DisplayEmptyRefVal = 1 << 14, + ImGuiInputTextFlags_NoHorizontalScroll = 1 << 15, + ImGuiInputTextFlags_NoUndoRedo = 1 << 16, + ImGuiInputTextFlags_ElideLeft = 1 << 17, + ImGuiInputTextFlags_CallbackCompletion = 1 << 18, + ImGuiInputTextFlags_CallbackHistory = 1 << 19, + ImGuiInputTextFlags_CallbackAlways = 1 << 20, + ImGuiInputTextFlags_CallbackCharFilter = 1 << 21, + ImGuiInputTextFlags_CallbackResize = 1 << 22, + ImGuiInputTextFlags_CallbackEdit = 1 << 23, +}ImGuiInputTextFlags_; +typedef enum { + ImGuiTreeNodeFlags_None = 0, + ImGuiTreeNodeFlags_Selected = 1 << 0, + ImGuiTreeNodeFlags_Framed = 1 << 1, + ImGuiTreeNodeFlags_AllowOverlap = 1 << 2, + ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, + ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, + ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, + ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, + ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, + ImGuiTreeNodeFlags_Leaf = 1 << 8, + ImGuiTreeNodeFlags_Bullet = 1 << 9, + ImGuiTreeNodeFlags_FramePadding = 1 << 10, + ImGuiTreeNodeFlags_SpanAvailWidth = 1 << 11, + ImGuiTreeNodeFlags_SpanFullWidth = 1 << 12, + ImGuiTreeNodeFlags_SpanLabelWidth = 1 << 13, + ImGuiTreeNodeFlags_SpanAllColumns = 1 << 14, + ImGuiTreeNodeFlags_LabelSpanAllColumns = 1 << 15, + ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 17, + ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog, +}ImGuiTreeNodeFlags_; +typedef enum { + ImGuiPopupFlags_None = 0, + ImGuiPopupFlags_MouseButtonLeft = 0, + ImGuiPopupFlags_MouseButtonRight = 1, + ImGuiPopupFlags_MouseButtonMiddle = 2, + ImGuiPopupFlags_MouseButtonMask_ = 0x1F, + ImGuiPopupFlags_MouseButtonDefault_ = 1, + ImGuiPopupFlags_NoReopen = 1 << 5, + ImGuiPopupFlags_NoOpenOverExistingPopup = 1 << 7, + ImGuiPopupFlags_NoOpenOverItems = 1 << 8, + ImGuiPopupFlags_AnyPopupId = 1 << 10, + ImGuiPopupFlags_AnyPopupLevel = 1 << 11, + ImGuiPopupFlags_AnyPopup = ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel, +}ImGuiPopupFlags_; +typedef enum { + ImGuiSelectableFlags_None = 0, + ImGuiSelectableFlags_NoAutoClosePopups = 1 << 0, + ImGuiSelectableFlags_SpanAllColumns = 1 << 1, + ImGuiSelectableFlags_AllowDoubleClick = 1 << 2, + ImGuiSelectableFlags_Disabled = 1 << 3, + ImGuiSelectableFlags_AllowOverlap = 1 << 4, + ImGuiSelectableFlags_Highlight = 1 << 5, +}ImGuiSelectableFlags_; +typedef enum { + ImGuiComboFlags_None = 0, + ImGuiComboFlags_PopupAlignLeft = 1 << 0, + ImGuiComboFlags_HeightSmall = 1 << 1, + ImGuiComboFlags_HeightRegular = 1 << 2, + ImGuiComboFlags_HeightLarge = 1 << 3, + ImGuiComboFlags_HeightLargest = 1 << 4, + ImGuiComboFlags_NoArrowButton = 1 << 5, + ImGuiComboFlags_NoPreview = 1 << 6, + ImGuiComboFlags_WidthFitPreview = 1 << 7, + ImGuiComboFlags_HeightMask_ = ImGuiComboFlags_HeightSmall | ImGuiComboFlags_HeightRegular | ImGuiComboFlags_HeightLarge | ImGuiComboFlags_HeightLargest, +}ImGuiComboFlags_; +typedef enum { + ImGuiTabBarFlags_None = 0, + ImGuiTabBarFlags_Reorderable = 1 << 0, + ImGuiTabBarFlags_AutoSelectNewTabs = 1 << 1, + ImGuiTabBarFlags_TabListPopupButton = 1 << 2, + ImGuiTabBarFlags_NoCloseWithMiddleMouseButton = 1 << 3, + ImGuiTabBarFlags_NoTabListScrollingButtons = 1 << 4, + ImGuiTabBarFlags_NoTooltip = 1 << 5, + ImGuiTabBarFlags_DrawSelectedOverline = 1 << 6, + ImGuiTabBarFlags_FittingPolicyResizeDown = 1 << 7, + ImGuiTabBarFlags_FittingPolicyScroll = 1 << 8, + ImGuiTabBarFlags_FittingPolicyMask_ = ImGuiTabBarFlags_FittingPolicyResizeDown | ImGuiTabBarFlags_FittingPolicyScroll, + ImGuiTabBarFlags_FittingPolicyDefault_ = ImGuiTabBarFlags_FittingPolicyResizeDown, +}ImGuiTabBarFlags_; +typedef enum { + ImGuiTabItemFlags_None = 0, + ImGuiTabItemFlags_UnsavedDocument = 1 << 0, + ImGuiTabItemFlags_SetSelected = 1 << 1, + ImGuiTabItemFlags_NoCloseWithMiddleMouseButton = 1 << 2, + ImGuiTabItemFlags_NoPushId = 1 << 3, + ImGuiTabItemFlags_NoTooltip = 1 << 4, + ImGuiTabItemFlags_NoReorder = 1 << 5, + ImGuiTabItemFlags_Leading = 1 << 6, + ImGuiTabItemFlags_Trailing = 1 << 7, + ImGuiTabItemFlags_NoAssumedClosure = 1 << 8, +}ImGuiTabItemFlags_; +typedef enum { + ImGuiFocusedFlags_None = 0, + ImGuiFocusedFlags_ChildWindows = 1 << 0, + ImGuiFocusedFlags_RootWindow = 1 << 1, + ImGuiFocusedFlags_AnyWindow = 1 << 2, + ImGuiFocusedFlags_NoPopupHierarchy = 1 << 3, + ImGuiFocusedFlags_DockHierarchy = 1 << 4, + ImGuiFocusedFlags_RootAndChildWindows = ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows, +}ImGuiFocusedFlags_; +typedef enum { + ImGuiHoveredFlags_None = 0, + ImGuiHoveredFlags_ChildWindows = 1 << 0, + ImGuiHoveredFlags_RootWindow = 1 << 1, + ImGuiHoveredFlags_AnyWindow = 1 << 2, + ImGuiHoveredFlags_NoPopupHierarchy = 1 << 3, + ImGuiHoveredFlags_DockHierarchy = 1 << 4, + ImGuiHoveredFlags_AllowWhenBlockedByPopup = 1 << 5, + ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = 1 << 7, + ImGuiHoveredFlags_AllowWhenOverlappedByItem = 1 << 8, + ImGuiHoveredFlags_AllowWhenOverlappedByWindow = 1 << 9, + ImGuiHoveredFlags_AllowWhenDisabled = 1 << 10, + ImGuiHoveredFlags_NoNavOverride = 1 << 11, + ImGuiHoveredFlags_AllowWhenOverlapped = ImGuiHoveredFlags_AllowWhenOverlappedByItem | ImGuiHoveredFlags_AllowWhenOverlappedByWindow, + ImGuiHoveredFlags_RectOnly = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped, + ImGuiHoveredFlags_RootAndChildWindows = ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows, + ImGuiHoveredFlags_ForTooltip = 1 << 12, + ImGuiHoveredFlags_Stationary = 1 << 13, + ImGuiHoveredFlags_DelayNone = 1 << 14, + ImGuiHoveredFlags_DelayShort = 1 << 15, + ImGuiHoveredFlags_DelayNormal = 1 << 16, + ImGuiHoveredFlags_NoSharedDelay = 1 << 17, +}ImGuiHoveredFlags_; +typedef enum { + ImGuiDockNodeFlags_None = 0, + ImGuiDockNodeFlags_KeepAliveOnly = 1 << 0, + ImGuiDockNodeFlags_NoDockingOverCentralNode = 1 << 2, + ImGuiDockNodeFlags_PassthruCentralNode = 1 << 3, + ImGuiDockNodeFlags_NoDockingSplit = 1 << 4, + ImGuiDockNodeFlags_NoResize = 1 << 5, + ImGuiDockNodeFlags_AutoHideTabBar = 1 << 6, + ImGuiDockNodeFlags_NoUndocking = 1 << 7, +}ImGuiDockNodeFlags_; +typedef enum { + ImGuiDragDropFlags_None = 0, + ImGuiDragDropFlags_SourceNoPreviewTooltip = 1 << 0, + ImGuiDragDropFlags_SourceNoDisableHover = 1 << 1, + ImGuiDragDropFlags_SourceNoHoldToOpenOthers = 1 << 2, + ImGuiDragDropFlags_SourceAllowNullID = 1 << 3, + ImGuiDragDropFlags_SourceExtern = 1 << 4, + ImGuiDragDropFlags_PayloadAutoExpire = 1 << 5, + ImGuiDragDropFlags_PayloadNoCrossContext = 1 << 6, + ImGuiDragDropFlags_PayloadNoCrossProcess = 1 << 7, + ImGuiDragDropFlags_AcceptBeforeDelivery = 1 << 10, + ImGuiDragDropFlags_AcceptNoDrawDefaultRect = 1 << 11, + ImGuiDragDropFlags_AcceptNoPreviewTooltip = 1 << 12, + ImGuiDragDropFlags_AcceptPeekOnly = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect, +}ImGuiDragDropFlags_; +typedef enum { + ImGuiDataType_S8, + ImGuiDataType_U8, + ImGuiDataType_S16, + ImGuiDataType_U16, + ImGuiDataType_S32, + ImGuiDataType_U32, + ImGuiDataType_S64, + ImGuiDataType_U64, + ImGuiDataType_Float, + ImGuiDataType_Double, + ImGuiDataType_Bool, + ImGuiDataType_String, + ImGuiDataType_COUNT +}ImGuiDataType_; +typedef enum { +ImGuiDir_None=-1, +ImGuiDir_Left=0, +ImGuiDir_Right=1, +ImGuiDir_Up=2, +ImGuiDir_Down=3, +ImGuiDir_COUNT=4, +}ImGuiDir; +typedef enum { +ImGuiSortDirection_None=0, +ImGuiSortDirection_Ascending=1, +ImGuiSortDirection_Descending=2, +}ImGuiSortDirection; +typedef enum { +ImGuiKey_None=0, +ImGuiKey_NamedKey_BEGIN=512, +ImGuiKey_Tab=512, +ImGuiKey_LeftArrow=513, +ImGuiKey_RightArrow=514, +ImGuiKey_UpArrow=515, +ImGuiKey_DownArrow=516, +ImGuiKey_PageUp=517, +ImGuiKey_PageDown=518, +ImGuiKey_Home=519, +ImGuiKey_End=520, +ImGuiKey_Insert=521, +ImGuiKey_Delete=522, +ImGuiKey_Backspace=523, +ImGuiKey_Space=524, +ImGuiKey_Enter=525, +ImGuiKey_Escape=526, +ImGuiKey_LeftCtrl=527, +ImGuiKey_LeftShift=528, +ImGuiKey_LeftAlt=529, +ImGuiKey_LeftSuper=530, +ImGuiKey_RightCtrl=531, +ImGuiKey_RightShift=532, +ImGuiKey_RightAlt=533, +ImGuiKey_RightSuper=534, +ImGuiKey_Menu=535, +ImGuiKey_0=536, +ImGuiKey_1=537, +ImGuiKey_2=538, +ImGuiKey_3=539, +ImGuiKey_4=540, +ImGuiKey_5=541, +ImGuiKey_6=542, +ImGuiKey_7=543, +ImGuiKey_8=544, +ImGuiKey_9=545, +ImGuiKey_A=546, +ImGuiKey_B=547, +ImGuiKey_C=548, +ImGuiKey_D=549, +ImGuiKey_E=550, +ImGuiKey_F=551, +ImGuiKey_G=552, +ImGuiKey_H=553, +ImGuiKey_I=554, +ImGuiKey_J=555, +ImGuiKey_K=556, +ImGuiKey_L=557, +ImGuiKey_M=558, +ImGuiKey_N=559, +ImGuiKey_O=560, +ImGuiKey_P=561, +ImGuiKey_Q=562, +ImGuiKey_R=563, +ImGuiKey_S=564, +ImGuiKey_T=565, +ImGuiKey_U=566, +ImGuiKey_V=567, +ImGuiKey_W=568, +ImGuiKey_X=569, +ImGuiKey_Y=570, +ImGuiKey_Z=571, +ImGuiKey_F1=572, +ImGuiKey_F2=573, +ImGuiKey_F3=574, +ImGuiKey_F4=575, +ImGuiKey_F5=576, +ImGuiKey_F6=577, +ImGuiKey_F7=578, +ImGuiKey_F8=579, +ImGuiKey_F9=580, +ImGuiKey_F10=581, +ImGuiKey_F11=582, +ImGuiKey_F12=583, +ImGuiKey_F13=584, +ImGuiKey_F14=585, +ImGuiKey_F15=586, +ImGuiKey_F16=587, +ImGuiKey_F17=588, +ImGuiKey_F18=589, +ImGuiKey_F19=590, +ImGuiKey_F20=591, +ImGuiKey_F21=592, +ImGuiKey_F22=593, +ImGuiKey_F23=594, +ImGuiKey_F24=595, +ImGuiKey_Apostrophe=596, +ImGuiKey_Comma=597, +ImGuiKey_Minus=598, +ImGuiKey_Period=599, +ImGuiKey_Slash=600, +ImGuiKey_Semicolon=601, +ImGuiKey_Equal=602, +ImGuiKey_LeftBracket=603, +ImGuiKey_Backslash=604, +ImGuiKey_RightBracket=605, +ImGuiKey_GraveAccent=606, +ImGuiKey_CapsLock=607, +ImGuiKey_ScrollLock=608, +ImGuiKey_NumLock=609, +ImGuiKey_PrintScreen=610, +ImGuiKey_Pause=611, +ImGuiKey_Keypad0=612, +ImGuiKey_Keypad1=613, +ImGuiKey_Keypad2=614, +ImGuiKey_Keypad3=615, +ImGuiKey_Keypad4=616, +ImGuiKey_Keypad5=617, +ImGuiKey_Keypad6=618, +ImGuiKey_Keypad7=619, +ImGuiKey_Keypad8=620, +ImGuiKey_Keypad9=621, +ImGuiKey_KeypadDecimal=622, +ImGuiKey_KeypadDivide=623, +ImGuiKey_KeypadMultiply=624, +ImGuiKey_KeypadSubtract=625, +ImGuiKey_KeypadAdd=626, +ImGuiKey_KeypadEnter=627, +ImGuiKey_KeypadEqual=628, +ImGuiKey_AppBack=629, +ImGuiKey_AppForward=630, +ImGuiKey_Oem102=631, +ImGuiKey_GamepadStart=632, +ImGuiKey_GamepadBack=633, +ImGuiKey_GamepadFaceLeft=634, +ImGuiKey_GamepadFaceRight=635, +ImGuiKey_GamepadFaceUp=636, +ImGuiKey_GamepadFaceDown=637, +ImGuiKey_GamepadDpadLeft=638, +ImGuiKey_GamepadDpadRight=639, +ImGuiKey_GamepadDpadUp=640, +ImGuiKey_GamepadDpadDown=641, +ImGuiKey_GamepadL1=642, +ImGuiKey_GamepadR1=643, +ImGuiKey_GamepadL2=644, +ImGuiKey_GamepadR2=645, +ImGuiKey_GamepadL3=646, +ImGuiKey_GamepadR3=647, +ImGuiKey_GamepadLStickLeft=648, +ImGuiKey_GamepadLStickRight=649, +ImGuiKey_GamepadLStickUp=650, +ImGuiKey_GamepadLStickDown=651, +ImGuiKey_GamepadRStickLeft=652, +ImGuiKey_GamepadRStickRight=653, +ImGuiKey_GamepadRStickUp=654, +ImGuiKey_GamepadRStickDown=655, +ImGuiKey_MouseLeft=656, +ImGuiKey_MouseRight=657, +ImGuiKey_MouseMiddle=658, +ImGuiKey_MouseX1=659, +ImGuiKey_MouseX2=660, +ImGuiKey_MouseWheelX=661, +ImGuiKey_MouseWheelY=662, +ImGuiKey_ReservedForModCtrl=663, +ImGuiKey_ReservedForModShift=664, +ImGuiKey_ReservedForModAlt=665, +ImGuiKey_ReservedForModSuper=666, +ImGuiKey_NamedKey_END=667, +ImGuiMod_None=0, +ImGuiMod_Ctrl=1 << 12, +ImGuiMod_Shift=1 << 13, +ImGuiMod_Alt=1 << 14, +ImGuiMod_Super=1 << 15, +ImGuiMod_Mask_=0xF000, +ImGuiKey_NamedKey_COUNT=ImGuiKey_NamedKey_END - ImGuiKey_NamedKey_BEGIN, +}ImGuiKey; +typedef enum { + ImGuiInputFlags_None = 0, + ImGuiInputFlags_Repeat = 1 << 0, + ImGuiInputFlags_RouteActive = 1 << 10, + ImGuiInputFlags_RouteFocused = 1 << 11, + ImGuiInputFlags_RouteGlobal = 1 << 12, + ImGuiInputFlags_RouteAlways = 1 << 13, + ImGuiInputFlags_RouteOverFocused = 1 << 14, + ImGuiInputFlags_RouteOverActive = 1 << 15, + ImGuiInputFlags_RouteUnlessBgFocused = 1 << 16, + ImGuiInputFlags_RouteFromRootWindow = 1 << 17, + ImGuiInputFlags_Tooltip = 1 << 18, +}ImGuiInputFlags_; +typedef enum { + ImGuiConfigFlags_None = 0, + ImGuiConfigFlags_NavEnableKeyboard = 1 << 0, + ImGuiConfigFlags_NavEnableGamepad = 1 << 1, + ImGuiConfigFlags_NoMouse = 1 << 4, + ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, + ImGuiConfigFlags_NoKeyboard = 1 << 6, + ImGuiConfigFlags_DockingEnable = 1 << 7, + ImGuiConfigFlags_ViewportsEnable = 1 << 10, + ImGuiConfigFlags_DpiEnableScaleViewports= 1 << 14, + ImGuiConfigFlags_DpiEnableScaleFonts = 1 << 15, + ImGuiConfigFlags_IsSRGB = 1 << 20, + ImGuiConfigFlags_IsTouchScreen = 1 << 21, +}ImGuiConfigFlags_; +typedef enum { + ImGuiBackendFlags_None = 0, + ImGuiBackendFlags_HasGamepad = 1 << 0, + ImGuiBackendFlags_HasMouseCursors = 1 << 1, + ImGuiBackendFlags_HasSetMousePos = 1 << 2, + ImGuiBackendFlags_RendererHasVtxOffset = 1 << 3, + ImGuiBackendFlags_PlatformHasViewports = 1 << 10, + ImGuiBackendFlags_HasMouseHoveredViewport=1 << 11, + ImGuiBackendFlags_RendererHasViewports = 1 << 12, +}ImGuiBackendFlags_; +typedef enum { + ImGuiCol_Text, + ImGuiCol_TextDisabled, + ImGuiCol_WindowBg, + ImGuiCol_ChildBg, + ImGuiCol_PopupBg, + ImGuiCol_Border, + ImGuiCol_BorderShadow, + ImGuiCol_FrameBg, + ImGuiCol_FrameBgHovered, + ImGuiCol_FrameBgActive, + ImGuiCol_TitleBg, + ImGuiCol_TitleBgActive, + ImGuiCol_TitleBgCollapsed, + ImGuiCol_MenuBarBg, + ImGuiCol_ScrollbarBg, + ImGuiCol_ScrollbarGrab, + ImGuiCol_ScrollbarGrabHovered, + ImGuiCol_ScrollbarGrabActive, + ImGuiCol_CheckMark, + ImGuiCol_SliderGrab, + ImGuiCol_SliderGrabActive, + ImGuiCol_Button, + ImGuiCol_ButtonHovered, + ImGuiCol_ButtonActive, + ImGuiCol_Header, + ImGuiCol_HeaderHovered, + ImGuiCol_HeaderActive, + ImGuiCol_Separator, + ImGuiCol_SeparatorHovered, + ImGuiCol_SeparatorActive, + ImGuiCol_ResizeGrip, + ImGuiCol_ResizeGripHovered, + ImGuiCol_ResizeGripActive, + ImGuiCol_TabHovered, + ImGuiCol_Tab, + ImGuiCol_TabSelected, + ImGuiCol_TabSelectedOverline, + ImGuiCol_TabDimmed, + ImGuiCol_TabDimmedSelected, + ImGuiCol_TabDimmedSelectedOverline, + ImGuiCol_DockingPreview, + ImGuiCol_DockingEmptyBg, + ImGuiCol_PlotLines, + ImGuiCol_PlotLinesHovered, + ImGuiCol_PlotHistogram, + ImGuiCol_PlotHistogramHovered, + ImGuiCol_TableHeaderBg, + ImGuiCol_TableBorderStrong, + ImGuiCol_TableBorderLight, + ImGuiCol_TableRowBg, + ImGuiCol_TableRowBgAlt, + ImGuiCol_TextLink, + ImGuiCol_TextSelectedBg, + ImGuiCol_DragDropTarget, + ImGuiCol_NavCursor, + ImGuiCol_NavWindowingHighlight, + ImGuiCol_NavWindowingDimBg, + ImGuiCol_ModalWindowDimBg, + ImGuiCol_COUNT, +}ImGuiCol_; +typedef enum { + ImGuiStyleVar_Alpha, + ImGuiStyleVar_DisabledAlpha, + ImGuiStyleVar_WindowPadding, + ImGuiStyleVar_WindowRounding, + ImGuiStyleVar_WindowBorderSize, + ImGuiStyleVar_WindowMinSize, + ImGuiStyleVar_WindowTitleAlign, + ImGuiStyleVar_ChildRounding, + ImGuiStyleVar_ChildBorderSize, + ImGuiStyleVar_PopupRounding, + ImGuiStyleVar_PopupBorderSize, + ImGuiStyleVar_FramePadding, + ImGuiStyleVar_FrameRounding, + ImGuiStyleVar_FrameBorderSize, + ImGuiStyleVar_ItemSpacing, + ImGuiStyleVar_ItemInnerSpacing, + ImGuiStyleVar_IndentSpacing, + ImGuiStyleVar_CellPadding, + ImGuiStyleVar_ScrollbarSize, + ImGuiStyleVar_ScrollbarRounding, + ImGuiStyleVar_GrabMinSize, + ImGuiStyleVar_GrabRounding, + ImGuiStyleVar_ImageBorderSize, + ImGuiStyleVar_TabRounding, + ImGuiStyleVar_TabBorderSize, + ImGuiStyleVar_TabBarBorderSize, + ImGuiStyleVar_TabBarOverlineSize, + ImGuiStyleVar_TableAngledHeadersAngle, + ImGuiStyleVar_TableAngledHeadersTextAlign, + ImGuiStyleVar_ButtonTextAlign, + ImGuiStyleVar_SelectableTextAlign, + ImGuiStyleVar_SeparatorTextBorderSize, + ImGuiStyleVar_SeparatorTextAlign, + ImGuiStyleVar_SeparatorTextPadding, + ImGuiStyleVar_DockingSeparatorSize, + ImGuiStyleVar_COUNT +}ImGuiStyleVar_; +typedef enum { + ImGuiButtonFlags_None = 0, + ImGuiButtonFlags_MouseButtonLeft = 1 << 0, + ImGuiButtonFlags_MouseButtonRight = 1 << 1, + ImGuiButtonFlags_MouseButtonMiddle = 1 << 2, + ImGuiButtonFlags_MouseButtonMask_ = ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight | ImGuiButtonFlags_MouseButtonMiddle, + ImGuiButtonFlags_EnableNav = 1 << 3, +}ImGuiButtonFlags_; +typedef enum { + ImGuiColorEditFlags_None = 0, + ImGuiColorEditFlags_NoAlpha = 1 << 1, + ImGuiColorEditFlags_NoPicker = 1 << 2, + ImGuiColorEditFlags_NoOptions = 1 << 3, + ImGuiColorEditFlags_NoSmallPreview = 1 << 4, + ImGuiColorEditFlags_NoInputs = 1 << 5, + ImGuiColorEditFlags_NoTooltip = 1 << 6, + ImGuiColorEditFlags_NoLabel = 1 << 7, + ImGuiColorEditFlags_NoSidePreview = 1 << 8, + ImGuiColorEditFlags_NoDragDrop = 1 << 9, + ImGuiColorEditFlags_NoBorder = 1 << 10, + ImGuiColorEditFlags_AlphaOpaque = 1 << 11, + ImGuiColorEditFlags_AlphaNoBg = 1 << 12, + ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 13, + ImGuiColorEditFlags_AlphaBar = 1 << 16, + ImGuiColorEditFlags_HDR = 1 << 19, + ImGuiColorEditFlags_DisplayRGB = 1 << 20, + ImGuiColorEditFlags_DisplayHSV = 1 << 21, + ImGuiColorEditFlags_DisplayHex = 1 << 22, + ImGuiColorEditFlags_Uint8 = 1 << 23, + ImGuiColorEditFlags_Float = 1 << 24, + ImGuiColorEditFlags_PickerHueBar = 1 << 25, + ImGuiColorEditFlags_PickerHueWheel = 1 << 26, + ImGuiColorEditFlags_InputRGB = 1 << 27, + ImGuiColorEditFlags_InputHSV = 1 << 28, + ImGuiColorEditFlags_DefaultOptions_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_PickerHueBar, + ImGuiColorEditFlags_AlphaMask_ = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaOpaque | ImGuiColorEditFlags_AlphaNoBg | ImGuiColorEditFlags_AlphaPreviewHalf, + ImGuiColorEditFlags_DisplayMask_ = ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_DisplayHex, + ImGuiColorEditFlags_DataTypeMask_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_Float, + ImGuiColorEditFlags_PickerMask_ = ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_PickerHueBar, + ImGuiColorEditFlags_InputMask_ = ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_InputHSV, +}ImGuiColorEditFlags_; +typedef enum { + ImGuiSliderFlags_None = 0, + ImGuiSliderFlags_Logarithmic = 1 << 5, + ImGuiSliderFlags_NoRoundToFormat = 1 << 6, + ImGuiSliderFlags_NoInput = 1 << 7, + ImGuiSliderFlags_WrapAround = 1 << 8, + ImGuiSliderFlags_ClampOnInput = 1 << 9, + ImGuiSliderFlags_ClampZeroRange = 1 << 10, + ImGuiSliderFlags_NoSpeedTweaks = 1 << 11, + ImGuiSliderFlags_AlwaysClamp = ImGuiSliderFlags_ClampOnInput | ImGuiSliderFlags_ClampZeroRange, + ImGuiSliderFlags_InvalidMask_ = 0x7000000F, +}ImGuiSliderFlags_; +typedef enum { + ImGuiMouseButton_Left = 0, + ImGuiMouseButton_Right = 1, + ImGuiMouseButton_Middle = 2, + ImGuiMouseButton_COUNT = 5 +}ImGuiMouseButton_; +typedef enum { + ImGuiMouseCursor_None = -1, + ImGuiMouseCursor_Arrow = 0, + ImGuiMouseCursor_TextInput, + ImGuiMouseCursor_ResizeAll, + ImGuiMouseCursor_ResizeNS, + ImGuiMouseCursor_ResizeEW, + ImGuiMouseCursor_ResizeNESW, + ImGuiMouseCursor_ResizeNWSE, + ImGuiMouseCursor_Hand, + ImGuiMouseCursor_Wait, + ImGuiMouseCursor_Progress, + ImGuiMouseCursor_NotAllowed, + ImGuiMouseCursor_COUNT +}ImGuiMouseCursor_; +typedef enum { +ImGuiMouseSource_Mouse=0, +ImGuiMouseSource_TouchScreen=1, +ImGuiMouseSource_Pen=2, +ImGuiMouseSource_COUNT=3, +}ImGuiMouseSource; +typedef enum { + ImGuiCond_None = 0, + ImGuiCond_Always = 1 << 0, + ImGuiCond_Once = 1 << 1, + ImGuiCond_FirstUseEver = 1 << 2, + ImGuiCond_Appearing = 1 << 3, +}ImGuiCond_; +typedef enum { + ImGuiTableFlags_None = 0, + ImGuiTableFlags_Resizable = 1 << 0, + ImGuiTableFlags_Reorderable = 1 << 1, + ImGuiTableFlags_Hideable = 1 << 2, + ImGuiTableFlags_Sortable = 1 << 3, + ImGuiTableFlags_NoSavedSettings = 1 << 4, + ImGuiTableFlags_ContextMenuInBody = 1 << 5, + ImGuiTableFlags_RowBg = 1 << 6, + ImGuiTableFlags_BordersInnerH = 1 << 7, + ImGuiTableFlags_BordersOuterH = 1 << 8, + ImGuiTableFlags_BordersInnerV = 1 << 9, + ImGuiTableFlags_BordersOuterV = 1 << 10, + ImGuiTableFlags_BordersH = ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_BordersOuterH, + ImGuiTableFlags_BordersV = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersOuterV, + ImGuiTableFlags_BordersInner = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersInnerH, + ImGuiTableFlags_BordersOuter = ImGuiTableFlags_BordersOuterV | ImGuiTableFlags_BordersOuterH, + ImGuiTableFlags_Borders = ImGuiTableFlags_BordersInner | ImGuiTableFlags_BordersOuter, + ImGuiTableFlags_NoBordersInBody = 1 << 11, + ImGuiTableFlags_NoBordersInBodyUntilResize = 1 << 12, + ImGuiTableFlags_SizingFixedFit = 1 << 13, + ImGuiTableFlags_SizingFixedSame = 2 << 13, + ImGuiTableFlags_SizingStretchProp = 3 << 13, + ImGuiTableFlags_SizingStretchSame = 4 << 13, + ImGuiTableFlags_NoHostExtendX = 1 << 16, + ImGuiTableFlags_NoHostExtendY = 1 << 17, + ImGuiTableFlags_NoKeepColumnsVisible = 1 << 18, + ImGuiTableFlags_PreciseWidths = 1 << 19, + ImGuiTableFlags_NoClip = 1 << 20, + ImGuiTableFlags_PadOuterX = 1 << 21, + ImGuiTableFlags_NoPadOuterX = 1 << 22, + ImGuiTableFlags_NoPadInnerX = 1 << 23, + ImGuiTableFlags_ScrollX = 1 << 24, + ImGuiTableFlags_ScrollY = 1 << 25, + ImGuiTableFlags_SortMulti = 1 << 26, + ImGuiTableFlags_SortTristate = 1 << 27, + ImGuiTableFlags_HighlightHoveredColumn = 1 << 28, + ImGuiTableFlags_SizingMask_ = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_SizingFixedSame | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_SizingStretchSame, +}ImGuiTableFlags_; +typedef enum { + ImGuiTableColumnFlags_None = 0, + ImGuiTableColumnFlags_Disabled = 1 << 0, + ImGuiTableColumnFlags_DefaultHide = 1 << 1, + ImGuiTableColumnFlags_DefaultSort = 1 << 2, + ImGuiTableColumnFlags_WidthStretch = 1 << 3, + ImGuiTableColumnFlags_WidthFixed = 1 << 4, + ImGuiTableColumnFlags_NoResize = 1 << 5, + ImGuiTableColumnFlags_NoReorder = 1 << 6, + ImGuiTableColumnFlags_NoHide = 1 << 7, + ImGuiTableColumnFlags_NoClip = 1 << 8, + ImGuiTableColumnFlags_NoSort = 1 << 9, + ImGuiTableColumnFlags_NoSortAscending = 1 << 10, + ImGuiTableColumnFlags_NoSortDescending = 1 << 11, + ImGuiTableColumnFlags_NoHeaderLabel = 1 << 12, + ImGuiTableColumnFlags_NoHeaderWidth = 1 << 13, + ImGuiTableColumnFlags_PreferSortAscending = 1 << 14, + ImGuiTableColumnFlags_PreferSortDescending = 1 << 15, + ImGuiTableColumnFlags_IndentEnable = 1 << 16, + ImGuiTableColumnFlags_IndentDisable = 1 << 17, + ImGuiTableColumnFlags_AngledHeader = 1 << 18, + ImGuiTableColumnFlags_IsEnabled = 1 << 24, + ImGuiTableColumnFlags_IsVisible = 1 << 25, + ImGuiTableColumnFlags_IsSorted = 1 << 26, + ImGuiTableColumnFlags_IsHovered = 1 << 27, + ImGuiTableColumnFlags_WidthMask_ = ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_WidthFixed, + ImGuiTableColumnFlags_IndentMask_ = ImGuiTableColumnFlags_IndentEnable | ImGuiTableColumnFlags_IndentDisable, + ImGuiTableColumnFlags_StatusMask_ = ImGuiTableColumnFlags_IsEnabled | ImGuiTableColumnFlags_IsVisible | ImGuiTableColumnFlags_IsSorted | ImGuiTableColumnFlags_IsHovered, + ImGuiTableColumnFlags_NoDirectResize_ = 1 << 30, +}ImGuiTableColumnFlags_; +typedef enum { + ImGuiTableRowFlags_None = 0, + ImGuiTableRowFlags_Headers = 1 << 0, +}ImGuiTableRowFlags_; +typedef enum { + ImGuiTableBgTarget_None = 0, + ImGuiTableBgTarget_RowBg0 = 1, + ImGuiTableBgTarget_RowBg1 = 2, + ImGuiTableBgTarget_CellBg = 3, +}ImGuiTableBgTarget_; +struct ImGuiTableSortSpecs +{ + const ImGuiTableColumnSortSpecs* Specs; + int SpecsCount; + bool SpecsDirty; +}; +struct ImGuiTableColumnSortSpecs +{ + ImGuiID ColumnUserID; + ImS16 ColumnIndex; + ImS16 SortOrder; + ImGuiSortDirection SortDirection; +}; +struct ImGuiStyle +{ + float Alpha; + float DisabledAlpha; + ImVec2 WindowPadding; + float WindowRounding; + float WindowBorderSize; + float WindowBorderHoverPadding; + ImVec2 WindowMinSize; + ImVec2 WindowTitleAlign; + ImGuiDir WindowMenuButtonPosition; + float ChildRounding; + float ChildBorderSize; + float PopupRounding; + float PopupBorderSize; + ImVec2 FramePadding; + float FrameRounding; + float FrameBorderSize; + ImVec2 ItemSpacing; + ImVec2 ItemInnerSpacing; + ImVec2 CellPadding; + ImVec2 TouchExtraPadding; + float IndentSpacing; + float ColumnsMinSpacing; + float ScrollbarSize; + float ScrollbarRounding; + float GrabMinSize; + float GrabRounding; + float LogSliderDeadzone; + float ImageBorderSize; + float TabRounding; + float TabBorderSize; + float TabCloseButtonMinWidthSelected; + float TabCloseButtonMinWidthUnselected; + float TabBarBorderSize; + float TabBarOverlineSize; + float TableAngledHeadersAngle; + ImVec2 TableAngledHeadersTextAlign; + ImGuiDir ColorButtonPosition; + ImVec2 ButtonTextAlign; + ImVec2 SelectableTextAlign; + float SeparatorTextBorderSize; + ImVec2 SeparatorTextAlign; + ImVec2 SeparatorTextPadding; + ImVec2 DisplayWindowPadding; + ImVec2 DisplaySafeAreaPadding; + float DockingSeparatorSize; + float MouseCursorScale; + bool AntiAliasedLines; + bool AntiAliasedLinesUseTex; + bool AntiAliasedFill; + float CurveTessellationTol; + float CircleTessellationMaxError; + ImVec4 Colors[ImGuiCol_COUNT]; + float HoverStationaryDelay; + float HoverDelayShort; + float HoverDelayNormal; + ImGuiHoveredFlags HoverFlagsForTooltipMouse; + ImGuiHoveredFlags HoverFlagsForTooltipNav; +}; +struct ImGuiKeyData +{ + bool Down; + float DownDuration; + float DownDurationPrev; + float AnalogValue; +}; +typedef struct ImVector_ImWchar {int Size;int Capacity;ImWchar* Data;} ImVector_ImWchar; + +struct ImGuiIO +{ + ImGuiConfigFlags ConfigFlags; + ImGuiBackendFlags BackendFlags; + ImVec2 DisplaySize; + float DeltaTime; + float IniSavingRate; + const char* IniFilename; + const char* LogFilename; + void* UserData; + ImFontAtlas*Fonts; + float FontGlobalScale; + bool FontAllowUserScaling; + ImFont* FontDefault; + ImVec2 DisplayFramebufferScale; + bool ConfigNavSwapGamepadButtons; + bool ConfigNavMoveSetMousePos; + bool ConfigNavCaptureKeyboard; + bool ConfigNavEscapeClearFocusItem; + bool ConfigNavEscapeClearFocusWindow; + bool ConfigNavCursorVisibleAuto; + bool ConfigNavCursorVisibleAlways; + bool ConfigDockingNoSplit; + bool ConfigDockingWithShift; + bool ConfigDockingAlwaysTabBar; + bool ConfigDockingTransparentPayload; + bool ConfigViewportsNoAutoMerge; + bool ConfigViewportsNoTaskBarIcon; + bool ConfigViewportsNoDecoration; + bool ConfigViewportsNoDefaultParent; + bool MouseDrawCursor; + bool ConfigMacOSXBehaviors; + bool ConfigInputTrickleEventQueue; + bool ConfigInputTextCursorBlink; + bool ConfigInputTextEnterKeepActive; + bool ConfigDragClickToInputText; + bool ConfigWindowsResizeFromEdges; + bool ConfigWindowsMoveFromTitleBarOnly; + bool ConfigWindowsCopyContentsWithCtrlC; + bool ConfigScrollbarScrollByPage; + float ConfigMemoryCompactTimer; + float MouseDoubleClickTime; + float MouseDoubleClickMaxDist; + float MouseDragThreshold; + float KeyRepeatDelay; + float KeyRepeatRate; + bool ConfigErrorRecovery; + bool ConfigErrorRecoveryEnableAssert; + bool ConfigErrorRecoveryEnableDebugLog; + bool ConfigErrorRecoveryEnableTooltip; + bool ConfigDebugIsDebuggerPresent; + bool ConfigDebugHighlightIdConflicts; + bool ConfigDebugHighlightIdConflictsShowItemPicker; + bool ConfigDebugBeginReturnValueOnce; + bool ConfigDebugBeginReturnValueLoop; + bool ConfigDebugIgnoreFocusLoss; + bool ConfigDebugIniSettings; + const char* BackendPlatformName; + const char* BackendRendererName; + void* BackendPlatformUserData; + void* BackendRendererUserData; + void* BackendLanguageUserData; + bool WantCaptureMouse; + bool WantCaptureKeyboard; + bool WantTextInput; + bool WantSetMousePos; + bool WantSaveIniSettings; + bool NavActive; + bool NavVisible; + float Framerate; + int MetricsRenderVertices; + int MetricsRenderIndices; + int MetricsRenderWindows; + int MetricsActiveWindows; + ImVec2 MouseDelta; + ImGuiContext* Ctx; + ImVec2 MousePos; + bool MouseDown[5]; + float MouseWheel; + float MouseWheelH; + ImGuiMouseSource MouseSource; + ImGuiID MouseHoveredViewport; + bool KeyCtrl; + bool KeyShift; + bool KeyAlt; + bool KeySuper; + ImGuiKeyChord KeyMods; + ImGuiKeyData KeysData[ImGuiKey_NamedKey_COUNT]; + bool WantCaptureMouseUnlessPopupClose; + ImVec2 MousePosPrev; + ImVec2 MouseClickedPos[5]; + double MouseClickedTime[5]; + bool MouseClicked[5]; + bool MouseDoubleClicked[5]; + ImU16 MouseClickedCount[5]; + ImU16 MouseClickedLastCount[5]; + bool MouseReleased[5]; + double MouseReleasedTime[5]; + bool MouseDownOwned[5]; + bool MouseDownOwnedUnlessPopupClose[5]; + bool MouseWheelRequestAxisSwap; + bool MouseCtrlLeftAsRightClick; + float MouseDownDuration[5]; + float MouseDownDurationPrev[5]; + ImVec2 MouseDragMaxDistanceAbs[5]; + float MouseDragMaxDistanceSqr[5]; + float PenPressure; + bool AppFocusLost; + bool AppAcceptingEvents; + ImWchar16 InputQueueSurrogate; + ImVector_ImWchar InputQueueCharacters; +}; +struct ImGuiInputTextCallbackData +{ + ImGuiContext* Ctx; + ImGuiInputTextFlags EventFlag; + ImGuiInputTextFlags Flags; + void* UserData; + ImWchar EventChar; + ImGuiKey EventKey; + char* Buf; + int BufTextLen; + int BufSize; + bool BufDirty; + int CursorPos; + int SelectionStart; + int SelectionEnd; +}; +struct ImGuiSizeCallbackData +{ + void* UserData; + ImVec2 Pos; + ImVec2 CurrentSize; + ImVec2 DesiredSize; +}; +struct ImGuiWindowClass +{ + ImGuiID ClassId; + ImGuiID ParentViewportId; + ImGuiID FocusRouteParentWindowId; + ImGuiViewportFlags ViewportFlagsOverrideSet; + ImGuiViewportFlags ViewportFlagsOverrideClear; + ImGuiTabItemFlags TabItemFlagsOverrideSet; + ImGuiDockNodeFlags DockNodeFlagsOverrideSet; + bool DockingAlwaysTabBar; + bool DockingAllowUnclassed; +}; +struct ImGuiPayload +{ + void* Data; + int DataSize; + ImGuiID SourceId; + ImGuiID SourceParentId; + int DataFrameCount; + char DataType[32 + 1]; + bool Preview; + bool Delivery; +}; +struct ImGuiOnceUponAFrame +{ + int RefFrame; +}; +struct ImGuiTextRange +{ + const char* b; + const char* e; +}; +typedef struct ImGuiTextRange ImGuiTextRange; + +typedef struct ImVector_ImGuiTextRange {int Size;int Capacity;ImGuiTextRange* Data;} ImVector_ImGuiTextRange; + +struct ImGuiTextFilter +{ + char InputBuf[256]; + ImVector_ImGuiTextRange Filters; + int CountGrep; +}; +typedef struct ImGuiTextRange ImGuiTextRange; +typedef struct ImVector_char {int Size;int Capacity;char* Data;} ImVector_char; + +struct ImGuiTextBuffer +{ + ImVector_char Buf; +}; +struct ImGuiStoragePair +{ + ImGuiID key; + union { int val_i; float val_f; void* val_p; }; +}; +typedef struct ImVector_ImGuiStoragePair {int Size;int Capacity;ImGuiStoragePair* Data;} ImVector_ImGuiStoragePair; + +struct ImGuiStorage +{ + ImVector_ImGuiStoragePair Data; +}; +struct ImGuiListClipper +{ + ImGuiContext* Ctx; + int DisplayStart; + int DisplayEnd; + int ItemsCount; + float ItemsHeight; + float StartPosY; + double StartSeekOffsetY; + void* TempData; +}; +struct ImColor +{ + ImVec4 Value; +}; +typedef enum { + ImGuiMultiSelectFlags_None = 0, + ImGuiMultiSelectFlags_SingleSelect = 1 << 0, + ImGuiMultiSelectFlags_NoSelectAll = 1 << 1, + ImGuiMultiSelectFlags_NoRangeSelect = 1 << 2, + ImGuiMultiSelectFlags_NoAutoSelect = 1 << 3, + ImGuiMultiSelectFlags_NoAutoClear = 1 << 4, + ImGuiMultiSelectFlags_NoAutoClearOnReselect = 1 << 5, + ImGuiMultiSelectFlags_BoxSelect1d = 1 << 6, + ImGuiMultiSelectFlags_BoxSelect2d = 1 << 7, + ImGuiMultiSelectFlags_BoxSelectNoScroll = 1 << 8, + ImGuiMultiSelectFlags_ClearOnEscape = 1 << 9, + ImGuiMultiSelectFlags_ClearOnClickVoid = 1 << 10, + ImGuiMultiSelectFlags_ScopeWindow = 1 << 11, + ImGuiMultiSelectFlags_ScopeRect = 1 << 12, + ImGuiMultiSelectFlags_SelectOnClick = 1 << 13, + ImGuiMultiSelectFlags_SelectOnClickRelease = 1 << 14, + ImGuiMultiSelectFlags_NavWrapX = 1 << 16, +}ImGuiMultiSelectFlags_; +typedef struct ImVector_ImGuiSelectionRequest {int Size;int Capacity;ImGuiSelectionRequest* Data;} ImVector_ImGuiSelectionRequest; + +struct ImGuiMultiSelectIO +{ + ImVector_ImGuiSelectionRequest Requests; + ImGuiSelectionUserData RangeSrcItem; + ImGuiSelectionUserData NavIdItem; + bool NavIdSelected; + bool RangeSrcReset; + int ItemsCount; +}; +typedef enum { + ImGuiSelectionRequestType_None = 0, + ImGuiSelectionRequestType_SetAll, + ImGuiSelectionRequestType_SetRange, +}ImGuiSelectionRequestType; +struct ImGuiSelectionRequest +{ + ImGuiSelectionRequestType Type; + bool Selected; + ImS8 RangeDirection; + ImGuiSelectionUserData RangeFirstItem; + ImGuiSelectionUserData RangeLastItem; +}; +struct ImGuiSelectionBasicStorage +{ + int Size; + bool PreserveOrder; + void* UserData; + ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); + int _SelectionOrder; + ImGuiStorage _Storage; +}; +struct ImGuiSelectionExternalStorage +{ + void* UserData; + void (*AdapterSetItemSelected)(ImGuiSelectionExternalStorage* self, int idx, bool selected); +}; +typedef unsigned short ImDrawIdx; +typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); +struct ImDrawCmd +{ + ImVec4 ClipRect; + ImTextureID TextureId; + unsigned int VtxOffset; + unsigned int IdxOffset; + unsigned int ElemCount; + ImDrawCallback UserCallback; + void* UserCallbackData; + int UserCallbackDataSize; + int UserCallbackDataOffset; +}; +struct ImDrawVert +{ + ImVec2 pos; + ImVec2 uv; + ImU32 col; +}; +typedef struct ImDrawCmdHeader ImDrawCmdHeader; +struct ImDrawCmdHeader +{ + ImVec4 ClipRect; + ImTextureID TextureId; + unsigned int VtxOffset; +}; +typedef struct ImVector_ImDrawCmd {int Size;int Capacity;ImDrawCmd* Data;} ImVector_ImDrawCmd; + +typedef struct ImVector_ImDrawIdx {int Size;int Capacity;ImDrawIdx* Data;} ImVector_ImDrawIdx; + +struct ImDrawChannel +{ + ImVector_ImDrawCmd _CmdBuffer; + ImVector_ImDrawIdx _IdxBuffer; +}; +typedef struct ImVector_ImDrawChannel {int Size;int Capacity;ImDrawChannel* Data;} ImVector_ImDrawChannel; + +struct ImDrawListSplitter +{ + int _Current; + int _Count; + ImVector_ImDrawChannel _Channels; +}; +typedef enum { + ImDrawFlags_None = 0, + ImDrawFlags_Closed = 1 << 0, + ImDrawFlags_RoundCornersTopLeft = 1 << 4, + ImDrawFlags_RoundCornersTopRight = 1 << 5, + ImDrawFlags_RoundCornersBottomLeft = 1 << 6, + ImDrawFlags_RoundCornersBottomRight = 1 << 7, + ImDrawFlags_RoundCornersNone = 1 << 8, + ImDrawFlags_RoundCornersTop = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight, + ImDrawFlags_RoundCornersBottom = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, + ImDrawFlags_RoundCornersLeft = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersTopLeft, + ImDrawFlags_RoundCornersRight = ImDrawFlags_RoundCornersBottomRight | ImDrawFlags_RoundCornersTopRight, + ImDrawFlags_RoundCornersAll = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight | ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, + ImDrawFlags_RoundCornersDefault_ = ImDrawFlags_RoundCornersAll, + ImDrawFlags_RoundCornersMask_ = ImDrawFlags_RoundCornersAll | ImDrawFlags_RoundCornersNone, +}ImDrawFlags_; +typedef enum { + ImDrawListFlags_None = 0, + ImDrawListFlags_AntiAliasedLines = 1 << 0, + ImDrawListFlags_AntiAliasedLinesUseTex = 1 << 1, + ImDrawListFlags_AntiAliasedFill = 1 << 2, + ImDrawListFlags_AllowVtxOffset = 1 << 3, +}ImDrawListFlags_; +typedef struct ImVector_ImDrawVert {int Size;int Capacity;ImDrawVert* Data;} ImVector_ImDrawVert; + +typedef struct ImVector_ImVec2 {int Size;int Capacity;ImVec2* Data;} ImVector_ImVec2; + +typedef struct ImVector_ImVec4 {int Size;int Capacity;ImVec4* Data;} ImVector_ImVec4; + +typedef struct ImVector_ImTextureID {int Size;int Capacity;ImTextureID* Data;} ImVector_ImTextureID; + +typedef struct ImVector_ImU8 {int Size;int Capacity;ImU8* Data;} ImVector_ImU8; + +struct ImDrawList +{ + ImVector_ImDrawCmd CmdBuffer; + ImVector_ImDrawIdx IdxBuffer; + ImVector_ImDrawVert VtxBuffer; + ImDrawListFlags Flags; + unsigned int _VtxCurrentIdx; + ImDrawListSharedData* _Data; + ImDrawVert* _VtxWritePtr; + ImDrawIdx* _IdxWritePtr; + ImVector_ImVec2 _Path; + ImDrawCmdHeader _CmdHeader; + ImDrawListSplitter _Splitter; + ImVector_ImVec4 _ClipRectStack; + ImVector_ImTextureID _TextureIdStack; + ImVector_ImU8 _CallbacksDataBuf; + float _FringeScale; + const char* _OwnerName; +}; +typedef struct ImVector_ImDrawListPtr {int Size;int Capacity;ImDrawList** Data;} ImVector_ImDrawListPtr; + +struct ImDrawData +{ + bool Valid; + int CmdListsCount; + int TotalIdxCount; + int TotalVtxCount; + ImVector_ImDrawListPtr CmdLists; + ImVec2 DisplayPos; + ImVec2 DisplaySize; + ImVec2 FramebufferScale; + ImGuiViewport* OwnerViewport; +}; +struct ImFontConfig +{ + void* FontData; + int FontDataSize; + bool FontDataOwnedByAtlas; + bool MergeMode; + bool PixelSnapH; + int FontNo; + int OversampleH; + int OversampleV; + float SizePixels; + ImVec2 GlyphOffset; + const ImWchar* GlyphRanges; + float GlyphMinAdvanceX; + float GlyphMaxAdvanceX; + float GlyphExtraAdvanceX; + unsigned int FontBuilderFlags; + float RasterizerMultiply; + float RasterizerDensity; + ImWchar EllipsisChar; + char Name[40]; + ImFont* DstFont; +}; +struct ImFontGlyph +{ + unsigned int Colored : 1; + unsigned int Visible : 1; + unsigned int Codepoint : 30; + float AdvanceX; + float X0, Y0, X1, Y1; + float U0, V0, U1, V1; +}; +typedef struct ImVector_ImU32 {int Size;int Capacity;ImU32* Data;} ImVector_ImU32; + +struct ImFontGlyphRangesBuilder +{ + ImVector_ImU32 UsedChars; +}; +typedef struct ImFontAtlasCustomRect ImFontAtlasCustomRect; +struct ImFontAtlasCustomRect +{ + unsigned short X, Y; + unsigned short Width, Height; + unsigned int GlyphID : 31; + unsigned int GlyphColored : 1; + float GlyphAdvanceX; + ImVec2 GlyphOffset; + ImFont* Font; +}; +typedef enum { + ImFontAtlasFlags_None = 0, + ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, + ImFontAtlasFlags_NoMouseCursors = 1 << 1, + ImFontAtlasFlags_NoBakedLines = 1 << 2, +}ImFontAtlasFlags_; +typedef struct ImVector_ImFontPtr {int Size;int Capacity;ImFont** Data;} ImVector_ImFontPtr; + +typedef struct ImVector_ImFontAtlasCustomRect {int Size;int Capacity;ImFontAtlasCustomRect* Data;} ImVector_ImFontAtlasCustomRect; + +typedef struct ImVector_ImFontConfig {int Size;int Capacity;ImFontConfig* Data;} ImVector_ImFontConfig; + +struct ImFontAtlas +{ + ImFontAtlasFlags Flags; + ImTextureID TexID; + int TexDesiredWidth; + int TexGlyphPadding; + void* UserData; + bool Locked; + bool TexReady; + bool TexPixelsUseColors; + unsigned char* TexPixelsAlpha8; + unsigned int* TexPixelsRGBA32; + int TexWidth; + int TexHeight; + ImVec2 TexUvScale; + ImVec2 TexUvWhitePixel; + ImVector_ImFontPtr Fonts; + ImVector_ImFontAtlasCustomRect CustomRects; + ImVector_ImFontConfig Sources; + ImVec4 TexUvLines[(32) + 1]; + const ImFontBuilderIO* FontBuilderIO; + unsigned int FontBuilderFlags; + int PackIdMouseCursors; + int PackIdLines; +}; +typedef struct ImVector_float {int Size;int Capacity;float* Data;} ImVector_float; + +typedef struct ImVector_ImU16 {int Size;int Capacity;ImU16* Data;} ImVector_ImU16; + +typedef struct ImVector_ImFontGlyph {int Size;int Capacity;ImFontGlyph* Data;} ImVector_ImFontGlyph; + +struct ImFont +{ + ImVector_float IndexAdvanceX; + float FallbackAdvanceX; + float FontSize; + ImVector_ImU16 IndexLookup; + ImVector_ImFontGlyph Glyphs; + ImFontGlyph* FallbackGlyph; + ImFontAtlas* ContainerAtlas; + ImFontConfig* Sources; + short SourcesCount; + short EllipsisCharCount; + ImWchar EllipsisChar; + ImWchar FallbackChar; + float EllipsisWidth; + float EllipsisCharStep; + float Scale; + float Ascent, Descent; + int MetricsTotalSurface; + bool DirtyLookupTables; + ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX +1)/8192/8]; +}; +typedef enum { + ImGuiViewportFlags_None = 0, + ImGuiViewportFlags_IsPlatformWindow = 1 << 0, + ImGuiViewportFlags_IsPlatformMonitor = 1 << 1, + ImGuiViewportFlags_OwnedByApp = 1 << 2, + ImGuiViewportFlags_NoDecoration = 1 << 3, + ImGuiViewportFlags_NoTaskBarIcon = 1 << 4, + ImGuiViewportFlags_NoFocusOnAppearing = 1 << 5, + ImGuiViewportFlags_NoFocusOnClick = 1 << 6, + ImGuiViewportFlags_NoInputs = 1 << 7, + ImGuiViewportFlags_NoRendererClear = 1 << 8, + ImGuiViewportFlags_NoAutoMerge = 1 << 9, + ImGuiViewportFlags_TopMost = 1 << 10, + ImGuiViewportFlags_CanHostOtherWindows = 1 << 11, + ImGuiViewportFlags_IsMinimized = 1 << 12, + ImGuiViewportFlags_IsFocused = 1 << 13, +}ImGuiViewportFlags_; +struct ImGuiViewport +{ + ImGuiID ID; + ImGuiViewportFlags Flags; + ImVec2 Pos; + ImVec2 Size; + ImVec2 WorkPos; + ImVec2 WorkSize; + float DpiScale; + ImGuiID ParentViewportId; + ImDrawData* DrawData; + void* RendererUserData; + void* PlatformUserData; + void* PlatformHandle; + void* PlatformHandleRaw; + bool PlatformWindowCreated; + bool PlatformRequestMove; + bool PlatformRequestResize; + bool PlatformRequestClose; +}; +typedef struct ImVector_ImGuiPlatformMonitor {int Size;int Capacity;ImGuiPlatformMonitor* Data;} ImVector_ImGuiPlatformMonitor; + +typedef struct ImVector_ImGuiViewportPtr {int Size;int Capacity;ImGuiViewport** Data;} ImVector_ImGuiViewportPtr; + +struct ImGuiPlatformIO +{ + const char* (*Platform_GetClipboardTextFn)(ImGuiContext* ctx); + void (*Platform_SetClipboardTextFn)(ImGuiContext* ctx, const char* text); + void* Platform_ClipboardUserData; + bool (*Platform_OpenInShellFn)(ImGuiContext* ctx, const char* path); + void* Platform_OpenInShellUserData; + void (*Platform_SetImeDataFn)(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); + void* Platform_ImeUserData; + ImWchar Platform_LocaleDecimalPoint; + void* Renderer_RenderState; + void (*Platform_CreateWindow)(ImGuiViewport* vp); + void (*Platform_DestroyWindow)(ImGuiViewport* vp); + void (*Platform_ShowWindow)(ImGuiViewport* vp); + void (*Platform_SetWindowPos)(ImGuiViewport* vp, ImVec2 pos); + ImVec2 (*Platform_GetWindowPos)(ImGuiViewport* vp); + void (*Platform_SetWindowSize)(ImGuiViewport* vp, ImVec2 size); + ImVec2 (*Platform_GetWindowSize)(ImGuiViewport* vp); + void (*Platform_SetWindowFocus)(ImGuiViewport* vp); + bool (*Platform_GetWindowFocus)(ImGuiViewport* vp); + bool (*Platform_GetWindowMinimized)(ImGuiViewport* vp); + void (*Platform_SetWindowTitle)(ImGuiViewport* vp, const char* str); + void (*Platform_SetWindowAlpha)(ImGuiViewport* vp, float alpha); + void (*Platform_UpdateWindow)(ImGuiViewport* vp); + void (*Platform_RenderWindow)(ImGuiViewport* vp, void* render_arg); + void (*Platform_SwapBuffers)(ImGuiViewport* vp, void* render_arg); + float (*Platform_GetWindowDpiScale)(ImGuiViewport* vp); + void (*Platform_OnChangedViewport)(ImGuiViewport* vp); + ImVec4 (*Platform_GetWindowWorkAreaInsets)(ImGuiViewport* vp); + int (*Platform_CreateVkSurface)(ImGuiViewport* vp, ImU64 vk_inst, const void* vk_allocators, ImU64* out_vk_surface); + void (*Renderer_CreateWindow)(ImGuiViewport* vp); + void (*Renderer_DestroyWindow)(ImGuiViewport* vp); + void (*Renderer_SetWindowSize)(ImGuiViewport* vp, ImVec2 size); + void (*Renderer_RenderWindow)(ImGuiViewport* vp, void* render_arg); + void (*Renderer_SwapBuffers)(ImGuiViewport* vp, void* render_arg); + ImVector_ImGuiPlatformMonitor Monitors; + ImVector_ImGuiViewportPtr Viewports; +}; +struct ImGuiPlatformMonitor +{ + ImVec2 MainPos, MainSize; + ImVec2 WorkPos, WorkSize; + float DpiScale; + void* PlatformHandle; +}; +struct ImGuiPlatformImeData +{ + bool WantVisible; + ImVec2 InputPos; + float InputLineHeight; +}; +struct ImBitVector; +struct ImRect; +struct ImGuiTextIndex; +struct ImDrawDataBuilder; +struct ImDrawListSharedData; +struct ImGuiBoxSelectState; +struct ImGuiColorMod; +struct ImGuiContext; +struct ImGuiContextHook; +struct ImGuiDataTypeInfo; +struct ImGuiDeactivatedItemData; +struct ImGuiDockContext; +struct ImGuiDockRequest; +struct ImGuiDockNode; +struct ImGuiDockNodeSettings; +struct ImGuiErrorRecoveryState; +struct ImGuiGroupData; +struct ImGuiInputTextState; +struct ImGuiInputTextDeactivateData; +struct ImGuiLastItemData; +struct ImGuiLocEntry; +struct ImGuiMenuColumns; +struct ImGuiMultiSelectState; +struct ImGuiMultiSelectTempData; +struct ImGuiNavItemData; +struct ImGuiMetricsConfig; +struct ImGuiNextWindowData; +struct ImGuiNextItemData; +struct ImGuiOldColumnData; +struct ImGuiOldColumns; +struct ImGuiPopupData; +struct ImGuiSettingsHandler; +struct ImGuiStyleMod; +struct ImGuiStyleVarInfo; +struct ImGuiTabBar; +struct ImGuiTabItem; +struct ImGuiTable; +struct ImGuiTableHeaderData; +struct ImGuiTableColumn; +struct ImGuiTableInstanceData; +struct ImGuiTableTempData; +struct ImGuiTableSettings; +struct ImGuiTableColumnsSettings; +struct ImGuiTreeNodeStackData; +struct ImGuiTypingSelectState; +struct ImGuiTypingSelectRequest; +struct ImGuiWindow; +struct ImGuiWindowDockStyle; +struct ImGuiWindowTempData; +struct ImGuiWindowSettings; +typedef int ImGuiDataAuthority; +typedef int ImGuiLayoutType; +typedef int ImGuiActivateFlags; +typedef int ImGuiDebugLogFlags; +typedef int ImGuiFocusRequestFlags; +typedef int ImGuiItemStatusFlags; +typedef int ImGuiOldColumnFlags; +typedef int ImGuiLogFlags; +typedef int ImGuiNavRenderCursorFlags; +typedef int ImGuiNavMoveFlags; +typedef int ImGuiNextItemDataFlags; +typedef int ImGuiNextWindowDataFlags; +typedef int ImGuiScrollFlags; +typedef int ImGuiSeparatorFlags; +typedef int ImGuiTextFlags; +typedef int ImGuiTooltipFlags; +typedef int ImGuiTypingSelectFlags; +typedef int ImGuiWindowRefreshFlags; +extern ImGuiContext* GImGui; +typedef FILE* ImFileHandle; +typedef struct ImVec1 ImVec1; +struct ImVec1 +{ + float x; +}; +typedef struct ImVec2ih ImVec2ih; +struct ImVec2ih +{ + short x, y; +}; +struct ImRect +{ + ImVec2 Min; + ImVec2 Max; +}; +typedef ImU32* ImBitArrayPtr; +struct ImBitVector +{ + ImVector_ImU32 Storage; +}; +typedef int ImPoolIdx; +typedef struct ImVector_int {int Size;int Capacity;int* Data;} ImVector_int; + +struct ImGuiTextIndex +{ + ImVector_int LineOffsets; + int EndOffset; +}; +struct ImDrawListSharedData +{ + ImVec2 TexUvWhitePixel; + const ImVec4* TexUvLines; + ImFont* Font; + float FontSize; + float FontScale; + float CurveTessellationTol; + float CircleSegmentMaxError; + float InitialFringeScale; + ImDrawListFlags InitialFlags; + ImVec4 ClipRectFullscreen; + ImVector_ImVec2 TempBuffer; + ImVec2 ArcFastVtx[48]; + float ArcFastRadiusCutoff; + ImU8 CircleSegmentCounts[64]; +}; +struct ImDrawDataBuilder +{ + ImVector_ImDrawListPtr* Layers[2]; + ImVector_ImDrawListPtr LayerData1; +}; +struct ImGuiStyleVarInfo +{ + ImU32 Count : 8; + ImGuiDataType DataType : 8; + ImU32 Offset : 16; +}; +struct ImGuiColorMod +{ + ImGuiCol Col; + ImVec4 BackupValue; +}; +struct ImGuiStyleMod +{ + ImGuiStyleVar VarIdx; + union { int BackupInt[2]; float BackupFloat[2]; }; +}; +typedef struct ImGuiDataTypeStorage ImGuiDataTypeStorage; +struct ImGuiDataTypeStorage +{ + ImU8 Data[8]; +}; +struct ImGuiDataTypeInfo +{ + size_t Size; + const char* Name; + const char* PrintFmt; + const char* ScanFmt; +}; +typedef enum { + ImGuiDataType_Pointer = ImGuiDataType_COUNT, + ImGuiDataType_ID, +}ImGuiDataTypePrivate_; +typedef enum { + ImGuiItemFlags_Disabled = 1 << 10, + ImGuiItemFlags_ReadOnly = 1 << 11, + ImGuiItemFlags_MixedValue = 1 << 12, + ImGuiItemFlags_NoWindowHoverableCheck = 1 << 13, + ImGuiItemFlags_AllowOverlap = 1 << 14, + ImGuiItemFlags_NoNavDisableMouseHover = 1 << 15, + ImGuiItemFlags_NoMarkEdited = 1 << 16, + ImGuiItemFlags_Inputable = 1 << 20, + ImGuiItemFlags_HasSelectionUserData = 1 << 21, + ImGuiItemFlags_IsMultiSelect = 1 << 22, + ImGuiItemFlags_Default_ = ImGuiItemFlags_AutoClosePopups, +}ImGuiItemFlagsPrivate_; +typedef enum { + ImGuiItemStatusFlags_None = 0, + ImGuiItemStatusFlags_HoveredRect = 1 << 0, + ImGuiItemStatusFlags_HasDisplayRect = 1 << 1, + ImGuiItemStatusFlags_Edited = 1 << 2, + ImGuiItemStatusFlags_ToggledSelection = 1 << 3, + ImGuiItemStatusFlags_ToggledOpen = 1 << 4, + ImGuiItemStatusFlags_HasDeactivated = 1 << 5, + ImGuiItemStatusFlags_Deactivated = 1 << 6, + ImGuiItemStatusFlags_HoveredWindow = 1 << 7, + ImGuiItemStatusFlags_Visible = 1 << 8, + ImGuiItemStatusFlags_HasClipRect = 1 << 9, + ImGuiItemStatusFlags_HasShortcut = 1 << 10, +}ImGuiItemStatusFlags_; +typedef enum { + ImGuiHoveredFlags_DelayMask_ = ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_NoSharedDelay, + ImGuiHoveredFlags_AllowedMaskForIsWindowHovered = ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy | ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_Stationary, + ImGuiHoveredFlags_AllowedMaskForIsItemHovered = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped | ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_NoNavOverride | ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayMask_, +}ImGuiHoveredFlagsPrivate_; +typedef enum { + ImGuiInputTextFlags_Multiline = 1 << 26, + ImGuiInputTextFlags_MergedItem = 1 << 27, + ImGuiInputTextFlags_LocalizeDecimalPoint= 1 << 28, +}ImGuiInputTextFlagsPrivate_; +typedef enum { + ImGuiButtonFlags_PressedOnClick = 1 << 4, + ImGuiButtonFlags_PressedOnClickRelease = 1 << 5, + ImGuiButtonFlags_PressedOnClickReleaseAnywhere = 1 << 6, + ImGuiButtonFlags_PressedOnRelease = 1 << 7, + ImGuiButtonFlags_PressedOnDoubleClick = 1 << 8, + ImGuiButtonFlags_PressedOnDragDropHold = 1 << 9, + ImGuiButtonFlags_FlattenChildren = 1 << 11, + ImGuiButtonFlags_AllowOverlap = 1 << 12, + ImGuiButtonFlags_AlignTextBaseLine = 1 << 15, + ImGuiButtonFlags_NoKeyModsAllowed = 1 << 16, + ImGuiButtonFlags_NoHoldingActiveId = 1 << 17, + ImGuiButtonFlags_NoNavFocus = 1 << 18, + ImGuiButtonFlags_NoHoveredOnFocus = 1 << 19, + ImGuiButtonFlags_NoSetKeyOwner = 1 << 20, + ImGuiButtonFlags_NoTestKeyOwner = 1 << 21, + ImGuiButtonFlags_PressedOnMask_ = ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_PressedOnDragDropHold, + ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease, +}ImGuiButtonFlagsPrivate_; +typedef enum { + ImGuiComboFlags_CustomPreview = 1 << 20, +}ImGuiComboFlagsPrivate_; +typedef enum { + ImGuiSliderFlags_Vertical = 1 << 20, + ImGuiSliderFlags_ReadOnly = 1 << 21, +}ImGuiSliderFlagsPrivate_; +typedef enum { + ImGuiSelectableFlags_NoHoldingActiveID = 1 << 20, + ImGuiSelectableFlags_SelectOnNav = 1 << 21, + ImGuiSelectableFlags_SelectOnClick = 1 << 22, + ImGuiSelectableFlags_SelectOnRelease = 1 << 23, + ImGuiSelectableFlags_SpanAvailWidth = 1 << 24, + ImGuiSelectableFlags_SetNavIdOnHover = 1 << 25, + ImGuiSelectableFlags_NoPadWithHalfSpacing = 1 << 26, + ImGuiSelectableFlags_NoSetKeyOwner = 1 << 27, +}ImGuiSelectableFlagsPrivate_; +typedef enum { + ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 28, + ImGuiTreeNodeFlags_UpsideDownArrow = 1 << 29, + ImGuiTreeNodeFlags_OpenOnMask_ = ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_OpenOnArrow, +}ImGuiTreeNodeFlagsPrivate_; +typedef enum { + ImGuiSeparatorFlags_None = 0, + ImGuiSeparatorFlags_Horizontal = 1 << 0, + ImGuiSeparatorFlags_Vertical = 1 << 1, + ImGuiSeparatorFlags_SpanAllColumns = 1 << 2, +}ImGuiSeparatorFlags_; +typedef enum { + ImGuiFocusRequestFlags_None = 0, + ImGuiFocusRequestFlags_RestoreFocusedChild = 1 << 0, + ImGuiFocusRequestFlags_UnlessBelowModal = 1 << 1, +}ImGuiFocusRequestFlags_; +typedef enum { + ImGuiTextFlags_None = 0, + ImGuiTextFlags_NoWidthForLargeClippedText = 1 << 0, +}ImGuiTextFlags_; +typedef enum { + ImGuiTooltipFlags_None = 0, + ImGuiTooltipFlags_OverridePrevious = 1 << 1, +}ImGuiTooltipFlags_; +typedef enum { + ImGuiLayoutType_Horizontal = 0, + ImGuiLayoutType_Vertical = 1 +}ImGuiLayoutType_; +typedef enum { + ImGuiLogFlags_None = 0, + ImGuiLogFlags_OutputTTY = 1 << 0, + ImGuiLogFlags_OutputFile = 1 << 1, + ImGuiLogFlags_OutputBuffer = 1 << 2, + ImGuiLogFlags_OutputClipboard = 1 << 3, + ImGuiLogFlags_OutputMask_ = ImGuiLogFlags_OutputTTY | ImGuiLogFlags_OutputFile | ImGuiLogFlags_OutputBuffer | ImGuiLogFlags_OutputClipboard, +}ImGuiLogFlags_; +typedef enum { + ImGuiAxis_None = -1, + ImGuiAxis_X = 0, + ImGuiAxis_Y = 1 +}ImGuiAxis; +typedef enum { + ImGuiPlotType_Lines, + ImGuiPlotType_Histogram, +}ImGuiPlotType; +typedef struct ImGuiComboPreviewData ImGuiComboPreviewData; +struct ImGuiComboPreviewData +{ + ImRect PreviewRect; + ImVec2 BackupCursorPos; + ImVec2 BackupCursorMaxPos; + ImVec2 BackupCursorPosPrevLine; + float BackupPrevLineTextBaseOffset; + ImGuiLayoutType BackupLayout; +}; +struct ImGuiGroupData +{ + ImGuiID WindowID; + ImVec2 BackupCursorPos; + ImVec2 BackupCursorMaxPos; + ImVec2 BackupCursorPosPrevLine; + ImVec1 BackupIndent; + ImVec1 BackupGroupOffset; + ImVec2 BackupCurrLineSize; + float BackupCurrLineTextBaseOffset; + ImGuiID BackupActiveIdIsAlive; + bool BackupDeactivatedIdIsAlive; + bool BackupHoveredIdIsAlive; + bool BackupIsSameLine; + bool EmitItem; +}; +struct ImGuiMenuColumns +{ + ImU32 TotalWidth; + ImU32 NextTotalWidth; + ImU16 Spacing; + ImU16 OffsetIcon; + ImU16 OffsetLabel; + ImU16 OffsetShortcut; + ImU16 OffsetMark; + ImU16 Widths[4]; +}; +typedef struct ImGuiInputTextDeactivatedState ImGuiInputTextDeactivatedState; +struct ImGuiInputTextDeactivatedState +{ + ImGuiID ID; + ImVector_char TextA; +}; struct STB_TexteditState; +typedef STB_TexteditState ImStbTexteditState; +struct ImGuiInputTextState +{ + ImGuiContext* Ctx; + ImStbTexteditState* Stb; + ImGuiInputTextFlags Flags; + ImGuiID ID; + int TextLen; + const char* TextSrc; + ImVector_char TextA; + ImVector_char TextToRevertTo; + ImVector_char CallbackTextBackup; + int BufCapacity; + ImVec2 Scroll; + float CursorAnim; + bool CursorFollow; + bool SelectedAllMouseLock; + bool Edited; + bool WantReloadUserBuf; + int ReloadSelectionStart; + int ReloadSelectionEnd; +}; +typedef enum { + ImGuiWindowRefreshFlags_None = 0, + ImGuiWindowRefreshFlags_TryToAvoidRefresh = 1 << 0, + ImGuiWindowRefreshFlags_RefreshOnHover = 1 << 1, + ImGuiWindowRefreshFlags_RefreshOnFocus = 1 << 2, +}ImGuiWindowRefreshFlags_; +typedef enum { + ImGuiNextWindowDataFlags_None = 0, + ImGuiNextWindowDataFlags_HasPos = 1 << 0, + ImGuiNextWindowDataFlags_HasSize = 1 << 1, + ImGuiNextWindowDataFlags_HasContentSize = 1 << 2, + ImGuiNextWindowDataFlags_HasCollapsed = 1 << 3, + ImGuiNextWindowDataFlags_HasSizeConstraint = 1 << 4, + ImGuiNextWindowDataFlags_HasFocus = 1 << 5, + ImGuiNextWindowDataFlags_HasBgAlpha = 1 << 6, + ImGuiNextWindowDataFlags_HasScroll = 1 << 7, + ImGuiNextWindowDataFlags_HasWindowFlags = 1 << 8, + ImGuiNextWindowDataFlags_HasChildFlags = 1 << 9, + ImGuiNextWindowDataFlags_HasRefreshPolicy = 1 << 10, + ImGuiNextWindowDataFlags_HasViewport = 1 << 11, + ImGuiNextWindowDataFlags_HasDock = 1 << 12, + ImGuiNextWindowDataFlags_HasWindowClass = 1 << 13, +}ImGuiNextWindowDataFlags_; +struct ImGuiNextWindowData +{ + ImGuiNextWindowDataFlags HasFlags; + ImGuiCond PosCond; + ImGuiCond SizeCond; + ImGuiCond CollapsedCond; + ImGuiCond DockCond; + ImVec2 PosVal; + ImVec2 PosPivotVal; + ImVec2 SizeVal; + ImVec2 ContentSizeVal; + ImVec2 ScrollVal; + ImGuiWindowFlags WindowFlags; + ImGuiChildFlags ChildFlags; + bool PosUndock; + bool CollapsedVal; + ImRect SizeConstraintRect; + ImGuiSizeCallback SizeCallback; + void* SizeCallbackUserData; + float BgAlphaVal; + ImGuiID ViewportId; + ImGuiID DockId; + ImGuiWindowClass WindowClass; + ImVec2 MenuBarOffsetMinVal; + ImGuiWindowRefreshFlags RefreshFlagsVal; +}; +typedef enum { + ImGuiNextItemDataFlags_None = 0, + ImGuiNextItemDataFlags_HasWidth = 1 << 0, + ImGuiNextItemDataFlags_HasOpen = 1 << 1, + ImGuiNextItemDataFlags_HasShortcut = 1 << 2, + ImGuiNextItemDataFlags_HasRefVal = 1 << 3, + ImGuiNextItemDataFlags_HasStorageID = 1 << 4, +}ImGuiNextItemDataFlags_; +struct ImGuiNextItemData +{ + ImGuiNextItemDataFlags HasFlags; + ImGuiItemFlags ItemFlags; + ImGuiID FocusScopeId; + ImGuiSelectionUserData SelectionUserData; + float Width; + ImGuiKeyChord Shortcut; + ImGuiInputFlags ShortcutFlags; + bool OpenVal; + ImU8 OpenCond; + ImGuiDataTypeStorage RefVal; + ImGuiID StorageId; +}; +struct ImGuiLastItemData +{ + ImGuiID ID; + ImGuiItemFlags ItemFlags; + ImGuiItemStatusFlags StatusFlags; + ImRect Rect; + ImRect NavRect; + ImRect DisplayRect; + ImRect ClipRect; + ImGuiKeyChord Shortcut; +}; +struct ImGuiTreeNodeStackData +{ + ImGuiID ID; + ImGuiTreeNodeFlags TreeFlags; + ImGuiItemFlags ItemFlags; + ImRect NavRect; +}; +struct ImGuiErrorRecoveryState +{ + short SizeOfWindowStack; + short SizeOfIDStack; + short SizeOfTreeStack; + short SizeOfColorStack; + short SizeOfStyleVarStack; + short SizeOfFontStack; + short SizeOfFocusScopeStack; + short SizeOfGroupStack; + short SizeOfItemFlagsStack; + short SizeOfBeginPopupStack; + short SizeOfDisabledStack; +}; +typedef struct ImGuiWindowStackData ImGuiWindowStackData; +struct ImGuiWindowStackData +{ + ImGuiWindow* Window; + ImGuiLastItemData ParentLastItemDataBackup; + ImGuiErrorRecoveryState StackSizesInBegin; + bool DisabledOverrideReenable; + float DisabledOverrideReenableAlphaBackup; +}; +typedef struct ImGuiShrinkWidthItem ImGuiShrinkWidthItem; +struct ImGuiShrinkWidthItem +{ + int Index; + float Width; + float InitialWidth; +}; +typedef struct ImGuiPtrOrIndex ImGuiPtrOrIndex; +struct ImGuiPtrOrIndex +{ + void* Ptr; + int Index; +}; +struct ImGuiDeactivatedItemData +{ + ImGuiID ID; + int ElapseFrame; + bool HasBeenEditedBefore; + bool IsAlive; +}; +typedef enum { + ImGuiPopupPositionPolicy_Default, + ImGuiPopupPositionPolicy_ComboBox, + ImGuiPopupPositionPolicy_Tooltip, +}ImGuiPopupPositionPolicy; +struct ImGuiPopupData +{ + ImGuiID PopupId; + ImGuiWindow* Window; + ImGuiWindow* RestoreNavWindow; + int ParentNavLayer; + int OpenFrameCount; + ImGuiID OpenParentId; + ImVec2 OpenPopupPos; + ImVec2 OpenMousePos; +}; +typedef struct ImBitArray_ImGuiKey_NamedKey_COUNT__lessImGuiKey_NamedKey_BEGIN {ImU32 Storage[(ImGuiKey_NamedKey_COUNT+31)>>5];} ImBitArray_ImGuiKey_NamedKey_COUNT__lessImGuiKey_NamedKey_BEGIN; + +typedef ImBitArray_ImGuiKey_NamedKey_COUNT__lessImGuiKey_NamedKey_BEGIN ImBitArrayForNamedKeys; +typedef enum { + ImGuiInputEventType_None = 0, + ImGuiInputEventType_MousePos, + ImGuiInputEventType_MouseWheel, + ImGuiInputEventType_MouseButton, + ImGuiInputEventType_MouseViewport, + ImGuiInputEventType_Key, + ImGuiInputEventType_Text, + ImGuiInputEventType_Focus, + ImGuiInputEventType_COUNT +}ImGuiInputEventType; +typedef enum { + ImGuiInputSource_None = 0, + ImGuiInputSource_Mouse, + ImGuiInputSource_Keyboard, + ImGuiInputSource_Gamepad, + ImGuiInputSource_COUNT +}ImGuiInputSource; +typedef struct ImGuiInputEventMousePos ImGuiInputEventMousePos; +struct ImGuiInputEventMousePos +{ float PosX, PosY; ImGuiMouseSource MouseSource; +}; +typedef struct ImGuiInputEventMouseWheel ImGuiInputEventMouseWheel; +struct ImGuiInputEventMouseWheel +{ float WheelX, WheelY; ImGuiMouseSource MouseSource; +}; +typedef struct ImGuiInputEventMouseButton ImGuiInputEventMouseButton; +struct ImGuiInputEventMouseButton +{ int Button; bool Down; ImGuiMouseSource MouseSource; +}; +typedef struct ImGuiInputEventMouseViewport ImGuiInputEventMouseViewport; +struct ImGuiInputEventMouseViewport +{ ImGuiID HoveredViewportID; +}; +typedef struct ImGuiInputEventKey ImGuiInputEventKey; +struct ImGuiInputEventKey +{ ImGuiKey Key; bool Down; float AnalogValue; +}; +typedef struct ImGuiInputEventText ImGuiInputEventText; +struct ImGuiInputEventText +{ unsigned int Char; +}; +typedef struct ImGuiInputEventAppFocused ImGuiInputEventAppFocused; +struct ImGuiInputEventAppFocused +{ bool Focused; +}; +typedef struct ImGuiInputEvent ImGuiInputEvent; +struct ImGuiInputEvent +{ + ImGuiInputEventType Type; + ImGuiInputSource Source; + ImU32 EventId; + union + { + ImGuiInputEventMousePos MousePos; + ImGuiInputEventMouseWheel MouseWheel; + ImGuiInputEventMouseButton MouseButton; + ImGuiInputEventMouseViewport MouseViewport; + ImGuiInputEventKey Key; + ImGuiInputEventText Text; + ImGuiInputEventAppFocused AppFocused; + }; + bool AddedByTestEngine; +}; +typedef ImS16 ImGuiKeyRoutingIndex; +typedef struct ImGuiKeyRoutingData ImGuiKeyRoutingData; +struct ImGuiKeyRoutingData +{ + ImGuiKeyRoutingIndex NextEntryIndex; + ImU16 Mods; + ImU8 RoutingCurrScore; + ImU8 RoutingNextScore; + ImGuiID RoutingCurr; + ImGuiID RoutingNext; +}; +typedef struct ImGuiKeyRoutingTable ImGuiKeyRoutingTable; +typedef struct ImVector_ImGuiKeyRoutingData {int Size;int Capacity;ImGuiKeyRoutingData* Data;} ImVector_ImGuiKeyRoutingData; + +struct ImGuiKeyRoutingTable +{ + ImGuiKeyRoutingIndex Index[ImGuiKey_NamedKey_COUNT]; + ImVector_ImGuiKeyRoutingData Entries; + ImVector_ImGuiKeyRoutingData EntriesNext; +}; +typedef struct ImGuiKeyOwnerData ImGuiKeyOwnerData; +struct ImGuiKeyOwnerData +{ + ImGuiID OwnerCurr; + ImGuiID OwnerNext; + bool LockThisFrame; + bool LockUntilRelease; +}; +typedef enum { + ImGuiInputFlags_RepeatRateDefault = 1 << 1, + ImGuiInputFlags_RepeatRateNavMove = 1 << 2, + ImGuiInputFlags_RepeatRateNavTweak = 1 << 3, + ImGuiInputFlags_RepeatUntilRelease = 1 << 4, + ImGuiInputFlags_RepeatUntilKeyModsChange = 1 << 5, + ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone = 1 << 6, + ImGuiInputFlags_RepeatUntilOtherKeyPress = 1 << 7, + ImGuiInputFlags_LockThisFrame = 1 << 20, + ImGuiInputFlags_LockUntilRelease = 1 << 21, + ImGuiInputFlags_CondHovered = 1 << 22, + ImGuiInputFlags_CondActive = 1 << 23, + ImGuiInputFlags_CondDefault_ = ImGuiInputFlags_CondHovered | ImGuiInputFlags_CondActive, + ImGuiInputFlags_RepeatRateMask_ = ImGuiInputFlags_RepeatRateDefault | ImGuiInputFlags_RepeatRateNavMove | ImGuiInputFlags_RepeatRateNavTweak, + ImGuiInputFlags_RepeatUntilMask_ = ImGuiInputFlags_RepeatUntilRelease | ImGuiInputFlags_RepeatUntilKeyModsChange | ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone | ImGuiInputFlags_RepeatUntilOtherKeyPress, + ImGuiInputFlags_RepeatMask_ = ImGuiInputFlags_Repeat | ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_, + ImGuiInputFlags_CondMask_ = ImGuiInputFlags_CondHovered | ImGuiInputFlags_CondActive, + ImGuiInputFlags_RouteTypeMask_ = ImGuiInputFlags_RouteActive | ImGuiInputFlags_RouteFocused | ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteAlways, + ImGuiInputFlags_RouteOptionsMask_ = ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive | ImGuiInputFlags_RouteUnlessBgFocused | ImGuiInputFlags_RouteFromRootWindow, + ImGuiInputFlags_SupportedByIsKeyPressed = ImGuiInputFlags_RepeatMask_, + ImGuiInputFlags_SupportedByIsMouseClicked = ImGuiInputFlags_Repeat, + ImGuiInputFlags_SupportedByShortcut = ImGuiInputFlags_RepeatMask_ | ImGuiInputFlags_RouteTypeMask_ | ImGuiInputFlags_RouteOptionsMask_, + ImGuiInputFlags_SupportedBySetNextItemShortcut = ImGuiInputFlags_RepeatMask_ | ImGuiInputFlags_RouteTypeMask_ | ImGuiInputFlags_RouteOptionsMask_ | ImGuiInputFlags_Tooltip, + ImGuiInputFlags_SupportedBySetKeyOwner = ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease, + ImGuiInputFlags_SupportedBySetItemKeyOwner = ImGuiInputFlags_SupportedBySetKeyOwner | ImGuiInputFlags_CondMask_, +}ImGuiInputFlagsPrivate_; +typedef struct ImGuiListClipperRange ImGuiListClipperRange; +struct ImGuiListClipperRange +{ + int Min; + int Max; + bool PosToIndexConvert; + ImS8 PosToIndexOffsetMin; + ImS8 PosToIndexOffsetMax; +}; +typedef struct ImGuiListClipperData ImGuiListClipperData; +typedef struct ImVector_ImGuiListClipperRange {int Size;int Capacity;ImGuiListClipperRange* Data;} ImVector_ImGuiListClipperRange; + +struct ImGuiListClipperData +{ + ImGuiListClipper* ListClipper; + float LossynessOffset; + int StepNo; + int ItemsFrozen; + ImVector_ImGuiListClipperRange Ranges; +}; +typedef enum { + ImGuiActivateFlags_None = 0, + ImGuiActivateFlags_PreferInput = 1 << 0, + ImGuiActivateFlags_PreferTweak = 1 << 1, + ImGuiActivateFlags_TryToPreserveState = 1 << 2, + ImGuiActivateFlags_FromTabbing = 1 << 3, + ImGuiActivateFlags_FromShortcut = 1 << 4, +}ImGuiActivateFlags_; +typedef enum { + ImGuiScrollFlags_None = 0, + ImGuiScrollFlags_KeepVisibleEdgeX = 1 << 0, + ImGuiScrollFlags_KeepVisibleEdgeY = 1 << 1, + ImGuiScrollFlags_KeepVisibleCenterX = 1 << 2, + ImGuiScrollFlags_KeepVisibleCenterY = 1 << 3, + ImGuiScrollFlags_AlwaysCenterX = 1 << 4, + ImGuiScrollFlags_AlwaysCenterY = 1 << 5, + ImGuiScrollFlags_NoScrollParent = 1 << 6, + ImGuiScrollFlags_MaskX_ = ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleCenterX | ImGuiScrollFlags_AlwaysCenterX, + ImGuiScrollFlags_MaskY_ = ImGuiScrollFlags_KeepVisibleEdgeY | ImGuiScrollFlags_KeepVisibleCenterY | ImGuiScrollFlags_AlwaysCenterY, +}ImGuiScrollFlags_; +typedef enum { + ImGuiNavRenderCursorFlags_None = 0, + ImGuiNavRenderCursorFlags_Compact = 1 << 1, + ImGuiNavRenderCursorFlags_AlwaysDraw = 1 << 2, + ImGuiNavRenderCursorFlags_NoRounding = 1 << 3, +}ImGuiNavRenderCursorFlags_; +typedef enum { + ImGuiNavMoveFlags_None = 0, + ImGuiNavMoveFlags_LoopX = 1 << 0, + ImGuiNavMoveFlags_LoopY = 1 << 1, + ImGuiNavMoveFlags_WrapX = 1 << 2, + ImGuiNavMoveFlags_WrapY = 1 << 3, + ImGuiNavMoveFlags_WrapMask_ = ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_WrapY, + ImGuiNavMoveFlags_AllowCurrentNavId = 1 << 4, + ImGuiNavMoveFlags_AlsoScoreVisibleSet = 1 << 5, + ImGuiNavMoveFlags_ScrollToEdgeY = 1 << 6, + ImGuiNavMoveFlags_Forwarded = 1 << 7, + ImGuiNavMoveFlags_DebugNoResult = 1 << 8, + ImGuiNavMoveFlags_FocusApi = 1 << 9, + ImGuiNavMoveFlags_IsTabbing = 1 << 10, + ImGuiNavMoveFlags_IsPageMove = 1 << 11, + ImGuiNavMoveFlags_Activate = 1 << 12, + ImGuiNavMoveFlags_NoSelect = 1 << 13, + ImGuiNavMoveFlags_NoSetNavCursorVisible = 1 << 14, + ImGuiNavMoveFlags_NoClearActiveId = 1 << 15, +}ImGuiNavMoveFlags_; +typedef enum { + ImGuiNavLayer_Main = 0, + ImGuiNavLayer_Menu = 1, + ImGuiNavLayer_COUNT +}ImGuiNavLayer; +struct ImGuiNavItemData +{ + ImGuiWindow* Window; + ImGuiID ID; + ImGuiID FocusScopeId; + ImRect RectRel; + ImGuiItemFlags ItemFlags; + float DistBox; + float DistCenter; + float DistAxial; + ImGuiSelectionUserData SelectionUserData; +}; +typedef struct ImGuiFocusScopeData ImGuiFocusScopeData; +struct ImGuiFocusScopeData +{ + ImGuiID ID; + ImGuiID WindowID; +}; +typedef enum { + ImGuiTypingSelectFlags_None = 0, + ImGuiTypingSelectFlags_AllowBackspace = 1 << 0, + ImGuiTypingSelectFlags_AllowSingleCharMode = 1 << 1, +}ImGuiTypingSelectFlags_; +struct ImGuiTypingSelectRequest +{ + ImGuiTypingSelectFlags Flags; + int SearchBufferLen; + const char* SearchBuffer; + bool SelectRequest; + bool SingleCharMode; + ImS8 SingleCharSize; +}; +struct ImGuiTypingSelectState +{ + ImGuiTypingSelectRequest Request; + char SearchBuffer[64]; + ImGuiID FocusScope; + int LastRequestFrame; + float LastRequestTime; + bool SingleCharModeLock; +}; +typedef enum { + ImGuiOldColumnFlags_None = 0, + ImGuiOldColumnFlags_NoBorder = 1 << 0, + ImGuiOldColumnFlags_NoResize = 1 << 1, + ImGuiOldColumnFlags_NoPreserveWidths = 1 << 2, + ImGuiOldColumnFlags_NoForceWithinWindow = 1 << 3, + ImGuiOldColumnFlags_GrowParentContentsSize = 1 << 4, +}ImGuiOldColumnFlags_; +struct ImGuiOldColumnData +{ + float OffsetNorm; + float OffsetNormBeforeResize; + ImGuiOldColumnFlags Flags; + ImRect ClipRect; +}; +typedef struct ImVector_ImGuiOldColumnData {int Size;int Capacity;ImGuiOldColumnData* Data;} ImVector_ImGuiOldColumnData; + +struct ImGuiOldColumns +{ + ImGuiID ID; + ImGuiOldColumnFlags Flags; + bool IsFirstFrame; + bool IsBeingResized; + int Current; + int Count; + float OffMinX, OffMaxX; + float LineMinY, LineMaxY; + float HostCursorPosY; + float HostCursorMaxPosX; + ImRect HostInitialClipRect; + ImRect HostBackupClipRect; + ImRect HostBackupParentWorkRect; + ImVector_ImGuiOldColumnData Columns; + ImDrawListSplitter Splitter; +}; +struct ImGuiBoxSelectState +{ + ImGuiID ID; + bool IsActive; + bool IsStarting; + bool IsStartedFromVoid; + bool IsStartedSetNavIdOnce; + bool RequestClear; + ImGuiKeyChord KeyMods : 16; + ImVec2 StartPosRel; + ImVec2 EndPosRel; + ImVec2 ScrollAccum; + ImGuiWindow* Window; + bool UnclipMode; + ImRect UnclipRect; + ImRect BoxSelectRectPrev; + ImRect BoxSelectRectCurr; +}; +struct ImGuiMultiSelectTempData +{ + ImGuiMultiSelectIO IO; + ImGuiMultiSelectState* Storage; + ImGuiID FocusScopeId; + ImGuiMultiSelectFlags Flags; + ImVec2 ScopeRectMin; + ImVec2 BackupCursorMaxPos; + ImGuiSelectionUserData LastSubmittedItem; + ImGuiID BoxSelectId; + ImGuiKeyChord KeyMods; + ImS8 LoopRequestSetAll; + bool IsEndIO; + bool IsFocused; + bool IsKeyboardSetRange; + bool NavIdPassedBy; + bool RangeSrcPassedBy; + bool RangeDstPassedBy; +}; +struct ImGuiMultiSelectState +{ + ImGuiWindow* Window; + ImGuiID ID; + int LastFrameActive; + int LastSelectionSize; + ImS8 RangeSelected; + ImS8 NavIdSelected; + ImGuiSelectionUserData RangeSrcItem; + ImGuiSelectionUserData NavIdItem; +}; +typedef enum { + ImGuiDockNodeFlags_DockSpace = 1 << 10, + ImGuiDockNodeFlags_CentralNode = 1 << 11, + ImGuiDockNodeFlags_NoTabBar = 1 << 12, + ImGuiDockNodeFlags_HiddenTabBar = 1 << 13, + ImGuiDockNodeFlags_NoWindowMenuButton = 1 << 14, + ImGuiDockNodeFlags_NoCloseButton = 1 << 15, + ImGuiDockNodeFlags_NoResizeX = 1 << 16, + ImGuiDockNodeFlags_NoResizeY = 1 << 17, + ImGuiDockNodeFlags_DockedWindowsInFocusRoute= 1 << 18, + ImGuiDockNodeFlags_NoDockingSplitOther = 1 << 19, + ImGuiDockNodeFlags_NoDockingOverMe = 1 << 20, + ImGuiDockNodeFlags_NoDockingOverOther = 1 << 21, + ImGuiDockNodeFlags_NoDockingOverEmpty = 1 << 22, + ImGuiDockNodeFlags_NoDocking = ImGuiDockNodeFlags_NoDockingOverMe | ImGuiDockNodeFlags_NoDockingOverOther | ImGuiDockNodeFlags_NoDockingOverEmpty | ImGuiDockNodeFlags_NoDockingSplit | ImGuiDockNodeFlags_NoDockingSplitOther, + ImGuiDockNodeFlags_SharedFlagsInheritMask_ = ~0, + ImGuiDockNodeFlags_NoResizeFlagsMask_ = (int)ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_NoResizeX | ImGuiDockNodeFlags_NoResizeY, + ImGuiDockNodeFlags_LocalFlagsTransferMask_ = (int)ImGuiDockNodeFlags_NoDockingSplit | ImGuiDockNodeFlags_NoResizeFlagsMask_ | (int)ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton, + ImGuiDockNodeFlags_SavedFlagsMask_ = ImGuiDockNodeFlags_NoResizeFlagsMask_ | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton, +}ImGuiDockNodeFlagsPrivate_; +typedef enum { + ImGuiDataAuthority_Auto, + ImGuiDataAuthority_DockNode, + ImGuiDataAuthority_Window, +}ImGuiDataAuthority_; +typedef enum { + ImGuiDockNodeState_Unknown, + ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow, + ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing, + ImGuiDockNodeState_HostWindowVisible, +}ImGuiDockNodeState; +typedef struct ImVector_ImGuiWindowPtr {int Size;int Capacity;ImGuiWindow** Data;} ImVector_ImGuiWindowPtr; + +struct ImGuiDockNode +{ + ImGuiID ID; + ImGuiDockNodeFlags SharedFlags; + ImGuiDockNodeFlags LocalFlags; + ImGuiDockNodeFlags LocalFlagsInWindows; + ImGuiDockNodeFlags MergedFlags; + ImGuiDockNodeState State; + ImGuiDockNode* ParentNode; + ImGuiDockNode* ChildNodes[2]; + ImVector_ImGuiWindowPtr Windows; + ImGuiTabBar* TabBar; + ImVec2 Pos; + ImVec2 Size; + ImVec2 SizeRef; + ImGuiAxis SplitAxis; + ImGuiWindowClass WindowClass; + ImU32 LastBgColor; + ImGuiWindow* HostWindow; + ImGuiWindow* VisibleWindow; + ImGuiDockNode* CentralNode; + ImGuiDockNode* OnlyNodeWithWindows; + int CountNodeWithWindows; + int LastFrameAlive; + int LastFrameActive; + int LastFrameFocused; + ImGuiID LastFocusedNodeId; + ImGuiID SelectedTabId; + ImGuiID WantCloseTabId; + ImGuiID RefViewportId; + ImGuiDataAuthority AuthorityForPos :3; + ImGuiDataAuthority AuthorityForSize :3; + ImGuiDataAuthority AuthorityForViewport :3; + bool IsVisible :1; + bool IsFocused :1; + bool IsBgDrawnThisFrame :1; + bool HasCloseButton :1; + bool HasWindowMenuButton :1; + bool HasCentralNodeChild :1; + bool WantCloseAll :1; + bool WantLockSizeOnce :1; + bool WantMouseMove :1; + bool WantHiddenTabBarUpdate :1; + bool WantHiddenTabBarToggle :1; +}; +typedef enum { + ImGuiWindowDockStyleCol_Text, + ImGuiWindowDockStyleCol_TabHovered, + ImGuiWindowDockStyleCol_TabFocused, + ImGuiWindowDockStyleCol_TabSelected, + ImGuiWindowDockStyleCol_TabSelectedOverline, + ImGuiWindowDockStyleCol_TabDimmed, + ImGuiWindowDockStyleCol_TabDimmedSelected, + ImGuiWindowDockStyleCol_TabDimmedSelectedOverline, + ImGuiWindowDockStyleCol_COUNT +}ImGuiWindowDockStyleCol; +struct ImGuiWindowDockStyle +{ + ImU32 Colors[ImGuiWindowDockStyleCol_COUNT]; +}; +typedef struct ImVector_ImGuiDockRequest {int Size;int Capacity;ImGuiDockRequest* Data;} ImVector_ImGuiDockRequest; + +typedef struct ImVector_ImGuiDockNodeSettings {int Size;int Capacity;ImGuiDockNodeSettings* Data;} ImVector_ImGuiDockNodeSettings; + +struct ImGuiDockContext +{ + ImGuiStorage Nodes; + ImVector_ImGuiDockRequest Requests; + ImVector_ImGuiDockNodeSettings NodesSettings; + bool WantFullRebuild; +}; +typedef struct ImGuiViewportP ImGuiViewportP; +struct ImGuiViewportP +{ + ImGuiViewport _ImGuiViewport; + ImGuiWindow* Window; + int Idx; + int LastFrameActive; + int LastFocusedStampCount; + ImGuiID LastNameHash; + ImVec2 LastPos; + ImVec2 LastSize; + float Alpha; + float LastAlpha; + bool LastFocusedHadNavWindow; + short PlatformMonitor; + int BgFgDrawListsLastFrame[2]; + ImDrawList* BgFgDrawLists[2]; + ImDrawData DrawDataP; + ImDrawDataBuilder DrawDataBuilder; + ImVec2 LastPlatformPos; + ImVec2 LastPlatformSize; + ImVec2 LastRendererSize; + ImVec2 WorkInsetMin; + ImVec2 WorkInsetMax; + ImVec2 BuildWorkInsetMin; + ImVec2 BuildWorkInsetMax; +}; +struct ImGuiWindowSettings +{ + ImGuiID ID; + ImVec2ih Pos; + ImVec2ih Size; + ImVec2ih ViewportPos; + ImGuiID ViewportId; + ImGuiID DockId; + ImGuiID ClassId; + short DockOrder; + bool Collapsed; + bool IsChild; + bool WantApply; + bool WantDelete; +}; +struct ImGuiSettingsHandler +{ + const char* TypeName; + ImGuiID TypeHash; + void (*ClearAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); + void (*ReadInitFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); + void* (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name); + void (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line); + void (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); + void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); + void* UserData; +}; +typedef enum { +ImGuiLocKey_VersionStr=0, +ImGuiLocKey_TableSizeOne=1, +ImGuiLocKey_TableSizeAllFit=2, +ImGuiLocKey_TableSizeAllDefault=3, +ImGuiLocKey_TableResetOrder=4, +ImGuiLocKey_WindowingMainMenuBar=5, +ImGuiLocKey_WindowingPopup=6, +ImGuiLocKey_WindowingUntitled=7, +ImGuiLocKey_OpenLink_s=8, +ImGuiLocKey_CopyLink=9, +ImGuiLocKey_DockingHideTabBar=10, +ImGuiLocKey_DockingHoldShiftToDock=11, +ImGuiLocKey_DockingDragToUndockOrMoveNode=12, +ImGuiLocKey_COUNT=13, +}ImGuiLocKey; +struct ImGuiLocEntry +{ + ImGuiLocKey Key; + const char* Text; +}; +typedef void (*ImGuiErrorCallback)(ImGuiContext* ctx, void* user_data, const char* msg); +typedef enum { + ImGuiDebugLogFlags_None = 0, + ImGuiDebugLogFlags_EventError = 1 << 0, + ImGuiDebugLogFlags_EventActiveId = 1 << 1, + ImGuiDebugLogFlags_EventFocus = 1 << 2, + ImGuiDebugLogFlags_EventPopup = 1 << 3, + ImGuiDebugLogFlags_EventNav = 1 << 4, + ImGuiDebugLogFlags_EventClipper = 1 << 5, + ImGuiDebugLogFlags_EventSelection = 1 << 6, + ImGuiDebugLogFlags_EventIO = 1 << 7, + ImGuiDebugLogFlags_EventFont = 1 << 8, + ImGuiDebugLogFlags_EventInputRouting = 1 << 9, + ImGuiDebugLogFlags_EventDocking = 1 << 10, + ImGuiDebugLogFlags_EventViewport = 1 << 11, + ImGuiDebugLogFlags_EventMask_ = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_EventActiveId | ImGuiDebugLogFlags_EventFocus | ImGuiDebugLogFlags_EventPopup | ImGuiDebugLogFlags_EventNav | ImGuiDebugLogFlags_EventClipper | ImGuiDebugLogFlags_EventSelection | ImGuiDebugLogFlags_EventIO | ImGuiDebugLogFlags_EventFont | ImGuiDebugLogFlags_EventInputRouting | ImGuiDebugLogFlags_EventDocking | ImGuiDebugLogFlags_EventViewport, + ImGuiDebugLogFlags_OutputToTTY = 1 << 20, + ImGuiDebugLogFlags_OutputToTestEngine = 1 << 21, +}ImGuiDebugLogFlags_; +typedef struct ImGuiDebugAllocEntry ImGuiDebugAllocEntry; +struct ImGuiDebugAllocEntry +{ + int FrameCount; + ImS16 AllocCount; + ImS16 FreeCount; +}; +typedef struct ImGuiDebugAllocInfo ImGuiDebugAllocInfo; +struct ImGuiDebugAllocInfo +{ + int TotalAllocCount; + int TotalFreeCount; + ImS16 LastEntriesIdx; + ImGuiDebugAllocEntry LastEntriesBuf[6]; +}; +struct ImGuiMetricsConfig +{ + bool ShowDebugLog; + bool ShowIDStackTool; + bool ShowWindowsRects; + bool ShowWindowsBeginOrder; + bool ShowTablesRects; + bool ShowDrawCmdMesh; + bool ShowDrawCmdBoundingBoxes; + bool ShowTextEncodingViewer; + bool ShowDockingNodes; + int ShowWindowsRectsType; + int ShowTablesRectsType; + int HighlightMonitorIdx; + ImGuiID HighlightViewportID; +}; +typedef struct ImGuiStackLevelInfo ImGuiStackLevelInfo; +struct ImGuiStackLevelInfo +{ + ImGuiID ID; + ImS8 QueryFrameCount; + bool QuerySuccess; + ImGuiDataType DataType : 8; + char Desc[57]; +}; +typedef struct ImGuiIDStackTool ImGuiIDStackTool; +typedef struct ImVector_ImGuiStackLevelInfo {int Size;int Capacity;ImGuiStackLevelInfo* Data;} ImVector_ImGuiStackLevelInfo; + +struct ImGuiIDStackTool +{ + int LastActiveFrame; + int StackLevel; + ImGuiID QueryId; + ImVector_ImGuiStackLevelInfo Results; + bool CopyToClipboardOnCtrlC; + float CopyToClipboardLastTime; + ImGuiTextBuffer ResultPathBuf; +}; +typedef void (*ImGuiContextHookCallback)(ImGuiContext* ctx, ImGuiContextHook* hook); +typedef enum { ImGuiContextHookType_NewFramePre, ImGuiContextHookType_NewFramePost, ImGuiContextHookType_EndFramePre, ImGuiContextHookType_EndFramePost, ImGuiContextHookType_RenderPre, ImGuiContextHookType_RenderPost, ImGuiContextHookType_Shutdown, ImGuiContextHookType_PendingRemoval_ }ImGuiContextHookType; +struct ImGuiContextHook +{ + ImGuiID HookId; + ImGuiContextHookType Type; + ImGuiID Owner; + ImGuiContextHookCallback Callback; + void* UserData; +}; +typedef struct ImVector_ImGuiInputEvent {int Size;int Capacity;ImGuiInputEvent* Data;} ImVector_ImGuiInputEvent; + +typedef struct ImVector_ImGuiWindowStackData {int Size;int Capacity;ImGuiWindowStackData* Data;} ImVector_ImGuiWindowStackData; + +typedef struct ImVector_ImGuiColorMod {int Size;int Capacity;ImGuiColorMod* Data;} ImVector_ImGuiColorMod; + +typedef struct ImVector_ImGuiStyleMod {int Size;int Capacity;ImGuiStyleMod* Data;} ImVector_ImGuiStyleMod; + +typedef struct ImVector_ImGuiFocusScopeData {int Size;int Capacity;ImGuiFocusScopeData* Data;} ImVector_ImGuiFocusScopeData; + +typedef struct ImVector_ImGuiItemFlags {int Size;int Capacity;ImGuiItemFlags* Data;} ImVector_ImGuiItemFlags; + +typedef struct ImVector_ImGuiGroupData {int Size;int Capacity;ImGuiGroupData* Data;} ImVector_ImGuiGroupData; + +typedef struct ImVector_ImGuiPopupData {int Size;int Capacity;ImGuiPopupData* Data;} ImVector_ImGuiPopupData; + +typedef struct ImVector_ImGuiTreeNodeStackData {int Size;int Capacity;ImGuiTreeNodeStackData* Data;} ImVector_ImGuiTreeNodeStackData; + +typedef struct ImVector_ImGuiViewportPPtr {int Size;int Capacity;ImGuiViewportP** Data;} ImVector_ImGuiViewportPPtr; + +typedef struct ImVector_unsigned_char {int Size;int Capacity;unsigned char* Data;} ImVector_unsigned_char; + +typedef struct ImVector_ImGuiListClipperData {int Size;int Capacity;ImGuiListClipperData* Data;} ImVector_ImGuiListClipperData; + +typedef struct ImVector_ImGuiTableTempData {int Size;int Capacity;ImGuiTableTempData* Data;} ImVector_ImGuiTableTempData; + +typedef struct ImVector_ImGuiTable {int Size;int Capacity;ImGuiTable* Data;} ImVector_ImGuiTable; + +typedef struct ImPool_ImGuiTable {ImVector_ImGuiTable Buf;ImGuiStorage Map;ImPoolIdx FreeIdx;ImPoolIdx AliveCount;} ImPool_ImGuiTable; + +typedef struct ImVector_ImGuiTabBar {int Size;int Capacity;ImGuiTabBar* Data;} ImVector_ImGuiTabBar; + +typedef struct ImPool_ImGuiTabBar {ImVector_ImGuiTabBar Buf;ImGuiStorage Map;ImPoolIdx FreeIdx;ImPoolIdx AliveCount;} ImPool_ImGuiTabBar; + +typedef struct ImVector_ImGuiPtrOrIndex {int Size;int Capacity;ImGuiPtrOrIndex* Data;} ImVector_ImGuiPtrOrIndex; + +typedef struct ImVector_ImGuiShrinkWidthItem {int Size;int Capacity;ImGuiShrinkWidthItem* Data;} ImVector_ImGuiShrinkWidthItem; + +typedef struct ImVector_ImGuiMultiSelectTempData {int Size;int Capacity;ImGuiMultiSelectTempData* Data;} ImVector_ImGuiMultiSelectTempData; + +typedef struct ImVector_ImGuiMultiSelectState {int Size;int Capacity;ImGuiMultiSelectState* Data;} ImVector_ImGuiMultiSelectState; + +typedef struct ImPool_ImGuiMultiSelectState {ImVector_ImGuiMultiSelectState Buf;ImGuiStorage Map;ImPoolIdx FreeIdx;ImPoolIdx AliveCount;} ImPool_ImGuiMultiSelectState; + +typedef struct ImVector_ImGuiID {int Size;int Capacity;ImGuiID* Data;} ImVector_ImGuiID; + +typedef struct ImVector_ImGuiSettingsHandler {int Size;int Capacity;ImGuiSettingsHandler* Data;} ImVector_ImGuiSettingsHandler; + +typedef struct ImChunkStream_ImGuiWindowSettings {ImVector_char Buf;} ImChunkStream_ImGuiWindowSettings; + +typedef struct ImChunkStream_ImGuiTableSettings {ImVector_char Buf;} ImChunkStream_ImGuiTableSettings; + +typedef struct ImVector_ImGuiContextHook {int Size;int Capacity;ImGuiContextHook* Data;} ImVector_ImGuiContextHook; + +struct ImGuiContext +{ + bool Initialized; + bool FontAtlasOwnedByContext; + ImGuiIO IO; + ImGuiPlatformIO PlatformIO; + ImGuiStyle Style; + ImGuiConfigFlags ConfigFlagsCurrFrame; + ImGuiConfigFlags ConfigFlagsLastFrame; + ImFont* Font; + float FontSize; + float FontBaseSize; + float FontScale; + float CurrentDpiScale; + ImDrawListSharedData DrawListSharedData; + double Time; + int FrameCount; + int FrameCountEnded; + int FrameCountPlatformEnded; + int FrameCountRendered; + ImGuiID WithinEndChildID; + bool WithinFrameScope; + bool WithinFrameScopeWithImplicitWindow; + bool GcCompactAll; + bool TestEngineHookItems; + void* TestEngine; + char ContextName[16]; + ImVector_ImGuiInputEvent InputEventsQueue; + ImVector_ImGuiInputEvent InputEventsTrail; + ImGuiMouseSource InputEventsNextMouseSource; + ImU32 InputEventsNextEventId; + ImVector_ImGuiWindowPtr Windows; + ImVector_ImGuiWindowPtr WindowsFocusOrder; + ImVector_ImGuiWindowPtr WindowsTempSortBuffer; + ImVector_ImGuiWindowStackData CurrentWindowStack; + ImGuiStorage WindowsById; + int WindowsActiveCount; + float WindowsBorderHoverPadding; + ImGuiID DebugBreakInWindow; + ImGuiWindow* CurrentWindow; + ImGuiWindow* HoveredWindow; + ImGuiWindow* HoveredWindowUnderMovingWindow; + ImGuiWindow* HoveredWindowBeforeClear; + ImGuiWindow* MovingWindow; + ImGuiWindow* WheelingWindow; + ImVec2 WheelingWindowRefMousePos; + int WheelingWindowStartFrame; + int WheelingWindowScrolledFrame; + float WheelingWindowReleaseTimer; + ImVec2 WheelingWindowWheelRemainder; + ImVec2 WheelingAxisAvg; + ImGuiID DebugDrawIdConflicts; + ImGuiID DebugHookIdInfo; + ImGuiID HoveredId; + ImGuiID HoveredIdPreviousFrame; + int HoveredIdPreviousFrameItemCount; + float HoveredIdTimer; + float HoveredIdNotActiveTimer; + bool HoveredIdAllowOverlap; + bool HoveredIdIsDisabled; + bool ItemUnclipByLog; + ImGuiID ActiveId; + ImGuiID ActiveIdIsAlive; + float ActiveIdTimer; + bool ActiveIdIsJustActivated; + bool ActiveIdAllowOverlap; + bool ActiveIdNoClearOnFocusLoss; + bool ActiveIdHasBeenPressedBefore; + bool ActiveIdHasBeenEditedBefore; + bool ActiveIdHasBeenEditedThisFrame; + bool ActiveIdFromShortcut; + int ActiveIdMouseButton : 8; + ImVec2 ActiveIdClickOffset; + ImGuiWindow* ActiveIdWindow; + ImGuiInputSource ActiveIdSource; + ImGuiID ActiveIdPreviousFrame; + ImGuiDeactivatedItemData DeactivatedItemData; + ImGuiDataTypeStorage ActiveIdValueOnActivation; + ImGuiID LastActiveId; + float LastActiveIdTimer; + double LastKeyModsChangeTime; + double LastKeyModsChangeFromNoneTime; + double LastKeyboardKeyPressTime; + ImBitArrayForNamedKeys KeysMayBeCharInput; + ImGuiKeyOwnerData KeysOwnerData[ImGuiKey_NamedKey_COUNT]; + ImGuiKeyRoutingTable KeysRoutingTable; + ImU32 ActiveIdUsingNavDirMask; + bool ActiveIdUsingAllKeyboardKeys; + ImGuiKeyChord DebugBreakInShortcutRouting; + ImGuiID CurrentFocusScopeId; + ImGuiItemFlags CurrentItemFlags; + ImGuiID DebugLocateId; + ImGuiNextItemData NextItemData; + ImGuiLastItemData LastItemData; + ImGuiNextWindowData NextWindowData; + bool DebugShowGroupRects; + ImGuiCol DebugFlashStyleColorIdx; + ImVector_ImGuiColorMod ColorStack; + ImVector_ImGuiStyleMod StyleVarStack; + ImVector_ImFontPtr FontStack; + ImVector_ImGuiFocusScopeData FocusScopeStack; + ImVector_ImGuiItemFlags ItemFlagsStack; + ImVector_ImGuiGroupData GroupStack; + ImVector_ImGuiPopupData OpenPopupStack; + ImVector_ImGuiPopupData BeginPopupStack; + ImVector_ImGuiTreeNodeStackData TreeNodeStack; + ImVector_ImGuiViewportPPtr Viewports; + ImGuiViewportP* CurrentViewport; + ImGuiViewportP* MouseViewport; + ImGuiViewportP* MouseLastHoveredViewport; + ImGuiID PlatformLastFocusedViewportId; + ImGuiPlatformMonitor FallbackMonitor; + ImRect PlatformMonitorsFullWorkRect; + int ViewportCreatedCount; + int PlatformWindowsCreatedCount; + int ViewportFocusedStampCount; + bool NavCursorVisible; + bool NavHighlightItemUnderNav; + bool NavMousePosDirty; + bool NavIdIsAlive; + ImGuiID NavId; + ImGuiWindow* NavWindow; + ImGuiID NavFocusScopeId; + ImGuiNavLayer NavLayer; + ImGuiID NavActivateId; + ImGuiID NavActivateDownId; + ImGuiID NavActivatePressedId; + ImGuiActivateFlags NavActivateFlags; + ImVector_ImGuiFocusScopeData NavFocusRoute; + ImGuiID NavHighlightActivatedId; + float NavHighlightActivatedTimer; + ImGuiID NavNextActivateId; + ImGuiActivateFlags NavNextActivateFlags; + ImGuiInputSource NavInputSource; + ImGuiSelectionUserData NavLastValidSelectionUserData; + ImS8 NavCursorHideFrames; + bool NavAnyRequest; + bool NavInitRequest; + bool NavInitRequestFromMove; + ImGuiNavItemData NavInitResult; + bool NavMoveSubmitted; + bool NavMoveScoringItems; + bool NavMoveForwardToNextFrame; + ImGuiNavMoveFlags NavMoveFlags; + ImGuiScrollFlags NavMoveScrollFlags; + ImGuiKeyChord NavMoveKeyMods; + ImGuiDir NavMoveDir; + ImGuiDir NavMoveDirForDebug; + ImGuiDir NavMoveClipDir; + ImRect NavScoringRect; + ImRect NavScoringNoClipRect; + int NavScoringDebugCount; + int NavTabbingDir; + int NavTabbingCounter; + ImGuiNavItemData NavMoveResultLocal; + ImGuiNavItemData NavMoveResultLocalVisible; + ImGuiNavItemData NavMoveResultOther; + ImGuiNavItemData NavTabbingResultFirst; + ImGuiID NavJustMovedFromFocusScopeId; + ImGuiID NavJustMovedToId; + ImGuiID NavJustMovedToFocusScopeId; + ImGuiKeyChord NavJustMovedToKeyMods; + bool NavJustMovedToIsTabbing; + bool NavJustMovedToHasSelectionData; + ImGuiKeyChord ConfigNavWindowingKeyNext; + ImGuiKeyChord ConfigNavWindowingKeyPrev; + ImGuiWindow* NavWindowingTarget; + ImGuiWindow* NavWindowingTargetAnim; + ImGuiWindow* NavWindowingListWindow; + float NavWindowingTimer; + float NavWindowingHighlightAlpha; + bool NavWindowingToggleLayer; + ImGuiKey NavWindowingToggleKey; + ImVec2 NavWindowingAccumDeltaPos; + ImVec2 NavWindowingAccumDeltaSize; + float DimBgRatio; + bool DragDropActive; + bool DragDropWithinSource; + bool DragDropWithinTarget; + ImGuiDragDropFlags DragDropSourceFlags; + int DragDropSourceFrameCount; + int DragDropMouseButton; + ImGuiPayload DragDropPayload; + ImRect DragDropTargetRect; + ImRect DragDropTargetClipRect; + ImGuiID DragDropTargetId; + ImGuiDragDropFlags DragDropAcceptFlags; + float DragDropAcceptIdCurrRectSurface; + ImGuiID DragDropAcceptIdCurr; + ImGuiID DragDropAcceptIdPrev; + int DragDropAcceptFrameCount; + ImGuiID DragDropHoldJustPressedId; + ImVector_unsigned_char DragDropPayloadBufHeap; + unsigned char DragDropPayloadBufLocal[16]; + int ClipperTempDataStacked; + ImVector_ImGuiListClipperData ClipperTempData; + ImGuiTable* CurrentTable; + ImGuiID DebugBreakInTable; + int TablesTempDataStacked; + ImVector_ImGuiTableTempData TablesTempData; + ImPool_ImGuiTable Tables; + ImVector_float TablesLastTimeActive; + ImVector_ImDrawChannel DrawChannelsTempMergeBuffer; + ImGuiTabBar* CurrentTabBar; + ImPool_ImGuiTabBar TabBars; + ImVector_ImGuiPtrOrIndex CurrentTabBarStack; + ImVector_ImGuiShrinkWidthItem ShrinkWidthBuffer; + ImGuiBoxSelectState BoxSelectState; + ImGuiMultiSelectTempData* CurrentMultiSelect; + int MultiSelectTempDataStacked; + ImVector_ImGuiMultiSelectTempData MultiSelectTempData; + ImPool_ImGuiMultiSelectState MultiSelectStorage; + ImGuiID HoverItemDelayId; + ImGuiID HoverItemDelayIdPreviousFrame; + float HoverItemDelayTimer; + float HoverItemDelayClearTimer; + ImGuiID HoverItemUnlockedStationaryId; + ImGuiID HoverWindowUnlockedStationaryId; + ImGuiMouseCursor MouseCursor; + float MouseStationaryTimer; + ImVec2 MouseLastValidPos; + ImGuiInputTextState InputTextState; + ImGuiInputTextDeactivatedState InputTextDeactivatedState; + ImFont InputTextPasswordFont; + ImGuiID TempInputId; + ImGuiDataTypeStorage DataTypeZeroValue; + int BeginMenuDepth; + int BeginComboDepth; + ImGuiColorEditFlags ColorEditOptions; + ImGuiID ColorEditCurrentID; + ImGuiID ColorEditSavedID; + float ColorEditSavedHue; + float ColorEditSavedSat; + ImU32 ColorEditSavedColor; + ImVec4 ColorPickerRef; + ImGuiComboPreviewData ComboPreviewData; + ImRect WindowResizeBorderExpectedRect; + bool WindowResizeRelativeMode; + short ScrollbarSeekMode; + float ScrollbarClickDeltaToGrabCenter; + float SliderGrabClickOffset; + float SliderCurrentAccum; + bool SliderCurrentAccumDirty; + bool DragCurrentAccumDirty; + float DragCurrentAccum; + float DragSpeedDefaultRatio; + float DisabledAlphaBackup; + short DisabledStackSize; + short TooltipOverrideCount; + ImGuiWindow* TooltipPreviousWindow; + ImVector_char ClipboardHandlerData; + ImVector_ImGuiID MenusIdSubmittedThisFrame; + ImGuiTypingSelectState TypingSelectState; + ImGuiPlatformImeData PlatformImeData; + ImGuiPlatformImeData PlatformImeDataPrev; + ImGuiID PlatformImeViewport; + ImGuiDockContext DockContext; + void (*DockNodeWindowMenuHandler)(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar); + bool SettingsLoaded; + float SettingsDirtyTimer; + ImGuiTextBuffer SettingsIniData; + ImVector_ImGuiSettingsHandler SettingsHandlers; + ImChunkStream_ImGuiWindowSettings SettingsWindows; + ImChunkStream_ImGuiTableSettings SettingsTables; + ImVector_ImGuiContextHook Hooks; + ImGuiID HookIdNext; + const char* LocalizationTable[ImGuiLocKey_COUNT]; + bool LogEnabled; + ImGuiLogFlags LogFlags; + ImGuiWindow* LogWindow; + ImFileHandle LogFile; + ImGuiTextBuffer LogBuffer; + const char* LogNextPrefix; + const char* LogNextSuffix; + float LogLinePosY; + bool LogLineFirstItem; + int LogDepthRef; + int LogDepthToExpand; + int LogDepthToExpandDefault; + ImGuiErrorCallback ErrorCallback; + void* ErrorCallbackUserData; + ImVec2 ErrorTooltipLockedPos; + bool ErrorFirst; + int ErrorCountCurrentFrame; + ImGuiErrorRecoveryState StackSizesInNewFrame; + ImGuiErrorRecoveryState*StackSizesInBeginForCurrentWindow; + int DebugDrawIdConflictsCount; + ImGuiDebugLogFlags DebugLogFlags; + ImGuiTextBuffer DebugLogBuf; + ImGuiTextIndex DebugLogIndex; + int DebugLogSkippedErrors; + ImGuiDebugLogFlags DebugLogAutoDisableFlags; + ImU8 DebugLogAutoDisableFrames; + ImU8 DebugLocateFrames; + bool DebugBreakInLocateId; + ImGuiKeyChord DebugBreakKeyChord; + ImS8 DebugBeginReturnValueCullDepth; + bool DebugItemPickerActive; + ImU8 DebugItemPickerMouseButton; + ImGuiID DebugItemPickerBreakId; + float DebugFlashStyleColorTime; + ImVec4 DebugFlashStyleColorBackup; + ImGuiMetricsConfig DebugMetricsConfig; + ImGuiIDStackTool DebugIDStackTool; + ImGuiDebugAllocInfo DebugAllocInfo; + ImGuiDockNode* DebugHoveredDockNode; + float FramerateSecPerFrame[60]; + int FramerateSecPerFrameIdx; + int FramerateSecPerFrameCount; + float FramerateSecPerFrameAccum; + int WantCaptureMouseNextFrame; + int WantCaptureKeyboardNextFrame; + int WantTextInputNextFrame; + ImVector_char TempBuffer; + char TempKeychordName[64]; +}; +struct ImGuiWindowTempData +{ + ImVec2 CursorPos; + ImVec2 CursorPosPrevLine; + ImVec2 CursorStartPos; + ImVec2 CursorMaxPos; + ImVec2 IdealMaxPos; + ImVec2 CurrLineSize; + ImVec2 PrevLineSize; + float CurrLineTextBaseOffset; + float PrevLineTextBaseOffset; + bool IsSameLine; + bool IsSetPos; + ImVec1 Indent; + ImVec1 ColumnsOffset; + ImVec1 GroupOffset; + ImVec2 CursorStartPosLossyness; + ImGuiNavLayer NavLayerCurrent; + short NavLayersActiveMask; + short NavLayersActiveMaskNext; + bool NavIsScrollPushableX; + bool NavHideHighlightOneFrame; + bool NavWindowHasScrollY; + bool MenuBarAppending; + ImVec2 MenuBarOffset; + ImGuiMenuColumns MenuColumns; + int TreeDepth; + ImU32 TreeHasStackDataDepthMask; + ImVector_ImGuiWindowPtr ChildWindows; + ImGuiStorage* StateStorage; + ImGuiOldColumns* CurrentColumns; + int CurrentTableIdx; + ImGuiLayoutType LayoutType; + ImGuiLayoutType ParentLayoutType; + ImU32 ModalDimBgColor; + ImGuiItemStatusFlags WindowItemStatusFlags; + ImGuiItemStatusFlags ChildItemStatusFlags; + ImGuiItemStatusFlags DockTabItemStatusFlags; + ImRect DockTabItemRect; + float ItemWidth; + float TextWrapPos; + ImVector_float ItemWidthStack; + ImVector_float TextWrapPosStack; +}; +typedef struct ImVector_ImGuiOldColumns {int Size;int Capacity;ImGuiOldColumns* Data;} ImVector_ImGuiOldColumns; + +struct ImGuiWindow +{ + ImGuiContext* Ctx; + char* Name; + ImGuiID ID; + ImGuiWindowFlags Flags, FlagsPreviousFrame; + ImGuiChildFlags ChildFlags; + ImGuiWindowClass WindowClass; + ImGuiViewportP* Viewport; + ImGuiID ViewportId; + ImVec2 ViewportPos; + int ViewportAllowPlatformMonitorExtend; + ImVec2 Pos; + ImVec2 Size; + ImVec2 SizeFull; + ImVec2 ContentSize; + ImVec2 ContentSizeIdeal; + ImVec2 ContentSizeExplicit; + ImVec2 WindowPadding; + float WindowRounding; + float WindowBorderSize; + float TitleBarHeight, MenuBarHeight; + float DecoOuterSizeX1, DecoOuterSizeY1; + float DecoOuterSizeX2, DecoOuterSizeY2; + float DecoInnerSizeX1, DecoInnerSizeY1; + int NameBufLen; + ImGuiID MoveId; + ImGuiID TabId; + ImGuiID ChildId; + ImGuiID PopupId; + ImVec2 Scroll; + ImVec2 ScrollMax; + ImVec2 ScrollTarget; + ImVec2 ScrollTargetCenterRatio; + ImVec2 ScrollTargetEdgeSnapDist; + ImVec2 ScrollbarSizes; + bool ScrollbarX, ScrollbarY; + bool ScrollbarXStabilizeEnabled; + ImU8 ScrollbarXStabilizeToggledHistory; + bool ViewportOwned; + bool Active; + bool WasActive; + bool WriteAccessed; + bool Collapsed; + bool WantCollapseToggle; + bool SkipItems; + bool SkipRefresh; + bool Appearing; + bool Hidden; + bool IsFallbackWindow; + bool IsExplicitChild; + bool HasCloseButton; + signed char ResizeBorderHovered; + signed char ResizeBorderHeld; + short BeginCount; + short BeginCountPreviousFrame; + short BeginOrderWithinParent; + short BeginOrderWithinContext; + short FocusOrder; + ImS8 AutoFitFramesX, AutoFitFramesY; + bool AutoFitOnlyGrows; + ImGuiDir AutoPosLastDirection; + ImS8 HiddenFramesCanSkipItems; + ImS8 HiddenFramesCannotSkipItems; + ImS8 HiddenFramesForRenderOnly; + ImS8 DisableInputsFrames; + ImGuiCond SetWindowPosAllowFlags : 8; + ImGuiCond SetWindowSizeAllowFlags : 8; + ImGuiCond SetWindowCollapsedAllowFlags : 8; + ImGuiCond SetWindowDockAllowFlags : 8; + ImVec2 SetWindowPosVal; + ImVec2 SetWindowPosPivot; + ImVector_ImGuiID IDStack; + ImGuiWindowTempData DC; + ImRect OuterRectClipped; + ImRect InnerRect; + ImRect InnerClipRect; + ImRect WorkRect; + ImRect ParentWorkRect; + ImRect ClipRect; + ImRect ContentRegionRect; + ImVec2ih HitTestHoleSize; + ImVec2ih HitTestHoleOffset; + int LastFrameActive; + int LastFrameJustFocused; + float LastTimeActive; + float ItemWidthDefault; + ImGuiStorage StateStorage; + ImVector_ImGuiOldColumns ColumnsStorage; + float FontWindowScale; + float FontWindowScaleParents; + float FontDpiScale; + float FontRefSize; + int SettingsOffset; + ImDrawList* DrawList; + ImDrawList DrawListInst; + ImGuiWindow* ParentWindow; + ImGuiWindow* ParentWindowInBeginStack; + ImGuiWindow* RootWindow; + ImGuiWindow* RootWindowPopupTree; + ImGuiWindow* RootWindowDockTree; + ImGuiWindow* RootWindowForTitleBarHighlight; + ImGuiWindow* RootWindowForNav; + ImGuiWindow* ParentWindowForFocusRoute; + ImGuiWindow* NavLastChildNavWindow; + ImGuiID NavLastIds[ImGuiNavLayer_COUNT]; + ImRect NavRectRel[ImGuiNavLayer_COUNT]; + ImVec2 NavPreferredScoringPosRel[ImGuiNavLayer_COUNT]; + ImGuiID NavRootFocusScopeId; + int MemoryDrawListIdxCapacity; + int MemoryDrawListVtxCapacity; + bool MemoryCompacted; + bool DockIsActive :1; + bool DockNodeIsVisible :1; + bool DockTabIsVisible :1; + bool DockTabWantClose :1; + short DockOrder; + ImGuiWindowDockStyle DockStyle; + ImGuiDockNode* DockNode; + ImGuiDockNode* DockNodeAsHost; + ImGuiID DockId; +}; +typedef enum { + ImGuiTabBarFlags_DockNode = 1 << 20, + ImGuiTabBarFlags_IsFocused = 1 << 21, + ImGuiTabBarFlags_SaveSettings = 1 << 22, +}ImGuiTabBarFlagsPrivate_; +typedef enum { + ImGuiTabItemFlags_SectionMask_ = ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing, + ImGuiTabItemFlags_NoCloseButton = 1 << 20, + ImGuiTabItemFlags_Button = 1 << 21, + ImGuiTabItemFlags_Invisible = 1 << 22, + ImGuiTabItemFlags_Unsorted = 1 << 23, +}ImGuiTabItemFlagsPrivate_; +struct ImGuiTabItem +{ + ImGuiID ID; + ImGuiTabItemFlags Flags; + ImGuiWindow* Window; + int LastFrameVisible; + int LastFrameSelected; + float Offset; + float Width; + float ContentWidth; + float RequestedWidth; + ImS32 NameOffset; + ImS16 BeginOrder; + ImS16 IndexDuringLayout; + bool WantClose; +}; +typedef struct ImVector_ImGuiTabItem {int Size;int Capacity;ImGuiTabItem* Data;} ImVector_ImGuiTabItem; + +struct ImGuiTabBar +{ + ImGuiWindow* Window; + ImVector_ImGuiTabItem Tabs; + ImGuiTabBarFlags Flags; + ImGuiID ID; + ImGuiID SelectedTabId; + ImGuiID NextSelectedTabId; + ImGuiID VisibleTabId; + int CurrFrameVisible; + int PrevFrameVisible; + ImRect BarRect; + float CurrTabsContentsHeight; + float PrevTabsContentsHeight; + float WidthAllTabs; + float WidthAllTabsIdeal; + float ScrollingAnim; + float ScrollingTarget; + float ScrollingTargetDistToVisibility; + float ScrollingSpeed; + float ScrollingRectMinX; + float ScrollingRectMaxX; + float SeparatorMinX; + float SeparatorMaxX; + ImGuiID ReorderRequestTabId; + ImS16 ReorderRequestOffset; + ImS8 BeginCount; + bool WantLayout; + bool VisibleTabWasSubmitted; + bool TabsAddedNew; + ImS16 TabsActiveCount; + ImS16 LastTabItemIdx; + float ItemSpacingY; + ImVec2 FramePadding; + ImVec2 BackupCursorPos; + ImGuiTextBuffer TabsNames; +}; +typedef ImS16 ImGuiTableColumnIdx; +typedef ImU16 ImGuiTableDrawChannelIdx; +struct ImGuiTableColumn +{ + ImGuiTableColumnFlags Flags; + float WidthGiven; + float MinX; + float MaxX; + float WidthRequest; + float WidthAuto; + float WidthMax; + float StretchWeight; + float InitStretchWeightOrWidth; + ImRect ClipRect; + ImGuiID UserID; + float WorkMinX; + float WorkMaxX; + float ItemWidth; + float ContentMaxXFrozen; + float ContentMaxXUnfrozen; + float ContentMaxXHeadersUsed; + float ContentMaxXHeadersIdeal; + ImS16 NameOffset; + ImGuiTableColumnIdx DisplayOrder; + ImGuiTableColumnIdx IndexWithinEnabledSet; + ImGuiTableColumnIdx PrevEnabledColumn; + ImGuiTableColumnIdx NextEnabledColumn; + ImGuiTableColumnIdx SortOrder; + ImGuiTableDrawChannelIdx DrawChannelCurrent; + ImGuiTableDrawChannelIdx DrawChannelFrozen; + ImGuiTableDrawChannelIdx DrawChannelUnfrozen; + bool IsEnabled; + bool IsUserEnabled; + bool IsUserEnabledNextFrame; + bool IsVisibleX; + bool IsVisibleY; + bool IsRequestOutput; + bool IsSkipItems; + bool IsPreserveWidthAuto; + ImS8 NavLayerCurrent; + ImU8 AutoFitQueue; + ImU8 CannotSkipItemsQueue; + ImU8 SortDirection : 2; + ImU8 SortDirectionsAvailCount : 2; + ImU8 SortDirectionsAvailMask : 4; + ImU8 SortDirectionsAvailList; +}; +typedef struct ImGuiTableCellData ImGuiTableCellData; +struct ImGuiTableCellData +{ + ImU32 BgColor; + ImGuiTableColumnIdx Column; +}; +struct ImGuiTableHeaderData +{ + ImGuiTableColumnIdx Index; + ImU32 TextColor; + ImU32 BgColor0; + ImU32 BgColor1; +}; +struct ImGuiTableInstanceData +{ + ImGuiID TableInstanceID; + float LastOuterHeight; + float LastTopHeadersRowHeight; + float LastFrozenHeight; + int HoveredRowLast; + int HoveredRowNext; +}; +typedef struct ImSpan_ImGuiTableColumn {ImGuiTableColumn* Data;ImGuiTableColumn* DataEnd;} ImSpan_ImGuiTableColumn; + +typedef struct ImSpan_ImGuiTableColumnIdx {ImGuiTableColumnIdx* Data;ImGuiTableColumnIdx* DataEnd;} ImSpan_ImGuiTableColumnIdx; + +typedef struct ImSpan_ImGuiTableCellData {ImGuiTableCellData* Data;ImGuiTableCellData* DataEnd;} ImSpan_ImGuiTableCellData; + +typedef struct ImVector_ImGuiTableInstanceData {int Size;int Capacity;ImGuiTableInstanceData* Data;} ImVector_ImGuiTableInstanceData; + +typedef struct ImVector_ImGuiTableColumnSortSpecs {int Size;int Capacity;ImGuiTableColumnSortSpecs* Data;} ImVector_ImGuiTableColumnSortSpecs; + +struct ImGuiTable +{ + ImGuiID ID; + ImGuiTableFlags Flags; + void* RawData; + ImGuiTableTempData* TempData; + ImSpan_ImGuiTableColumn Columns; + ImSpan_ImGuiTableColumnIdx DisplayOrderToIndex; + ImSpan_ImGuiTableCellData RowCellData; + ImBitArrayPtr EnabledMaskByDisplayOrder; + ImBitArrayPtr EnabledMaskByIndex; + ImBitArrayPtr VisibleMaskByIndex; + ImGuiTableFlags SettingsLoadedFlags; + int SettingsOffset; + int LastFrameActive; + int ColumnsCount; + int CurrentRow; + int CurrentColumn; + ImS16 InstanceCurrent; + ImS16 InstanceInteracted; + float RowPosY1; + float RowPosY2; + float RowMinHeight; + float RowCellPaddingY; + float RowTextBaseline; + float RowIndentOffsetX; + ImGuiTableRowFlags RowFlags : 16; + ImGuiTableRowFlags LastRowFlags : 16; + int RowBgColorCounter; + ImU32 RowBgColor[2]; + ImU32 BorderColorStrong; + ImU32 BorderColorLight; + float BorderX1; + float BorderX2; + float HostIndentX; + float MinColumnWidth; + float OuterPaddingX; + float CellPaddingX; + float CellSpacingX1; + float CellSpacingX2; + float InnerWidth; + float ColumnsGivenWidth; + float ColumnsAutoFitWidth; + float ColumnsStretchSumWeights; + float ResizedColumnNextWidth; + float ResizeLockMinContentsX2; + float RefScale; + float AngledHeadersHeight; + float AngledHeadersSlope; + ImRect OuterRect; + ImRect InnerRect; + ImRect WorkRect; + ImRect InnerClipRect; + ImRect BgClipRect; + ImRect Bg0ClipRectForDrawCmd; + ImRect Bg2ClipRectForDrawCmd; + ImRect HostClipRect; + ImRect HostBackupInnerClipRect; + ImGuiWindow* OuterWindow; + ImGuiWindow* InnerWindow; + ImGuiTextBuffer ColumnsNames; + ImDrawListSplitter* DrawSplitter; + ImGuiTableInstanceData InstanceDataFirst; + ImVector_ImGuiTableInstanceData InstanceDataExtra; + ImGuiTableColumnSortSpecs SortSpecsSingle; + ImVector_ImGuiTableColumnSortSpecs SortSpecsMulti; + ImGuiTableSortSpecs SortSpecs; + ImGuiTableColumnIdx SortSpecsCount; + ImGuiTableColumnIdx ColumnsEnabledCount; + ImGuiTableColumnIdx ColumnsEnabledFixedCount; + ImGuiTableColumnIdx DeclColumnsCount; + ImGuiTableColumnIdx AngledHeadersCount; + ImGuiTableColumnIdx HoveredColumnBody; + ImGuiTableColumnIdx HoveredColumnBorder; + ImGuiTableColumnIdx HighlightColumnHeader; + ImGuiTableColumnIdx AutoFitSingleColumn; + ImGuiTableColumnIdx ResizedColumn; + ImGuiTableColumnIdx LastResizedColumn; + ImGuiTableColumnIdx HeldHeaderColumn; + ImGuiTableColumnIdx ReorderColumn; + ImGuiTableColumnIdx ReorderColumnDir; + ImGuiTableColumnIdx LeftMostEnabledColumn; + ImGuiTableColumnIdx RightMostEnabledColumn; + ImGuiTableColumnIdx LeftMostStretchedColumn; + ImGuiTableColumnIdx RightMostStretchedColumn; + ImGuiTableColumnIdx ContextPopupColumn; + ImGuiTableColumnIdx FreezeRowsRequest; + ImGuiTableColumnIdx FreezeRowsCount; + ImGuiTableColumnIdx FreezeColumnsRequest; + ImGuiTableColumnIdx FreezeColumnsCount; + ImGuiTableColumnIdx RowCellDataCurrent; + ImGuiTableDrawChannelIdx DummyDrawChannel; + ImGuiTableDrawChannelIdx Bg2DrawChannelCurrent; + ImGuiTableDrawChannelIdx Bg2DrawChannelUnfrozen; + ImS8 NavLayer; + bool IsLayoutLocked; + bool IsInsideRow; + bool IsInitializing; + bool IsSortSpecsDirty; + bool IsUsingHeaders; + bool IsContextPopupOpen; + bool DisableDefaultContextMenu; + bool IsSettingsRequestLoad; + bool IsSettingsDirty; + bool IsDefaultDisplayOrder; + bool IsResetAllRequest; + bool IsResetDisplayOrderRequest; + bool IsUnfrozenRows; + bool IsDefaultSizingPolicy; + bool IsActiveIdAliveBeforeTable; + bool IsActiveIdInTable; + bool HasScrollbarYCurr; + bool HasScrollbarYPrev; + bool MemoryCompacted; + bool HostSkipItems; +}; +typedef struct ImVector_ImGuiTableHeaderData {int Size;int Capacity;ImGuiTableHeaderData* Data;} ImVector_ImGuiTableHeaderData; + +struct ImGuiTableTempData +{ + int TableIndex; + float LastTimeActive; + float AngledHeadersExtraWidth; + ImVector_ImGuiTableHeaderData AngledHeadersRequests; + ImVec2 UserOuterSize; + ImDrawListSplitter DrawSplitter; + ImRect HostBackupWorkRect; + ImRect HostBackupParentWorkRect; + ImVec2 HostBackupPrevLineSize; + ImVec2 HostBackupCurrLineSize; + ImVec2 HostBackupCursorMaxPos; + ImVec1 HostBackupColumnsOffset; + float HostBackupItemWidth; + int HostBackupItemWidthStackSize; +}; +typedef struct ImGuiTableColumnSettings ImGuiTableColumnSettings; +struct ImGuiTableColumnSettings +{ + float WidthOrWeight; + ImGuiID UserID; + ImGuiTableColumnIdx Index; + ImGuiTableColumnIdx DisplayOrder; + ImGuiTableColumnIdx SortOrder; + ImU8 SortDirection : 2; + ImS8 IsEnabled : 2; + ImU8 IsStretch : 1; +}; +struct ImGuiTableSettings +{ + ImGuiID ID; + ImGuiTableFlags SaveFlags; + float RefScale; + ImGuiTableColumnIdx ColumnsCount; + ImGuiTableColumnIdx ColumnsCountMax; + bool WantApply; +}; +struct ImFontBuilderIO +{ + bool (*FontBuilder_Build)(ImFontAtlas* atlas); +}; +#ifdef IMGUI_ENABLE_FREETYPE +struct ImFontAtlas; +struct ImFontBuilderIO; +typedef enum { + ImGuiFreeTypeBuilderFlags_NoHinting = 1 << 0, + ImGuiFreeTypeBuilderFlags_NoAutoHint = 1 << 1, + ImGuiFreeTypeBuilderFlags_ForceAutoHint = 1 << 2, + ImGuiFreeTypeBuilderFlags_LightHinting = 1 << 3, + ImGuiFreeTypeBuilderFlags_MonoHinting = 1 << 4, + ImGuiFreeTypeBuilderFlags_Bold = 1 << 5, + ImGuiFreeTypeBuilderFlags_Oblique = 1 << 6, + ImGuiFreeTypeBuilderFlags_Monochrome = 1 << 7, + ImGuiFreeTypeBuilderFlags_LoadColor = 1 << 8, + ImGuiFreeTypeBuilderFlags_Bitmap = 1 << 9 +}ImGuiFreeTypeBuilderFlags; +#endif +#define IMGUI_HAS_DOCK 1 + +#define ImDrawCallback_ResetRenderState (ImDrawCallback)(-8) + +#else +struct GLFWwindow; +struct SDL_Window; +typedef union SDL_Event SDL_Event; +#endif // CIMGUI_DEFINE_ENUMS_AND_STRUCTS + +#ifndef CIMGUI_DEFINE_ENUMS_AND_STRUCTS +typedef struct ImGuiTextFilter::ImGuiTextRange ImGuiTextRange; +typedef ImStb::STB_TexteditState STB_TexteditState; +typedef ImChunkStream ImChunkStream_ImGuiTableSettings; +typedef ImChunkStream ImChunkStream_ImGuiWindowSettings; +typedef ImPool ImPool_ImGuiMultiSelectState; +typedef ImPool ImPool_ImGuiTabBar; +typedef ImPool ImPool_ImGuiTable; +typedef ImSpan ImSpan_ImGuiTableCellData; +typedef ImSpan ImSpan_ImGuiTableColumn; +typedef ImSpan ImSpan_ImGuiTableColumnIdx; +typedef ImVector ImVector_ImDrawChannel; +typedef ImVector ImVector_ImDrawCmd; +typedef ImVector ImVector_ImDrawIdx; +typedef ImVector ImVector_ImDrawListPtr; +typedef ImVector ImVector_ImDrawVert; +typedef ImVector ImVector_ImFontPtr; +typedef ImVector ImVector_ImFontAtlasCustomRect; +typedef ImVector ImVector_ImFontConfig; +typedef ImVector ImVector_ImFontGlyph; +typedef ImVector ImVector_ImGuiColorMod; +typedef ImVector ImVector_ImGuiContextHook; +typedef ImVector ImVector_ImGuiDockNodeSettings; +typedef ImVector ImVector_ImGuiDockRequest; +typedef ImVector ImVector_ImGuiFocusScopeData; +typedef ImVector ImVector_ImGuiGroupData; +typedef ImVector ImVector_ImGuiID; +typedef ImVector ImVector_ImGuiInputEvent; +typedef ImVector ImVector_ImGuiItemFlags; +typedef ImVector ImVector_ImGuiKeyRoutingData; +typedef ImVector ImVector_ImGuiListClipperData; +typedef ImVector ImVector_ImGuiListClipperRange; +typedef ImVector ImVector_ImGuiMultiSelectTempData; +typedef ImVector ImVector_ImGuiOldColumnData; +typedef ImVector ImVector_ImGuiOldColumns; +typedef ImVector ImVector_ImGuiPlatformMonitor; +typedef ImVector ImVector_ImGuiPopupData; +typedef ImVector ImVector_ImGuiPtrOrIndex; +typedef ImVector ImVector_ImGuiSelectionRequest; +typedef ImVector ImVector_ImGuiSettingsHandler; +typedef ImVector ImVector_ImGuiShrinkWidthItem; +typedef ImVector ImVector_ImGuiStackLevelInfo; +typedef ImVector ImVector_ImGuiStoragePair; +typedef ImVector ImVector_ImGuiStyleMod; +typedef ImVector ImVector_ImGuiTabItem; +typedef ImVector ImVector_ImGuiTableColumnSortSpecs; +typedef ImVector ImVector_ImGuiTableHeaderData; +typedef ImVector ImVector_ImGuiTableInstanceData; +typedef ImVector ImVector_ImGuiTableTempData; +typedef ImVector ImVector_ImGuiTextRange; +typedef ImVector ImVector_ImGuiTreeNodeStackData; +typedef ImVector ImVector_ImGuiViewportPtr; +typedef ImVector ImVector_ImGuiViewportPPtr; +typedef ImVector ImVector_ImGuiWindowPtr; +typedef ImVector ImVector_ImGuiWindowStackData; +typedef ImVector ImVector_ImTextureID; +typedef ImVector ImVector_ImU16; +typedef ImVector ImVector_ImU32; +typedef ImVector ImVector_ImU8; +typedef ImVector ImVector_ImVec2; +typedef ImVector ImVector_ImVec4; +typedef ImVector ImVector_ImWchar; +typedef ImVector ImVector_char; +typedef ImVector ImVector_const_charPtr; +typedef ImVector ImVector_float; +typedef ImVector ImVector_int; +typedef ImVector ImVector_unsigned_char; +#endif //CIMGUI_DEFINE_ENUMS_AND_STRUCTS +CIMGUI_API ImVec2* ImVec2_ImVec2_Nil(void); +CIMGUI_API void ImVec2_destroy(ImVec2* self); +CIMGUI_API ImVec2* ImVec2_ImVec2_Float(float _x,float _y); +CIMGUI_API ImVec4* ImVec4_ImVec4_Nil(void); +CIMGUI_API void ImVec4_destroy(ImVec4* self); +CIMGUI_API ImVec4* ImVec4_ImVec4_Float(float _x,float _y,float _z,float _w); +CIMGUI_API ImGuiContext* igCreateContext(ImFontAtlas* shared_font_atlas); +CIMGUI_API void igDestroyContext(ImGuiContext* ctx); +CIMGUI_API ImGuiContext* igGetCurrentContext(void); +CIMGUI_API void igSetCurrentContext(ImGuiContext* ctx); +CIMGUI_API ImGuiIO* igGetIO_Nil(void); +CIMGUI_API ImGuiPlatformIO* igGetPlatformIO_Nil(void); +CIMGUI_API ImGuiStyle* igGetStyle(void); +CIMGUI_API void igNewFrame(void); +CIMGUI_API void igEndFrame(void); +CIMGUI_API void igRender(void); +CIMGUI_API ImDrawData* igGetDrawData(void); +CIMGUI_API void igShowDemoWindow(bool* p_open); +CIMGUI_API void igShowMetricsWindow(bool* p_open); +CIMGUI_API void igShowDebugLogWindow(bool* p_open); +CIMGUI_API void igShowIDStackToolWindow(bool* p_open); +CIMGUI_API void igShowAboutWindow(bool* p_open); +CIMGUI_API void igShowStyleEditor(ImGuiStyle* ref); +CIMGUI_API bool igShowStyleSelector(const char* label); +CIMGUI_API void igShowFontSelector(const char* label); +CIMGUI_API void igShowUserGuide(void); +CIMGUI_API const char* igGetVersion(void); +CIMGUI_API void igStyleColorsDark(ImGuiStyle* dst); +CIMGUI_API void igStyleColorsLight(ImGuiStyle* dst); +CIMGUI_API void igStyleColorsClassic(ImGuiStyle* dst); +CIMGUI_API bool igBegin(const char* name,bool* p_open,ImGuiWindowFlags flags); +CIMGUI_API void igEnd(void); +CIMGUI_API bool igBeginChild_Str(const char* str_id,const ImVec2 size,ImGuiChildFlags child_flags,ImGuiWindowFlags window_flags); +CIMGUI_API bool igBeginChild_ID(ImGuiID id,const ImVec2 size,ImGuiChildFlags child_flags,ImGuiWindowFlags window_flags); +CIMGUI_API void igEndChild(void); +CIMGUI_API bool igIsWindowAppearing(void); +CIMGUI_API bool igIsWindowCollapsed(void); +CIMGUI_API bool igIsWindowFocused(ImGuiFocusedFlags flags); +CIMGUI_API bool igIsWindowHovered(ImGuiHoveredFlags flags); +CIMGUI_API ImDrawList* igGetWindowDrawList(void); +CIMGUI_API float igGetWindowDpiScale(void); +CIMGUI_API void igGetWindowPos(ImVec2 *pOut); +CIMGUI_API void igGetWindowSize(ImVec2 *pOut); +CIMGUI_API float igGetWindowWidth(void); +CIMGUI_API float igGetWindowHeight(void); +CIMGUI_API ImGuiViewport* igGetWindowViewport(void); +CIMGUI_API void igSetNextWindowPos(const ImVec2 pos,ImGuiCond cond,const ImVec2 pivot); +CIMGUI_API void igSetNextWindowSize(const ImVec2 size,ImGuiCond cond); +CIMGUI_API void igSetNextWindowSizeConstraints(const ImVec2 size_min,const ImVec2 size_max,ImGuiSizeCallback custom_callback,void* custom_callback_data); +CIMGUI_API void igSetNextWindowContentSize(const ImVec2 size); +CIMGUI_API void igSetNextWindowCollapsed(bool collapsed,ImGuiCond cond); +CIMGUI_API void igSetNextWindowFocus(void); +CIMGUI_API void igSetNextWindowScroll(const ImVec2 scroll); +CIMGUI_API void igSetNextWindowBgAlpha(float alpha); +CIMGUI_API void igSetNextWindowViewport(ImGuiID viewport_id); +CIMGUI_API void igSetWindowPos_Vec2(const ImVec2 pos,ImGuiCond cond); +CIMGUI_API void igSetWindowSize_Vec2(const ImVec2 size,ImGuiCond cond); +CIMGUI_API void igSetWindowCollapsed_Bool(bool collapsed,ImGuiCond cond); +CIMGUI_API void igSetWindowFocus_Nil(void); +CIMGUI_API void igSetWindowFontScale(float scale); +CIMGUI_API void igSetWindowPos_Str(const char* name,const ImVec2 pos,ImGuiCond cond); +CIMGUI_API void igSetWindowSize_Str(const char* name,const ImVec2 size,ImGuiCond cond); +CIMGUI_API void igSetWindowCollapsed_Str(const char* name,bool collapsed,ImGuiCond cond); +CIMGUI_API void igSetWindowFocus_Str(const char* name); +CIMGUI_API float igGetScrollX(void); +CIMGUI_API float igGetScrollY(void); +CIMGUI_API void igSetScrollX_Float(float scroll_x); +CIMGUI_API void igSetScrollY_Float(float scroll_y); +CIMGUI_API float igGetScrollMaxX(void); +CIMGUI_API float igGetScrollMaxY(void); +CIMGUI_API void igSetScrollHereX(float center_x_ratio); +CIMGUI_API void igSetScrollHereY(float center_y_ratio); +CIMGUI_API void igSetScrollFromPosX_Float(float local_x,float center_x_ratio); +CIMGUI_API void igSetScrollFromPosY_Float(float local_y,float center_y_ratio); +CIMGUI_API void igPushFont(ImFont* font); +CIMGUI_API void igPopFont(void); +CIMGUI_API void igPushStyleColor_U32(ImGuiCol idx,ImU32 col); +CIMGUI_API void igPushStyleColor_Vec4(ImGuiCol idx,const ImVec4 col); +CIMGUI_API void igPopStyleColor(int count); +CIMGUI_API void igPushStyleVar_Float(ImGuiStyleVar idx,float val); +CIMGUI_API void igPushStyleVar_Vec2(ImGuiStyleVar idx,const ImVec2 val); +CIMGUI_API void igPushStyleVarX(ImGuiStyleVar idx,float val_x); +CIMGUI_API void igPushStyleVarY(ImGuiStyleVar idx,float val_y); +CIMGUI_API void igPopStyleVar(int count); +CIMGUI_API void igPushItemFlag(ImGuiItemFlags option,bool enabled); +CIMGUI_API void igPopItemFlag(void); +CIMGUI_API void igPushItemWidth(float item_width); +CIMGUI_API void igPopItemWidth(void); +CIMGUI_API void igSetNextItemWidth(float item_width); +CIMGUI_API float igCalcItemWidth(void); +CIMGUI_API void igPushTextWrapPos(float wrap_local_pos_x); +CIMGUI_API void igPopTextWrapPos(void); +CIMGUI_API ImFont* igGetFont(void); +CIMGUI_API float igGetFontSize(void); +CIMGUI_API void igGetFontTexUvWhitePixel(ImVec2 *pOut); +CIMGUI_API ImU32 igGetColorU32_Col(ImGuiCol idx,float alpha_mul); +CIMGUI_API ImU32 igGetColorU32_Vec4(const ImVec4 col); +CIMGUI_API ImU32 igGetColorU32_U32(ImU32 col,float alpha_mul); +CIMGUI_API const ImVec4* igGetStyleColorVec4(ImGuiCol idx); +CIMGUI_API void igGetCursorScreenPos(ImVec2 *pOut); +CIMGUI_API void igSetCursorScreenPos(const ImVec2 pos); +CIMGUI_API void igGetContentRegionAvail(ImVec2 *pOut); +CIMGUI_API void igGetCursorPos(ImVec2 *pOut); +CIMGUI_API float igGetCursorPosX(void); +CIMGUI_API float igGetCursorPosY(void); +CIMGUI_API void igSetCursorPos(const ImVec2 local_pos); +CIMGUI_API void igSetCursorPosX(float local_x); +CIMGUI_API void igSetCursorPosY(float local_y); +CIMGUI_API void igGetCursorStartPos(ImVec2 *pOut); +CIMGUI_API void igSeparator(void); +CIMGUI_API void igSameLine(float offset_from_start_x,float spacing); +CIMGUI_API void igNewLine(void); +CIMGUI_API void igSpacing(void); +CIMGUI_API void igDummy(const ImVec2 size); +CIMGUI_API void igIndent(float indent_w); +CIMGUI_API void igUnindent(float indent_w); +CIMGUI_API void igBeginGroup(void); +CIMGUI_API void igEndGroup(void); +CIMGUI_API void igAlignTextToFramePadding(void); +CIMGUI_API float igGetTextLineHeight(void); +CIMGUI_API float igGetTextLineHeightWithSpacing(void); +CIMGUI_API float igGetFrameHeight(void); +CIMGUI_API float igGetFrameHeightWithSpacing(void); +CIMGUI_API void igPushID_Str(const char* str_id); +CIMGUI_API void igPushID_StrStr(const char* str_id_begin,const char* str_id_end); +CIMGUI_API void igPushID_Ptr(const void* ptr_id); +CIMGUI_API void igPushID_Int(int int_id); +CIMGUI_API void igPopID(void); +CIMGUI_API ImGuiID igGetID_Str(const char* str_id); +CIMGUI_API ImGuiID igGetID_StrStr(const char* str_id_begin,const char* str_id_end); +CIMGUI_API ImGuiID igGetID_Ptr(const void* ptr_id); +CIMGUI_API ImGuiID igGetID_Int(int int_id); +CIMGUI_API void igTextUnformatted(const char* text,const char* text_end); +CIMGUI_API void igText(const char* fmt,...); +CIMGUI_API void igTextV(const char* fmt,va_list args); +CIMGUI_API void igTextColored(const ImVec4 col,const char* fmt,...); +CIMGUI_API void igTextColoredV(const ImVec4 col,const char* fmt,va_list args); +CIMGUI_API void igTextDisabled(const char* fmt,...); +CIMGUI_API void igTextDisabledV(const char* fmt,va_list args); +CIMGUI_API void igTextWrapped(const char* fmt,...); +CIMGUI_API void igTextWrappedV(const char* fmt,va_list args); +CIMGUI_API void igLabelText(const char* label,const char* fmt,...); +CIMGUI_API void igLabelTextV(const char* label,const char* fmt,va_list args); +CIMGUI_API void igBulletText(const char* fmt,...); +CIMGUI_API void igBulletTextV(const char* fmt,va_list args); +CIMGUI_API void igSeparatorText(const char* label); +CIMGUI_API bool igButton(const char* label,const ImVec2 size); +CIMGUI_API bool igSmallButton(const char* label); +CIMGUI_API bool igInvisibleButton(const char* str_id,const ImVec2 size,ImGuiButtonFlags flags); +CIMGUI_API bool igArrowButton(const char* str_id,ImGuiDir dir); +CIMGUI_API bool igCheckbox(const char* label,bool* v); +CIMGUI_API bool igCheckboxFlags_IntPtr(const char* label,int* flags,int flags_value); +CIMGUI_API bool igCheckboxFlags_UintPtr(const char* label,unsigned int* flags,unsigned int flags_value); +CIMGUI_API bool igRadioButton_Bool(const char* label,bool active); +CIMGUI_API bool igRadioButton_IntPtr(const char* label,int* v,int v_button); +CIMGUI_API void igProgressBar(float fraction,const ImVec2 size_arg,const char* overlay); +CIMGUI_API void igBullet(void); +CIMGUI_API bool igTextLink(const char* label); +CIMGUI_API void igTextLinkOpenURL(const char* label,const char* url); +CIMGUI_API void igImage(ImTextureID user_texture_id,const ImVec2 image_size,const ImVec2 uv0,const ImVec2 uv1); +CIMGUI_API void igImageWithBg(ImTextureID user_texture_id,const ImVec2 image_size,const ImVec2 uv0,const ImVec2 uv1,const ImVec4 bg_col,const ImVec4 tint_col); +CIMGUI_API bool igImageButton(const char* str_id,ImTextureID user_texture_id,const ImVec2 image_size,const ImVec2 uv0,const ImVec2 uv1,const ImVec4 bg_col,const ImVec4 tint_col); +CIMGUI_API bool igBeginCombo(const char* label,const char* preview_value,ImGuiComboFlags flags); +CIMGUI_API void igEndCombo(void); +CIMGUI_API bool igCombo_Str_arr(const char* label,int* current_item,const char* const items[],int items_count,int popup_max_height_in_items); +CIMGUI_API bool igCombo_Str(const char* label,int* current_item,const char* items_separated_by_zeros,int popup_max_height_in_items); +CIMGUI_API bool igCombo_FnStrPtr(const char* label,int* current_item,const char*(*getter)(void* user_data,int idx),void* user_data,int items_count,int popup_max_height_in_items); +CIMGUI_API bool igDragFloat(const char* label,float* v,float v_speed,float v_min,float v_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igDragFloat2(const char* label,float v[2],float v_speed,float v_min,float v_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igDragFloat3(const char* label,float v[3],float v_speed,float v_min,float v_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igDragFloat4(const char* label,float v[4],float v_speed,float v_min,float v_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igDragFloatRange2(const char* label,float* v_current_min,float* v_current_max,float v_speed,float v_min,float v_max,const char* format,const char* format_max,ImGuiSliderFlags flags); +CIMGUI_API bool igDragInt(const char* label,int* v,float v_speed,int v_min,int v_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igDragInt2(const char* label,int v[2],float v_speed,int v_min,int v_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igDragInt3(const char* label,int v[3],float v_speed,int v_min,int v_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igDragInt4(const char* label,int v[4],float v_speed,int v_min,int v_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igDragIntRange2(const char* label,int* v_current_min,int* v_current_max,float v_speed,int v_min,int v_max,const char* format,const char* format_max,ImGuiSliderFlags flags); +CIMGUI_API bool igDragScalar(const char* label,ImGuiDataType data_type,void* p_data,float v_speed,const void* p_min,const void* p_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igDragScalarN(const char* label,ImGuiDataType data_type,void* p_data,int components,float v_speed,const void* p_min,const void* p_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igSliderFloat(const char* label,float* v,float v_min,float v_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igSliderFloat2(const char* label,float v[2],float v_min,float v_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igSliderFloat3(const char* label,float v[3],float v_min,float v_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igSliderFloat4(const char* label,float v[4],float v_min,float v_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igSliderAngle(const char* label,float* v_rad,float v_degrees_min,float v_degrees_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igSliderInt(const char* label,int* v,int v_min,int v_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igSliderInt2(const char* label,int v[2],int v_min,int v_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igSliderInt3(const char* label,int v[3],int v_min,int v_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igSliderInt4(const char* label,int v[4],int v_min,int v_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igSliderScalar(const char* label,ImGuiDataType data_type,void* p_data,const void* p_min,const void* p_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igSliderScalarN(const char* label,ImGuiDataType data_type,void* p_data,int components,const void* p_min,const void* p_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igVSliderFloat(const char* label,const ImVec2 size,float* v,float v_min,float v_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igVSliderInt(const char* label,const ImVec2 size,int* v,int v_min,int v_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igVSliderScalar(const char* label,const ImVec2 size,ImGuiDataType data_type,void* p_data,const void* p_min,const void* p_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igInputText(const char* label,char* buf,size_t buf_size,ImGuiInputTextFlags flags,ImGuiInputTextCallback callback,void* user_data); +CIMGUI_API bool igInputTextMultiline(const char* label,char* buf,size_t buf_size,const ImVec2 size,ImGuiInputTextFlags flags,ImGuiInputTextCallback callback,void* user_data); +CIMGUI_API bool igInputTextWithHint(const char* label,const char* hint,char* buf,size_t buf_size,ImGuiInputTextFlags flags,ImGuiInputTextCallback callback,void* user_data); +CIMGUI_API bool igInputFloat(const char* label,float* v,float step,float step_fast,const char* format,ImGuiInputTextFlags flags); +CIMGUI_API bool igInputFloat2(const char* label,float v[2],const char* format,ImGuiInputTextFlags flags); +CIMGUI_API bool igInputFloat3(const char* label,float v[3],const char* format,ImGuiInputTextFlags flags); +CIMGUI_API bool igInputFloat4(const char* label,float v[4],const char* format,ImGuiInputTextFlags flags); +CIMGUI_API bool igInputInt(const char* label,int* v,int step,int step_fast,ImGuiInputTextFlags flags); +CIMGUI_API bool igInputInt2(const char* label,int v[2],ImGuiInputTextFlags flags); +CIMGUI_API bool igInputInt3(const char* label,int v[3],ImGuiInputTextFlags flags); +CIMGUI_API bool igInputInt4(const char* label,int v[4],ImGuiInputTextFlags flags); +CIMGUI_API bool igInputDouble(const char* label,double* v,double step,double step_fast,const char* format,ImGuiInputTextFlags flags); +CIMGUI_API bool igInputScalar(const char* label,ImGuiDataType data_type,void* p_data,const void* p_step,const void* p_step_fast,const char* format,ImGuiInputTextFlags flags); +CIMGUI_API bool igInputScalarN(const char* label,ImGuiDataType data_type,void* p_data,int components,const void* p_step,const void* p_step_fast,const char* format,ImGuiInputTextFlags flags); +CIMGUI_API bool igColorEdit3(const char* label,float col[3],ImGuiColorEditFlags flags); +CIMGUI_API bool igColorEdit4(const char* label,float col[4],ImGuiColorEditFlags flags); +CIMGUI_API bool igColorPicker3(const char* label,float col[3],ImGuiColorEditFlags flags); +CIMGUI_API bool igColorPicker4(const char* label,float col[4],ImGuiColorEditFlags flags,const float* ref_col); +CIMGUI_API bool igColorButton(const char* desc_id,const ImVec4 col,ImGuiColorEditFlags flags,const ImVec2 size); +CIMGUI_API void igSetColorEditOptions(ImGuiColorEditFlags flags); +CIMGUI_API bool igTreeNode_Str(const char* label); +CIMGUI_API bool igTreeNode_StrStr(const char* str_id,const char* fmt,...); +CIMGUI_API bool igTreeNode_Ptr(const void* ptr_id,const char* fmt,...); +CIMGUI_API bool igTreeNodeV_Str(const char* str_id,const char* fmt,va_list args); +CIMGUI_API bool igTreeNodeV_Ptr(const void* ptr_id,const char* fmt,va_list args); +CIMGUI_API bool igTreeNodeEx_Str(const char* label,ImGuiTreeNodeFlags flags); +CIMGUI_API bool igTreeNodeEx_StrStr(const char* str_id,ImGuiTreeNodeFlags flags,const char* fmt,...); +CIMGUI_API bool igTreeNodeEx_Ptr(const void* ptr_id,ImGuiTreeNodeFlags flags,const char* fmt,...); +CIMGUI_API bool igTreeNodeExV_Str(const char* str_id,ImGuiTreeNodeFlags flags,const char* fmt,va_list args); +CIMGUI_API bool igTreeNodeExV_Ptr(const void* ptr_id,ImGuiTreeNodeFlags flags,const char* fmt,va_list args); +CIMGUI_API void igTreePush_Str(const char* str_id); +CIMGUI_API void igTreePush_Ptr(const void* ptr_id); +CIMGUI_API void igTreePop(void); +CIMGUI_API float igGetTreeNodeToLabelSpacing(void); +CIMGUI_API bool igCollapsingHeader_TreeNodeFlags(const char* label,ImGuiTreeNodeFlags flags); +CIMGUI_API bool igCollapsingHeader_BoolPtr(const char* label,bool* p_visible,ImGuiTreeNodeFlags flags); +CIMGUI_API void igSetNextItemOpen(bool is_open,ImGuiCond cond); +CIMGUI_API void igSetNextItemStorageID(ImGuiID storage_id); +CIMGUI_API bool igSelectable_Bool(const char* label,bool selected,ImGuiSelectableFlags flags,const ImVec2 size); +CIMGUI_API bool igSelectable_BoolPtr(const char* label,bool* p_selected,ImGuiSelectableFlags flags,const ImVec2 size); +CIMGUI_API ImGuiMultiSelectIO* igBeginMultiSelect(ImGuiMultiSelectFlags flags,int selection_size,int items_count); +CIMGUI_API ImGuiMultiSelectIO* igEndMultiSelect(void); +CIMGUI_API void igSetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data); +CIMGUI_API bool igIsItemToggledSelection(void); +CIMGUI_API bool igBeginListBox(const char* label,const ImVec2 size); +CIMGUI_API void igEndListBox(void); +CIMGUI_API bool igListBox_Str_arr(const char* label,int* current_item,const char* const items[],int items_count,int height_in_items); +CIMGUI_API bool igListBox_FnStrPtr(const char* label,int* current_item,const char*(*getter)(void* user_data,int idx),void* user_data,int items_count,int height_in_items); +CIMGUI_API void igPlotLines_FloatPtr(const char* label,const float* values,int values_count,int values_offset,const char* overlay_text,float scale_min,float scale_max,ImVec2 graph_size,int stride); +CIMGUI_API void igPlotLines_FnFloatPtr(const char* label,float(*values_getter)(void* data,int idx),void* data,int values_count,int values_offset,const char* overlay_text,float scale_min,float scale_max,ImVec2 graph_size); +CIMGUI_API void igPlotHistogram_FloatPtr(const char* label,const float* values,int values_count,int values_offset,const char* overlay_text,float scale_min,float scale_max,ImVec2 graph_size,int stride); +CIMGUI_API void igPlotHistogram_FnFloatPtr(const char* label,float(*values_getter)(void* data,int idx),void* data,int values_count,int values_offset,const char* overlay_text,float scale_min,float scale_max,ImVec2 graph_size); +CIMGUI_API void igValue_Bool(const char* prefix,bool b); +CIMGUI_API void igValue_Int(const char* prefix,int v); +CIMGUI_API void igValue_Uint(const char* prefix,unsigned int v); +CIMGUI_API void igValue_Float(const char* prefix,float v,const char* float_format); +CIMGUI_API bool igBeginMenuBar(void); +CIMGUI_API void igEndMenuBar(void); +CIMGUI_API bool igBeginMainMenuBar(void); +CIMGUI_API void igEndMainMenuBar(void); +CIMGUI_API bool igBeginMenu(const char* label,bool enabled); +CIMGUI_API void igEndMenu(void); +CIMGUI_API bool igMenuItem_Bool(const char* label,const char* shortcut,bool selected,bool enabled); +CIMGUI_API bool igMenuItem_BoolPtr(const char* label,const char* shortcut,bool* p_selected,bool enabled); +CIMGUI_API bool igBeginTooltip(void); +CIMGUI_API void igEndTooltip(void); +CIMGUI_API void igSetTooltip(const char* fmt,...); +CIMGUI_API void igSetTooltipV(const char* fmt,va_list args); +CIMGUI_API bool igBeginItemTooltip(void); +CIMGUI_API void igSetItemTooltip(const char* fmt,...); +CIMGUI_API void igSetItemTooltipV(const char* fmt,va_list args); +CIMGUI_API bool igBeginPopup(const char* str_id,ImGuiWindowFlags flags); +CIMGUI_API bool igBeginPopupModal(const char* name,bool* p_open,ImGuiWindowFlags flags); +CIMGUI_API void igEndPopup(void); +CIMGUI_API void igOpenPopup_Str(const char* str_id,ImGuiPopupFlags popup_flags); +CIMGUI_API void igOpenPopup_ID(ImGuiID id,ImGuiPopupFlags popup_flags); +CIMGUI_API void igOpenPopupOnItemClick(const char* str_id,ImGuiPopupFlags popup_flags); +CIMGUI_API void igCloseCurrentPopup(void); +CIMGUI_API bool igBeginPopupContextItem(const char* str_id,ImGuiPopupFlags popup_flags); +CIMGUI_API bool igBeginPopupContextWindow(const char* str_id,ImGuiPopupFlags popup_flags); +CIMGUI_API bool igBeginPopupContextVoid(const char* str_id,ImGuiPopupFlags popup_flags); +CIMGUI_API bool igIsPopupOpen_Str(const char* str_id,ImGuiPopupFlags flags); +CIMGUI_API bool igBeginTable(const char* str_id,int columns,ImGuiTableFlags flags,const ImVec2 outer_size,float inner_width); +CIMGUI_API void igEndTable(void); +CIMGUI_API void igTableNextRow(ImGuiTableRowFlags row_flags,float min_row_height); +CIMGUI_API bool igTableNextColumn(void); +CIMGUI_API bool igTableSetColumnIndex(int column_n); +CIMGUI_API void igTableSetupColumn(const char* label,ImGuiTableColumnFlags flags,float init_width_or_weight,ImGuiID user_id); +CIMGUI_API void igTableSetupScrollFreeze(int cols,int rows); +CIMGUI_API void igTableHeader(const char* label); +CIMGUI_API void igTableHeadersRow(void); +CIMGUI_API void igTableAngledHeadersRow(void); +CIMGUI_API ImGuiTableSortSpecs* igTableGetSortSpecs(void); +CIMGUI_API int igTableGetColumnCount(void); +CIMGUI_API int igTableGetColumnIndex(void); +CIMGUI_API int igTableGetRowIndex(void); +CIMGUI_API const char* igTableGetColumnName_Int(int column_n); +CIMGUI_API ImGuiTableColumnFlags igTableGetColumnFlags(int column_n); +CIMGUI_API void igTableSetColumnEnabled(int column_n,bool v); +CIMGUI_API int igTableGetHoveredColumn(void); +CIMGUI_API void igTableSetBgColor(ImGuiTableBgTarget target,ImU32 color,int column_n); +CIMGUI_API void igColumns(int count,const char* id,bool borders); +CIMGUI_API void igNextColumn(void); +CIMGUI_API int igGetColumnIndex(void); +CIMGUI_API float igGetColumnWidth(int column_index); +CIMGUI_API void igSetColumnWidth(int column_index,float width); +CIMGUI_API float igGetColumnOffset(int column_index); +CIMGUI_API void igSetColumnOffset(int column_index,float offset_x); +CIMGUI_API int igGetColumnsCount(void); +CIMGUI_API bool igBeginTabBar(const char* str_id,ImGuiTabBarFlags flags); +CIMGUI_API void igEndTabBar(void); +CIMGUI_API bool igBeginTabItem(const char* label,bool* p_open,ImGuiTabItemFlags flags); +CIMGUI_API void igEndTabItem(void); +CIMGUI_API bool igTabItemButton(const char* label,ImGuiTabItemFlags flags); +CIMGUI_API void igSetTabItemClosed(const char* tab_or_docked_window_label); +CIMGUI_API ImGuiID igDockSpace(ImGuiID dockspace_id,const ImVec2 size,ImGuiDockNodeFlags flags,const ImGuiWindowClass* window_class); +CIMGUI_API ImGuiID igDockSpaceOverViewport(ImGuiID dockspace_id,const ImGuiViewport* viewport,ImGuiDockNodeFlags flags,const ImGuiWindowClass* window_class); +CIMGUI_API void igSetNextWindowDockID(ImGuiID dock_id,ImGuiCond cond); +CIMGUI_API void igSetNextWindowClass(const ImGuiWindowClass* window_class); +CIMGUI_API ImGuiID igGetWindowDockID(void); +CIMGUI_API bool igIsWindowDocked(void); +CIMGUI_API void igLogToTTY(int auto_open_depth); +CIMGUI_API void igLogToFile(int auto_open_depth,const char* filename); +CIMGUI_API void igLogToClipboard(int auto_open_depth); +CIMGUI_API void igLogFinish(void); +CIMGUI_API void igLogButtons(void); +CIMGUI_API void igLogTextV(const char* fmt,va_list args); +CIMGUI_API bool igBeginDragDropSource(ImGuiDragDropFlags flags); +CIMGUI_API bool igSetDragDropPayload(const char* type,const void* data,size_t sz,ImGuiCond cond); +CIMGUI_API void igEndDragDropSource(void); +CIMGUI_API bool igBeginDragDropTarget(void); +CIMGUI_API const ImGuiPayload* igAcceptDragDropPayload(const char* type,ImGuiDragDropFlags flags); +CIMGUI_API void igEndDragDropTarget(void); +CIMGUI_API const ImGuiPayload* igGetDragDropPayload(void); +CIMGUI_API void igBeginDisabled(bool disabled); +CIMGUI_API void igEndDisabled(void); +CIMGUI_API void igPushClipRect(const ImVec2 clip_rect_min,const ImVec2 clip_rect_max,bool intersect_with_current_clip_rect); +CIMGUI_API void igPopClipRect(void); +CIMGUI_API void igSetItemDefaultFocus(void); +CIMGUI_API void igSetKeyboardFocusHere(int offset); +CIMGUI_API void igSetNavCursorVisible(bool visible); +CIMGUI_API void igSetNextItemAllowOverlap(void); +CIMGUI_API bool igIsItemHovered(ImGuiHoveredFlags flags); +CIMGUI_API bool igIsItemActive(void); +CIMGUI_API bool igIsItemFocused(void); +CIMGUI_API bool igIsItemClicked(ImGuiMouseButton mouse_button); +CIMGUI_API bool igIsItemVisible(void); +CIMGUI_API bool igIsItemEdited(void); +CIMGUI_API bool igIsItemActivated(void); +CIMGUI_API bool igIsItemDeactivated(void); +CIMGUI_API bool igIsItemDeactivatedAfterEdit(void); +CIMGUI_API bool igIsItemToggledOpen(void); +CIMGUI_API bool igIsAnyItemHovered(void); +CIMGUI_API bool igIsAnyItemActive(void); +CIMGUI_API bool igIsAnyItemFocused(void); +CIMGUI_API ImGuiID igGetItemID(void); +CIMGUI_API void igGetItemRectMin(ImVec2 *pOut); +CIMGUI_API void igGetItemRectMax(ImVec2 *pOut); +CIMGUI_API void igGetItemRectSize(ImVec2 *pOut); +CIMGUI_API ImGuiViewport* igGetMainViewport(void); +CIMGUI_API ImDrawList* igGetBackgroundDrawList(ImGuiViewport* viewport); +CIMGUI_API ImDrawList* igGetForegroundDrawList_ViewportPtr(ImGuiViewport* viewport); +CIMGUI_API bool igIsRectVisible_Nil(const ImVec2 size); +CIMGUI_API bool igIsRectVisible_Vec2(const ImVec2 rect_min,const ImVec2 rect_max); +CIMGUI_API double igGetTime(void); +CIMGUI_API int igGetFrameCount(void); +CIMGUI_API ImDrawListSharedData* igGetDrawListSharedData(void); +CIMGUI_API const char* igGetStyleColorName(ImGuiCol idx); +CIMGUI_API void igSetStateStorage(ImGuiStorage* storage); +CIMGUI_API ImGuiStorage* igGetStateStorage(void); +CIMGUI_API void igCalcTextSize(ImVec2 *pOut,const char* text,const char* text_end,bool hide_text_after_double_hash,float wrap_width); +CIMGUI_API void igColorConvertU32ToFloat4(ImVec4 *pOut,ImU32 in); +CIMGUI_API ImU32 igColorConvertFloat4ToU32(const ImVec4 in); +CIMGUI_API void igColorConvertRGBtoHSV(float r,float g,float b,float* out_h,float* out_s,float* out_v); +CIMGUI_API void igColorConvertHSVtoRGB(float h,float s,float v,float* out_r,float* out_g,float* out_b); +CIMGUI_API bool igIsKeyDown_Nil(ImGuiKey key); +CIMGUI_API bool igIsKeyPressed_Bool(ImGuiKey key,bool repeat); +CIMGUI_API bool igIsKeyReleased_Nil(ImGuiKey key); +CIMGUI_API bool igIsKeyChordPressed_Nil(ImGuiKeyChord key_chord); +CIMGUI_API int igGetKeyPressedAmount(ImGuiKey key,float repeat_delay,float rate); +CIMGUI_API const char* igGetKeyName(ImGuiKey key); +CIMGUI_API void igSetNextFrameWantCaptureKeyboard(bool want_capture_keyboard); +CIMGUI_API bool igShortcut_Nil(ImGuiKeyChord key_chord,ImGuiInputFlags flags); +CIMGUI_API void igSetNextItemShortcut(ImGuiKeyChord key_chord,ImGuiInputFlags flags); +CIMGUI_API void igSetItemKeyOwner_Nil(ImGuiKey key); +CIMGUI_API bool igIsMouseDown_Nil(ImGuiMouseButton button); +CIMGUI_API bool igIsMouseClicked_Bool(ImGuiMouseButton button,bool repeat); +CIMGUI_API bool igIsMouseReleased_Nil(ImGuiMouseButton button); +CIMGUI_API bool igIsMouseDoubleClicked_Nil(ImGuiMouseButton button); +CIMGUI_API bool igIsMouseReleasedWithDelay(ImGuiMouseButton button,float delay); +CIMGUI_API int igGetMouseClickedCount(ImGuiMouseButton button); +CIMGUI_API bool igIsMouseHoveringRect(const ImVec2 r_min,const ImVec2 r_max,bool clip); +CIMGUI_API bool igIsMousePosValid(const ImVec2* mouse_pos); +CIMGUI_API bool igIsAnyMouseDown(void); +CIMGUI_API void igGetMousePos(ImVec2 *pOut); +CIMGUI_API void igGetMousePosOnOpeningCurrentPopup(ImVec2 *pOut); +CIMGUI_API bool igIsMouseDragging(ImGuiMouseButton button,float lock_threshold); +CIMGUI_API void igGetMouseDragDelta(ImVec2 *pOut,ImGuiMouseButton button,float lock_threshold); +CIMGUI_API void igResetMouseDragDelta(ImGuiMouseButton button); +CIMGUI_API ImGuiMouseCursor igGetMouseCursor(void); +CIMGUI_API void igSetMouseCursor(ImGuiMouseCursor cursor_type); +CIMGUI_API void igSetNextFrameWantCaptureMouse(bool want_capture_mouse); +CIMGUI_API const char* igGetClipboardText(void); +CIMGUI_API void igSetClipboardText(const char* text); +CIMGUI_API void igLoadIniSettingsFromDisk(const char* ini_filename); +CIMGUI_API void igLoadIniSettingsFromMemory(const char* ini_data,size_t ini_size); +CIMGUI_API void igSaveIniSettingsToDisk(const char* ini_filename); +CIMGUI_API const char* igSaveIniSettingsToMemory(size_t* out_ini_size); +CIMGUI_API void igDebugTextEncoding(const char* text); +CIMGUI_API void igDebugFlashStyleColor(ImGuiCol idx); +CIMGUI_API void igDebugStartItemPicker(void); +CIMGUI_API bool igDebugCheckVersionAndDataLayout(const char* version_str,size_t sz_io,size_t sz_style,size_t sz_vec2,size_t sz_vec4,size_t sz_drawvert,size_t sz_drawidx); +CIMGUI_API void igDebugLog(const char* fmt,...); +CIMGUI_API void igDebugLogV(const char* fmt,va_list args); +CIMGUI_API void igSetAllocatorFunctions(ImGuiMemAllocFunc alloc_func,ImGuiMemFreeFunc free_func,void* user_data); +CIMGUI_API void igGetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func,ImGuiMemFreeFunc* p_free_func,void** p_user_data); +CIMGUI_API void* igMemAlloc(size_t size); +CIMGUI_API void igMemFree(void* ptr); +CIMGUI_API void igUpdatePlatformWindows(void); +CIMGUI_API void igRenderPlatformWindowsDefault(void* platform_render_arg,void* renderer_render_arg); +CIMGUI_API void igDestroyPlatformWindows(void); +CIMGUI_API ImGuiViewport* igFindViewportByID(ImGuiID id); +CIMGUI_API ImGuiViewport* igFindViewportByPlatformHandle(void* platform_handle); +CIMGUI_API ImGuiTableSortSpecs* ImGuiTableSortSpecs_ImGuiTableSortSpecs(void); +CIMGUI_API void ImGuiTableSortSpecs_destroy(ImGuiTableSortSpecs* self); +CIMGUI_API ImGuiTableColumnSortSpecs* ImGuiTableColumnSortSpecs_ImGuiTableColumnSortSpecs(void); +CIMGUI_API void ImGuiTableColumnSortSpecs_destroy(ImGuiTableColumnSortSpecs* self); +CIMGUI_API ImGuiStyle* ImGuiStyle_ImGuiStyle(void); +CIMGUI_API void ImGuiStyle_destroy(ImGuiStyle* self); +CIMGUI_API void ImGuiStyle_ScaleAllSizes(ImGuiStyle* self,float scale_factor); +CIMGUI_API void ImGuiIO_AddKeyEvent(ImGuiIO* self,ImGuiKey key,bool down); +CIMGUI_API void ImGuiIO_AddKeyAnalogEvent(ImGuiIO* self,ImGuiKey key,bool down,float v); +CIMGUI_API void ImGuiIO_AddMousePosEvent(ImGuiIO* self,float x,float y); +CIMGUI_API void ImGuiIO_AddMouseButtonEvent(ImGuiIO* self,int button,bool down); +CIMGUI_API void ImGuiIO_AddMouseWheelEvent(ImGuiIO* self,float wheel_x,float wheel_y); +CIMGUI_API void ImGuiIO_AddMouseSourceEvent(ImGuiIO* self,ImGuiMouseSource source); +CIMGUI_API void ImGuiIO_AddMouseViewportEvent(ImGuiIO* self,ImGuiID id); +CIMGUI_API void ImGuiIO_AddFocusEvent(ImGuiIO* self,bool focused); +CIMGUI_API void ImGuiIO_AddInputCharacter(ImGuiIO* self,unsigned int c); +CIMGUI_API void ImGuiIO_AddInputCharacterUTF16(ImGuiIO* self,ImWchar16 c); +CIMGUI_API void ImGuiIO_AddInputCharactersUTF8(ImGuiIO* self,const char* str); +CIMGUI_API void ImGuiIO_SetKeyEventNativeData(ImGuiIO* self,ImGuiKey key,int native_keycode,int native_scancode,int native_legacy_index); +CIMGUI_API void ImGuiIO_SetAppAcceptingEvents(ImGuiIO* self,bool accepting_events); +CIMGUI_API void ImGuiIO_ClearEventsQueue(ImGuiIO* self); +CIMGUI_API void ImGuiIO_ClearInputKeys(ImGuiIO* self); +CIMGUI_API void ImGuiIO_ClearInputMouse(ImGuiIO* self); +CIMGUI_API ImGuiIO* ImGuiIO_ImGuiIO(void); +CIMGUI_API void ImGuiIO_destroy(ImGuiIO* self); +CIMGUI_API ImGuiInputTextCallbackData* ImGuiInputTextCallbackData_ImGuiInputTextCallbackData(void); +CIMGUI_API void ImGuiInputTextCallbackData_destroy(ImGuiInputTextCallbackData* self); +CIMGUI_API void ImGuiInputTextCallbackData_DeleteChars(ImGuiInputTextCallbackData* self,int pos,int bytes_count); +CIMGUI_API void ImGuiInputTextCallbackData_InsertChars(ImGuiInputTextCallbackData* self,int pos,const char* text,const char* text_end); +CIMGUI_API void ImGuiInputTextCallbackData_SelectAll(ImGuiInputTextCallbackData* self); +CIMGUI_API void ImGuiInputTextCallbackData_ClearSelection(ImGuiInputTextCallbackData* self); +CIMGUI_API bool ImGuiInputTextCallbackData_HasSelection(ImGuiInputTextCallbackData* self); +CIMGUI_API ImGuiWindowClass* ImGuiWindowClass_ImGuiWindowClass(void); +CIMGUI_API void ImGuiWindowClass_destroy(ImGuiWindowClass* self); +CIMGUI_API ImGuiPayload* ImGuiPayload_ImGuiPayload(void); +CIMGUI_API void ImGuiPayload_destroy(ImGuiPayload* self); +CIMGUI_API void ImGuiPayload_Clear(ImGuiPayload* self); +CIMGUI_API bool ImGuiPayload_IsDataType(ImGuiPayload* self,const char* type); +CIMGUI_API bool ImGuiPayload_IsPreview(ImGuiPayload* self); +CIMGUI_API bool ImGuiPayload_IsDelivery(ImGuiPayload* self); +CIMGUI_API ImGuiOnceUponAFrame* ImGuiOnceUponAFrame_ImGuiOnceUponAFrame(void); +CIMGUI_API void ImGuiOnceUponAFrame_destroy(ImGuiOnceUponAFrame* self); +CIMGUI_API ImGuiTextFilter* ImGuiTextFilter_ImGuiTextFilter(const char* default_filter); +CIMGUI_API void ImGuiTextFilter_destroy(ImGuiTextFilter* self); +CIMGUI_API bool ImGuiTextFilter_Draw(ImGuiTextFilter* self,const char* label,float width); +CIMGUI_API bool ImGuiTextFilter_PassFilter(ImGuiTextFilter* self,const char* text,const char* text_end); +CIMGUI_API void ImGuiTextFilter_Build(ImGuiTextFilter* self); +CIMGUI_API void ImGuiTextFilter_Clear(ImGuiTextFilter* self); +CIMGUI_API bool ImGuiTextFilter_IsActive(ImGuiTextFilter* self); +CIMGUI_API ImGuiTextRange* ImGuiTextRange_ImGuiTextRange_Nil(void); +CIMGUI_API void ImGuiTextRange_destroy(ImGuiTextRange* self); +CIMGUI_API ImGuiTextRange* ImGuiTextRange_ImGuiTextRange_Str(const char* _b,const char* _e); +CIMGUI_API bool ImGuiTextRange_empty(ImGuiTextRange* self); +CIMGUI_API void ImGuiTextRange_split(ImGuiTextRange* self,char separator,ImVector_ImGuiTextRange* out); +CIMGUI_API ImGuiTextBuffer* ImGuiTextBuffer_ImGuiTextBuffer(void); +CIMGUI_API void ImGuiTextBuffer_destroy(ImGuiTextBuffer* self); +CIMGUI_API const char* ImGuiTextBuffer_begin(ImGuiTextBuffer* self); +CIMGUI_API const char* ImGuiTextBuffer_end(ImGuiTextBuffer* self); +CIMGUI_API int ImGuiTextBuffer_size(ImGuiTextBuffer* self); +CIMGUI_API bool ImGuiTextBuffer_empty(ImGuiTextBuffer* self); +CIMGUI_API void ImGuiTextBuffer_clear(ImGuiTextBuffer* self); +CIMGUI_API void ImGuiTextBuffer_resize(ImGuiTextBuffer* self,int size); +CIMGUI_API void ImGuiTextBuffer_reserve(ImGuiTextBuffer* self,int capacity); +CIMGUI_API const char* ImGuiTextBuffer_c_str(ImGuiTextBuffer* self); +CIMGUI_API void ImGuiTextBuffer_append(ImGuiTextBuffer* self,const char* str,const char* str_end); +CIMGUI_API void ImGuiTextBuffer_appendfv(ImGuiTextBuffer* self,const char* fmt,va_list args); +CIMGUI_API ImGuiStoragePair* ImGuiStoragePair_ImGuiStoragePair_Int(ImGuiID _key,int _val); +CIMGUI_API void ImGuiStoragePair_destroy(ImGuiStoragePair* self); +CIMGUI_API ImGuiStoragePair* ImGuiStoragePair_ImGuiStoragePair_Float(ImGuiID _key,float _val); +CIMGUI_API ImGuiStoragePair* ImGuiStoragePair_ImGuiStoragePair_Ptr(ImGuiID _key,void* _val); +CIMGUI_API void ImGuiStorage_Clear(ImGuiStorage* self); +CIMGUI_API int ImGuiStorage_GetInt(ImGuiStorage* self,ImGuiID key,int default_val); +CIMGUI_API void ImGuiStorage_SetInt(ImGuiStorage* self,ImGuiID key,int val); +CIMGUI_API bool ImGuiStorage_GetBool(ImGuiStorage* self,ImGuiID key,bool default_val); +CIMGUI_API void ImGuiStorage_SetBool(ImGuiStorage* self,ImGuiID key,bool val); +CIMGUI_API float ImGuiStorage_GetFloat(ImGuiStorage* self,ImGuiID key,float default_val); +CIMGUI_API void ImGuiStorage_SetFloat(ImGuiStorage* self,ImGuiID key,float val); +CIMGUI_API void* ImGuiStorage_GetVoidPtr(ImGuiStorage* self,ImGuiID key); +CIMGUI_API void ImGuiStorage_SetVoidPtr(ImGuiStorage* self,ImGuiID key,void* val); +CIMGUI_API int* ImGuiStorage_GetIntRef(ImGuiStorage* self,ImGuiID key,int default_val); +CIMGUI_API bool* ImGuiStorage_GetBoolRef(ImGuiStorage* self,ImGuiID key,bool default_val); +CIMGUI_API float* ImGuiStorage_GetFloatRef(ImGuiStorage* self,ImGuiID key,float default_val); +CIMGUI_API void** ImGuiStorage_GetVoidPtrRef(ImGuiStorage* self,ImGuiID key,void* default_val); +CIMGUI_API void ImGuiStorage_BuildSortByKey(ImGuiStorage* self); +CIMGUI_API void ImGuiStorage_SetAllInt(ImGuiStorage* self,int val); +CIMGUI_API ImGuiListClipper* ImGuiListClipper_ImGuiListClipper(void); +CIMGUI_API void ImGuiListClipper_destroy(ImGuiListClipper* self); +CIMGUI_API void ImGuiListClipper_Begin(ImGuiListClipper* self,int items_count,float items_height); +CIMGUI_API void ImGuiListClipper_End(ImGuiListClipper* self); +CIMGUI_API bool ImGuiListClipper_Step(ImGuiListClipper* self); +CIMGUI_API void ImGuiListClipper_IncludeItemByIndex(ImGuiListClipper* self,int item_index); +CIMGUI_API void ImGuiListClipper_IncludeItemsByIndex(ImGuiListClipper* self,int item_begin,int item_end); +CIMGUI_API void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* self,int item_index); +CIMGUI_API ImColor* ImColor_ImColor_Nil(void); +CIMGUI_API void ImColor_destroy(ImColor* self); +CIMGUI_API ImColor* ImColor_ImColor_Float(float r,float g,float b,float a); +CIMGUI_API ImColor* ImColor_ImColor_Vec4(const ImVec4 col); +CIMGUI_API ImColor* ImColor_ImColor_Int(int r,int g,int b,int a); +CIMGUI_API ImColor* ImColor_ImColor_U32(ImU32 rgba); +CIMGUI_API void ImColor_SetHSV(ImColor* self,float h,float s,float v,float a); +CIMGUI_API void ImColor_HSV(ImColor *pOut,float h,float s,float v,float a); +CIMGUI_API ImGuiSelectionBasicStorage* ImGuiSelectionBasicStorage_ImGuiSelectionBasicStorage(void); +CIMGUI_API void ImGuiSelectionBasicStorage_destroy(ImGuiSelectionBasicStorage* self); +CIMGUI_API void ImGuiSelectionBasicStorage_ApplyRequests(ImGuiSelectionBasicStorage* self,ImGuiMultiSelectIO* ms_io); +CIMGUI_API bool ImGuiSelectionBasicStorage_Contains(ImGuiSelectionBasicStorage* self,ImGuiID id); +CIMGUI_API void ImGuiSelectionBasicStorage_Clear(ImGuiSelectionBasicStorage* self); +CIMGUI_API void ImGuiSelectionBasicStorage_Swap(ImGuiSelectionBasicStorage* self,ImGuiSelectionBasicStorage* r); +CIMGUI_API void ImGuiSelectionBasicStorage_SetItemSelected(ImGuiSelectionBasicStorage* self,ImGuiID id,bool selected); +CIMGUI_API bool ImGuiSelectionBasicStorage_GetNextSelectedItem(ImGuiSelectionBasicStorage* self,void** opaque_it,ImGuiID* out_id); +CIMGUI_API ImGuiID ImGuiSelectionBasicStorage_GetStorageIdFromIndex(ImGuiSelectionBasicStorage* self,int idx); +CIMGUI_API ImGuiSelectionExternalStorage* ImGuiSelectionExternalStorage_ImGuiSelectionExternalStorage(void); +CIMGUI_API void ImGuiSelectionExternalStorage_destroy(ImGuiSelectionExternalStorage* self); +CIMGUI_API void ImGuiSelectionExternalStorage_ApplyRequests(ImGuiSelectionExternalStorage* self,ImGuiMultiSelectIO* ms_io); +CIMGUI_API ImDrawCmd* ImDrawCmd_ImDrawCmd(void); +CIMGUI_API void ImDrawCmd_destroy(ImDrawCmd* self); +CIMGUI_API ImTextureID ImDrawCmd_GetTexID(ImDrawCmd* self); +CIMGUI_API ImDrawListSplitter* ImDrawListSplitter_ImDrawListSplitter(void); +CIMGUI_API void ImDrawListSplitter_destroy(ImDrawListSplitter* self); +CIMGUI_API void ImDrawListSplitter_Clear(ImDrawListSplitter* self); +CIMGUI_API void ImDrawListSplitter_ClearFreeMemory(ImDrawListSplitter* self); +CIMGUI_API void ImDrawListSplitter_Split(ImDrawListSplitter* self,ImDrawList* draw_list,int count); +CIMGUI_API void ImDrawListSplitter_Merge(ImDrawListSplitter* self,ImDrawList* draw_list); +CIMGUI_API void ImDrawListSplitter_SetCurrentChannel(ImDrawListSplitter* self,ImDrawList* draw_list,int channel_idx); +CIMGUI_API ImDrawList* ImDrawList_ImDrawList(ImDrawListSharedData* shared_data); +CIMGUI_API void ImDrawList_destroy(ImDrawList* self); +CIMGUI_API void ImDrawList_PushClipRect(ImDrawList* self,const ImVec2 clip_rect_min,const ImVec2 clip_rect_max,bool intersect_with_current_clip_rect); +CIMGUI_API void ImDrawList_PushClipRectFullScreen(ImDrawList* self); +CIMGUI_API void ImDrawList_PopClipRect(ImDrawList* self); +CIMGUI_API void ImDrawList_PushTextureID(ImDrawList* self,ImTextureID texture_id); +CIMGUI_API void ImDrawList_PopTextureID(ImDrawList* self); +CIMGUI_API void ImDrawList_GetClipRectMin(ImVec2 *pOut,ImDrawList* self); +CIMGUI_API void ImDrawList_GetClipRectMax(ImVec2 *pOut,ImDrawList* self); +CIMGUI_API void ImDrawList_AddLine(ImDrawList* self,const ImVec2 p1,const ImVec2 p2,ImU32 col,float thickness); +CIMGUI_API void ImDrawList_AddRect(ImDrawList* self,const ImVec2 p_min,const ImVec2 p_max,ImU32 col,float rounding,ImDrawFlags flags,float thickness); +CIMGUI_API void ImDrawList_AddRectFilled(ImDrawList* self,const ImVec2 p_min,const ImVec2 p_max,ImU32 col,float rounding,ImDrawFlags flags); +CIMGUI_API void ImDrawList_AddRectFilledMultiColor(ImDrawList* self,const ImVec2 p_min,const ImVec2 p_max,ImU32 col_upr_left,ImU32 col_upr_right,ImU32 col_bot_right,ImU32 col_bot_left); +CIMGUI_API void ImDrawList_AddQuad(ImDrawList* self,const ImVec2 p1,const ImVec2 p2,const ImVec2 p3,const ImVec2 p4,ImU32 col,float thickness); +CIMGUI_API void ImDrawList_AddQuadFilled(ImDrawList* self,const ImVec2 p1,const ImVec2 p2,const ImVec2 p3,const ImVec2 p4,ImU32 col); +CIMGUI_API void ImDrawList_AddTriangle(ImDrawList* self,const ImVec2 p1,const ImVec2 p2,const ImVec2 p3,ImU32 col,float thickness); +CIMGUI_API void ImDrawList_AddTriangleFilled(ImDrawList* self,const ImVec2 p1,const ImVec2 p2,const ImVec2 p3,ImU32 col); +CIMGUI_API void ImDrawList_AddCircle(ImDrawList* self,const ImVec2 center,float radius,ImU32 col,int num_segments,float thickness); +CIMGUI_API void ImDrawList_AddCircleFilled(ImDrawList* self,const ImVec2 center,float radius,ImU32 col,int num_segments); +CIMGUI_API void ImDrawList_AddNgon(ImDrawList* self,const ImVec2 center,float radius,ImU32 col,int num_segments,float thickness); +CIMGUI_API void ImDrawList_AddNgonFilled(ImDrawList* self,const ImVec2 center,float radius,ImU32 col,int num_segments); +CIMGUI_API void ImDrawList_AddEllipse(ImDrawList* self,const ImVec2 center,const ImVec2 radius,ImU32 col,float rot,int num_segments,float thickness); +CIMGUI_API void ImDrawList_AddEllipseFilled(ImDrawList* self,const ImVec2 center,const ImVec2 radius,ImU32 col,float rot,int num_segments); +CIMGUI_API void ImDrawList_AddText_Vec2(ImDrawList* self,const ImVec2 pos,ImU32 col,const char* text_begin,const char* text_end); +CIMGUI_API void ImDrawList_AddText_FontPtr(ImDrawList* self,ImFont* font,float font_size,const ImVec2 pos,ImU32 col,const char* text_begin,const char* text_end,float wrap_width,const ImVec4* cpu_fine_clip_rect); +CIMGUI_API void ImDrawList_AddBezierCubic(ImDrawList* self,const ImVec2 p1,const ImVec2 p2,const ImVec2 p3,const ImVec2 p4,ImU32 col,float thickness,int num_segments); +CIMGUI_API void ImDrawList_AddBezierQuadratic(ImDrawList* self,const ImVec2 p1,const ImVec2 p2,const ImVec2 p3,ImU32 col,float thickness,int num_segments); +CIMGUI_API void ImDrawList_AddPolyline(ImDrawList* self,const ImVec2* points,int num_points,ImU32 col,ImDrawFlags flags,float thickness); +CIMGUI_API void ImDrawList_AddConvexPolyFilled(ImDrawList* self,const ImVec2* points,int num_points,ImU32 col); +CIMGUI_API void ImDrawList_AddConcavePolyFilled(ImDrawList* self,const ImVec2* points,int num_points,ImU32 col); +CIMGUI_API void ImDrawList_AddImage(ImDrawList* self,ImTextureID user_texture_id,const ImVec2 p_min,const ImVec2 p_max,const ImVec2 uv_min,const ImVec2 uv_max,ImU32 col); +CIMGUI_API void ImDrawList_AddImageQuad(ImDrawList* self,ImTextureID user_texture_id,const ImVec2 p1,const ImVec2 p2,const ImVec2 p3,const ImVec2 p4,const ImVec2 uv1,const ImVec2 uv2,const ImVec2 uv3,const ImVec2 uv4,ImU32 col); +CIMGUI_API void ImDrawList_AddImageRounded(ImDrawList* self,ImTextureID user_texture_id,const ImVec2 p_min,const ImVec2 p_max,const ImVec2 uv_min,const ImVec2 uv_max,ImU32 col,float rounding,ImDrawFlags flags); +CIMGUI_API void ImDrawList_PathClear(ImDrawList* self); +CIMGUI_API void ImDrawList_PathLineTo(ImDrawList* self,const ImVec2 pos); +CIMGUI_API void ImDrawList_PathLineToMergeDuplicate(ImDrawList* self,const ImVec2 pos); +CIMGUI_API void ImDrawList_PathFillConvex(ImDrawList* self,ImU32 col); +CIMGUI_API void ImDrawList_PathFillConcave(ImDrawList* self,ImU32 col); +CIMGUI_API void ImDrawList_PathStroke(ImDrawList* self,ImU32 col,ImDrawFlags flags,float thickness); +CIMGUI_API void ImDrawList_PathArcTo(ImDrawList* self,const ImVec2 center,float radius,float a_min,float a_max,int num_segments); +CIMGUI_API void ImDrawList_PathArcToFast(ImDrawList* self,const ImVec2 center,float radius,int a_min_of_12,int a_max_of_12); +CIMGUI_API void ImDrawList_PathEllipticalArcTo(ImDrawList* self,const ImVec2 center,const ImVec2 radius,float rot,float a_min,float a_max,int num_segments); +CIMGUI_API void ImDrawList_PathBezierCubicCurveTo(ImDrawList* self,const ImVec2 p2,const ImVec2 p3,const ImVec2 p4,int num_segments); +CIMGUI_API void ImDrawList_PathBezierQuadraticCurveTo(ImDrawList* self,const ImVec2 p2,const ImVec2 p3,int num_segments); +CIMGUI_API void ImDrawList_PathRect(ImDrawList* self,const ImVec2 rect_min,const ImVec2 rect_max,float rounding,ImDrawFlags flags); +CIMGUI_API void ImDrawList_AddCallback(ImDrawList* self,ImDrawCallback callback,void* userdata,size_t userdata_size); +CIMGUI_API void ImDrawList_AddDrawCmd(ImDrawList* self); +CIMGUI_API ImDrawList* ImDrawList_CloneOutput(ImDrawList* self); +CIMGUI_API void ImDrawList_ChannelsSplit(ImDrawList* self,int count); +CIMGUI_API void ImDrawList_ChannelsMerge(ImDrawList* self); +CIMGUI_API void ImDrawList_ChannelsSetCurrent(ImDrawList* self,int n); +CIMGUI_API void ImDrawList_PrimReserve(ImDrawList* self,int idx_count,int vtx_count); +CIMGUI_API void ImDrawList_PrimUnreserve(ImDrawList* self,int idx_count,int vtx_count); +CIMGUI_API void ImDrawList_PrimRect(ImDrawList* self,const ImVec2 a,const ImVec2 b,ImU32 col); +CIMGUI_API void ImDrawList_PrimRectUV(ImDrawList* self,const ImVec2 a,const ImVec2 b,const ImVec2 uv_a,const ImVec2 uv_b,ImU32 col); +CIMGUI_API void ImDrawList_PrimQuadUV(ImDrawList* self,const ImVec2 a,const ImVec2 b,const ImVec2 c,const ImVec2 d,const ImVec2 uv_a,const ImVec2 uv_b,const ImVec2 uv_c,const ImVec2 uv_d,ImU32 col); +CIMGUI_API void ImDrawList_PrimWriteVtx(ImDrawList* self,const ImVec2 pos,const ImVec2 uv,ImU32 col); +CIMGUI_API void ImDrawList_PrimWriteIdx(ImDrawList* self,ImDrawIdx idx); +CIMGUI_API void ImDrawList_PrimVtx(ImDrawList* self,const ImVec2 pos,const ImVec2 uv,ImU32 col); +CIMGUI_API void ImDrawList__ResetForNewFrame(ImDrawList* self); +CIMGUI_API void ImDrawList__ClearFreeMemory(ImDrawList* self); +CIMGUI_API void ImDrawList__PopUnusedDrawCmd(ImDrawList* self); +CIMGUI_API void ImDrawList__TryMergeDrawCmds(ImDrawList* self); +CIMGUI_API void ImDrawList__OnChangedClipRect(ImDrawList* self); +CIMGUI_API void ImDrawList__OnChangedTextureID(ImDrawList* self); +CIMGUI_API void ImDrawList__OnChangedVtxOffset(ImDrawList* self); +CIMGUI_API void ImDrawList__SetTextureID(ImDrawList* self,ImTextureID texture_id); +CIMGUI_API int ImDrawList__CalcCircleAutoSegmentCount(ImDrawList* self,float radius); +CIMGUI_API void ImDrawList__PathArcToFastEx(ImDrawList* self,const ImVec2 center,float radius,int a_min_sample,int a_max_sample,int a_step); +CIMGUI_API void ImDrawList__PathArcToN(ImDrawList* self,const ImVec2 center,float radius,float a_min,float a_max,int num_segments); +CIMGUI_API ImDrawData* ImDrawData_ImDrawData(void); +CIMGUI_API void ImDrawData_destroy(ImDrawData* self); +CIMGUI_API void ImDrawData_Clear(ImDrawData* self); +CIMGUI_API void ImDrawData_AddDrawList(ImDrawData* self,ImDrawList* draw_list); +CIMGUI_API void ImDrawData_DeIndexAllBuffers(ImDrawData* self); +CIMGUI_API void ImDrawData_ScaleClipRects(ImDrawData* self,const ImVec2 fb_scale); +CIMGUI_API ImFontConfig* ImFontConfig_ImFontConfig(void); +CIMGUI_API void ImFontConfig_destroy(ImFontConfig* self); +CIMGUI_API ImFontGlyphRangesBuilder* ImFontGlyphRangesBuilder_ImFontGlyphRangesBuilder(void); +CIMGUI_API void ImFontGlyphRangesBuilder_destroy(ImFontGlyphRangesBuilder* self); +CIMGUI_API void ImFontGlyphRangesBuilder_Clear(ImFontGlyphRangesBuilder* self); +CIMGUI_API bool ImFontGlyphRangesBuilder_GetBit(ImFontGlyphRangesBuilder* self,size_t n); +CIMGUI_API void ImFontGlyphRangesBuilder_SetBit(ImFontGlyphRangesBuilder* self,size_t n); +CIMGUI_API void ImFontGlyphRangesBuilder_AddChar(ImFontGlyphRangesBuilder* self,ImWchar c); +CIMGUI_API void ImFontGlyphRangesBuilder_AddText(ImFontGlyphRangesBuilder* self,const char* text,const char* text_end); +CIMGUI_API void ImFontGlyphRangesBuilder_AddRanges(ImFontGlyphRangesBuilder* self,const ImWchar* ranges); +CIMGUI_API void ImFontGlyphRangesBuilder_BuildRanges(ImFontGlyphRangesBuilder* self,ImVector_ImWchar* out_ranges); +CIMGUI_API ImFontAtlasCustomRect* ImFontAtlasCustomRect_ImFontAtlasCustomRect(void); +CIMGUI_API void ImFontAtlasCustomRect_destroy(ImFontAtlasCustomRect* self); +CIMGUI_API bool ImFontAtlasCustomRect_IsPacked(ImFontAtlasCustomRect* self); +CIMGUI_API ImFontAtlas* ImFontAtlas_ImFontAtlas(void); +CIMGUI_API void ImFontAtlas_destroy(ImFontAtlas* self); +CIMGUI_API ImFont* ImFontAtlas_AddFont(ImFontAtlas* self,const ImFontConfig* font_cfg); +CIMGUI_API ImFont* ImFontAtlas_AddFontDefault(ImFontAtlas* self,const ImFontConfig* font_cfg); +CIMGUI_API ImFont* ImFontAtlas_AddFontFromFileTTF(ImFontAtlas* self,const char* filename,float size_pixels,const ImFontConfig* font_cfg,const ImWchar* glyph_ranges); +CIMGUI_API ImFont* ImFontAtlas_AddFontFromMemoryTTF(ImFontAtlas* self,void* font_data,int font_data_size,float size_pixels,const ImFontConfig* font_cfg,const ImWchar* glyph_ranges); +CIMGUI_API ImFont* ImFontAtlas_AddFontFromMemoryCompressedTTF(ImFontAtlas* self,const void* compressed_font_data,int compressed_font_data_size,float size_pixels,const ImFontConfig* font_cfg,const ImWchar* glyph_ranges); +CIMGUI_API ImFont* ImFontAtlas_AddFontFromMemoryCompressedBase85TTF(ImFontAtlas* self,const char* compressed_font_data_base85,float size_pixels,const ImFontConfig* font_cfg,const ImWchar* glyph_ranges); +CIMGUI_API void ImFontAtlas_ClearInputData(ImFontAtlas* self); +CIMGUI_API void ImFontAtlas_ClearFonts(ImFontAtlas* self); +CIMGUI_API void ImFontAtlas_ClearTexData(ImFontAtlas* self); +CIMGUI_API void ImFontAtlas_Clear(ImFontAtlas* self); +CIMGUI_API bool ImFontAtlas_Build(ImFontAtlas* self); +CIMGUI_API void ImFontAtlas_GetTexDataAsAlpha8(ImFontAtlas* self,unsigned char** out_pixels,int* out_width,int* out_height,int* out_bytes_per_pixel); +CIMGUI_API void ImFontAtlas_GetTexDataAsRGBA32(ImFontAtlas* self,unsigned char** out_pixels,int* out_width,int* out_height,int* out_bytes_per_pixel); +CIMGUI_API bool ImFontAtlas_IsBuilt(ImFontAtlas* self); +CIMGUI_API void ImFontAtlas_SetTexID(ImFontAtlas* self,ImTextureID id); +CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesDefault(ImFontAtlas* self); +CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesGreek(ImFontAtlas* self); +CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesKorean(ImFontAtlas* self); +CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesJapanese(ImFontAtlas* self); +CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesChineseFull(ImFontAtlas* self); +CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesChineseSimplifiedCommon(ImFontAtlas* self); +CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesCyrillic(ImFontAtlas* self); +CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesThai(ImFontAtlas* self); +CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesVietnamese(ImFontAtlas* self); +CIMGUI_API int ImFontAtlas_AddCustomRectRegular(ImFontAtlas* self,int width,int height); +CIMGUI_API int ImFontAtlas_AddCustomRectFontGlyph(ImFontAtlas* self,ImFont* font,ImWchar id,int width,int height,float advance_x,const ImVec2 offset); +CIMGUI_API ImFontAtlasCustomRect* ImFontAtlas_GetCustomRectByIndex(ImFontAtlas* self,int index); +CIMGUI_API void ImFontAtlas_CalcCustomRectUV(ImFontAtlas* self,const ImFontAtlasCustomRect* rect,ImVec2* out_uv_min,ImVec2* out_uv_max); +CIMGUI_API ImFont* ImFont_ImFont(void); +CIMGUI_API void ImFont_destroy(ImFont* self); +CIMGUI_API ImFontGlyph* ImFont_FindGlyph(ImFont* self,ImWchar c); +CIMGUI_API ImFontGlyph* ImFont_FindGlyphNoFallback(ImFont* self,ImWchar c); +CIMGUI_API float ImFont_GetCharAdvance(ImFont* self,ImWchar c); +CIMGUI_API bool ImFont_IsLoaded(ImFont* self); +CIMGUI_API const char* ImFont_GetDebugName(ImFont* self); +CIMGUI_API void ImFont_CalcTextSizeA(ImVec2 *pOut,ImFont* self,float size,float max_width,float wrap_width,const char* text_begin,const char* text_end,const char** remaining); +CIMGUI_API const char* ImFont_CalcWordWrapPositionA(ImFont* self,float scale,const char* text,const char* text_end,float wrap_width); +CIMGUI_API void ImFont_RenderChar(ImFont* self,ImDrawList* draw_list,float size,const ImVec2 pos,ImU32 col,ImWchar c); +CIMGUI_API void ImFont_RenderText(ImFont* self,ImDrawList* draw_list,float size,const ImVec2 pos,ImU32 col,const ImVec4 clip_rect,const char* text_begin,const char* text_end,float wrap_width,bool cpu_fine_clip); +CIMGUI_API void ImFont_BuildLookupTable(ImFont* self); +CIMGUI_API void ImFont_ClearOutputData(ImFont* self); +CIMGUI_API void ImFont_GrowIndex(ImFont* self,int new_size); +CIMGUI_API void ImFont_AddGlyph(ImFont* self,const ImFontConfig* src_cfg,ImWchar c,float x0,float y0,float x1,float y1,float u0,float v0,float u1,float v1,float advance_x); +CIMGUI_API void ImFont_AddRemapChar(ImFont* self,ImWchar dst,ImWchar src,bool overwrite_dst); +CIMGUI_API bool ImFont_IsGlyphRangeUnused(ImFont* self,unsigned int c_begin,unsigned int c_last); +CIMGUI_API ImGuiViewport* ImGuiViewport_ImGuiViewport(void); +CIMGUI_API void ImGuiViewport_destroy(ImGuiViewport* self); +CIMGUI_API void ImGuiViewport_GetCenter(ImVec2 *pOut,ImGuiViewport* self); +CIMGUI_API void ImGuiViewport_GetWorkCenter(ImVec2 *pOut,ImGuiViewport* self); +CIMGUI_API ImGuiPlatformIO* ImGuiPlatformIO_ImGuiPlatformIO(void); +CIMGUI_API void ImGuiPlatformIO_destroy(ImGuiPlatformIO* self); +CIMGUI_API ImGuiPlatformMonitor* ImGuiPlatformMonitor_ImGuiPlatformMonitor(void); +CIMGUI_API void ImGuiPlatformMonitor_destroy(ImGuiPlatformMonitor* self); +CIMGUI_API ImGuiPlatformImeData* ImGuiPlatformImeData_ImGuiPlatformImeData(void); +CIMGUI_API void ImGuiPlatformImeData_destroy(ImGuiPlatformImeData* self); +CIMGUI_API ImGuiID igImHashData(const void* data,size_t data_size,ImGuiID seed); +CIMGUI_API ImGuiID igImHashStr(const char* data,size_t data_size,ImGuiID seed); +CIMGUI_API void igImQsort(void* base,size_t count,size_t size_of_element,int(*compare_func)(void const*,void const*)); +CIMGUI_API ImU32 igImAlphaBlendColors(ImU32 col_a,ImU32 col_b); +CIMGUI_API bool igImIsPowerOfTwo_Int(int v); +CIMGUI_API bool igImIsPowerOfTwo_U64(ImU64 v); +CIMGUI_API int igImUpperPowerOfTwo(int v); +CIMGUI_API unsigned int igImCountSetBits(unsigned int v); +CIMGUI_API int igImStricmp(const char* str1,const char* str2); +CIMGUI_API int igImStrnicmp(const char* str1,const char* str2,size_t count); +CIMGUI_API void igImStrncpy(char* dst,const char* src,size_t count); +CIMGUI_API char* igImStrdup(const char* str); +CIMGUI_API char* igImStrdupcpy(char* dst,size_t* p_dst_size,const char* str); +CIMGUI_API const char* igImStrchrRange(const char* str_begin,const char* str_end,char c); +CIMGUI_API const char* igImStreolRange(const char* str,const char* str_end); +CIMGUI_API const char* igImStristr(const char* haystack,const char* haystack_end,const char* needle,const char* needle_end); +CIMGUI_API void igImStrTrimBlanks(char* str); +CIMGUI_API const char* igImStrSkipBlank(const char* str); +CIMGUI_API int igImStrlenW(const ImWchar* str); +CIMGUI_API const char* igImStrbol(const char* buf_mid_line,const char* buf_begin); +CIMGUI_API char igImToUpper(char c); +CIMGUI_API bool igImCharIsBlankA(char c); +CIMGUI_API bool igImCharIsBlankW(unsigned int c); +CIMGUI_API bool igImCharIsXdigitA(char c); +CIMGUI_API int igImFormatString(char* buf,size_t buf_size,const char* fmt,...); +CIMGUI_API int igImFormatStringV(char* buf,size_t buf_size,const char* fmt,va_list args); +CIMGUI_API void igImFormatStringToTempBuffer(const char** out_buf,const char** out_buf_end,const char* fmt,...); +CIMGUI_API void igImFormatStringToTempBufferV(const char** out_buf,const char** out_buf_end,const char* fmt,va_list args); +CIMGUI_API const char* igImParseFormatFindStart(const char* format); +CIMGUI_API const char* igImParseFormatFindEnd(const char* format); +CIMGUI_API const char* igImParseFormatTrimDecorations(const char* format,char* buf,size_t buf_size); +CIMGUI_API void igImParseFormatSanitizeForPrinting(const char* fmt_in,char* fmt_out,size_t fmt_out_size); +CIMGUI_API const char* igImParseFormatSanitizeForScanning(const char* fmt_in,char* fmt_out,size_t fmt_out_size); +CIMGUI_API int igImParseFormatPrecision(const char* format,int default_value); +CIMGUI_API const char* igImTextCharToUtf8(char out_buf[5],unsigned int c); +CIMGUI_API int igImTextStrToUtf8(char* out_buf,int out_buf_size,const ImWchar* in_text,const ImWchar* in_text_end); +CIMGUI_API int igImTextCharFromUtf8(unsigned int* out_char,const char* in_text,const char* in_text_end); +CIMGUI_API int igImTextStrFromUtf8(ImWchar* out_buf,int out_buf_size,const char* in_text,const char* in_text_end,const char** in_remaining); +CIMGUI_API int igImTextCountCharsFromUtf8(const char* in_text,const char* in_text_end); +CIMGUI_API int igImTextCountUtf8BytesFromChar(const char* in_text,const char* in_text_end); +CIMGUI_API int igImTextCountUtf8BytesFromStr(const ImWchar* in_text,const ImWchar* in_text_end); +CIMGUI_API const char* igImTextFindPreviousUtf8Codepoint(const char* in_text_start,const char* in_text_curr); +CIMGUI_API int igImTextCountLines(const char* in_text,const char* in_text_end); +CIMGUI_API ImFileHandle igImFileOpen(const char* filename,const char* mode); +CIMGUI_API bool igImFileClose(ImFileHandle file); +CIMGUI_API ImU64 igImFileGetSize(ImFileHandle file); +CIMGUI_API ImU64 igImFileRead(void* data,ImU64 size,ImU64 count,ImFileHandle file); +CIMGUI_API ImU64 igImFileWrite(const void* data,ImU64 size,ImU64 count,ImFileHandle file); +CIMGUI_API void* igImFileLoadToMemory(const char* filename,const char* mode,size_t* out_file_size,int padding_bytes); +CIMGUI_API float igImPow_Float(float x,float y); +CIMGUI_API double igImPow_double(double x,double y); +CIMGUI_API float igImLog_Float(float x); +CIMGUI_API double igImLog_double(double x); +CIMGUI_API int igImAbs_Int(int x); +CIMGUI_API float igImAbs_Float(float x); +CIMGUI_API double igImAbs_double(double x); +CIMGUI_API float igImSign_Float(float x); +CIMGUI_API double igImSign_double(double x); +CIMGUI_API float igImRsqrt_Float(float x); +CIMGUI_API double igImRsqrt_double(double x); +CIMGUI_API void igImMin(ImVec2 *pOut,const ImVec2 lhs,const ImVec2 rhs); +CIMGUI_API void igImMax(ImVec2 *pOut,const ImVec2 lhs,const ImVec2 rhs); +CIMGUI_API void igImClamp(ImVec2 *pOut,const ImVec2 v,const ImVec2 mn,const ImVec2 mx); +CIMGUI_API void igImLerp_Vec2Float(ImVec2 *pOut,const ImVec2 a,const ImVec2 b,float t); +CIMGUI_API void igImLerp_Vec2Vec2(ImVec2 *pOut,const ImVec2 a,const ImVec2 b,const ImVec2 t); +CIMGUI_API void igImLerp_Vec4(ImVec4 *pOut,const ImVec4 a,const ImVec4 b,float t); +CIMGUI_API float igImSaturate(float f); +CIMGUI_API float igImLengthSqr_Vec2(const ImVec2 lhs); +CIMGUI_API float igImLengthSqr_Vec4(const ImVec4 lhs); +CIMGUI_API float igImInvLength(const ImVec2 lhs,float fail_value); +CIMGUI_API float igImTrunc_Float(float f); +CIMGUI_API void igImTrunc_Vec2(ImVec2 *pOut,const ImVec2 v); +CIMGUI_API float igImFloor_Float(float f); +CIMGUI_API void igImFloor_Vec2(ImVec2 *pOut,const ImVec2 v); +CIMGUI_API int igImModPositive(int a,int b); +CIMGUI_API float igImDot(const ImVec2 a,const ImVec2 b); +CIMGUI_API void igImRotate(ImVec2 *pOut,const ImVec2 v,float cos_a,float sin_a); +CIMGUI_API float igImLinearSweep(float current,float target,float speed); +CIMGUI_API float igImLinearRemapClamp(float s0,float s1,float d0,float d1,float x); +CIMGUI_API void igImMul(ImVec2 *pOut,const ImVec2 lhs,const ImVec2 rhs); +CIMGUI_API bool igImIsFloatAboveGuaranteedIntegerPrecision(float f); +CIMGUI_API float igImExponentialMovingAverage(float avg,float sample,int n); +CIMGUI_API void igImBezierCubicCalc(ImVec2 *pOut,const ImVec2 p1,const ImVec2 p2,const ImVec2 p3,const ImVec2 p4,float t); +CIMGUI_API void igImBezierCubicClosestPoint(ImVec2 *pOut,const ImVec2 p1,const ImVec2 p2,const ImVec2 p3,const ImVec2 p4,const ImVec2 p,int num_segments); +CIMGUI_API void igImBezierCubicClosestPointCasteljau(ImVec2 *pOut,const ImVec2 p1,const ImVec2 p2,const ImVec2 p3,const ImVec2 p4,const ImVec2 p,float tess_tol); +CIMGUI_API void igImBezierQuadraticCalc(ImVec2 *pOut,const ImVec2 p1,const ImVec2 p2,const ImVec2 p3,float t); +CIMGUI_API void igImLineClosestPoint(ImVec2 *pOut,const ImVec2 a,const ImVec2 b,const ImVec2 p); +CIMGUI_API bool igImTriangleContainsPoint(const ImVec2 a,const ImVec2 b,const ImVec2 c,const ImVec2 p); +CIMGUI_API void igImTriangleClosestPoint(ImVec2 *pOut,const ImVec2 a,const ImVec2 b,const ImVec2 c,const ImVec2 p); +CIMGUI_API void igImTriangleBarycentricCoords(const ImVec2 a,const ImVec2 b,const ImVec2 c,const ImVec2 p,float* out_u,float* out_v,float* out_w); +CIMGUI_API float igImTriangleArea(const ImVec2 a,const ImVec2 b,const ImVec2 c); +CIMGUI_API bool igImTriangleIsClockwise(const ImVec2 a,const ImVec2 b,const ImVec2 c); +CIMGUI_API ImVec1* ImVec1_ImVec1_Nil(void); +CIMGUI_API void ImVec1_destroy(ImVec1* self); +CIMGUI_API ImVec1* ImVec1_ImVec1_Float(float _x); +CIMGUI_API ImVec2ih* ImVec2ih_ImVec2ih_Nil(void); +CIMGUI_API void ImVec2ih_destroy(ImVec2ih* self); +CIMGUI_API ImVec2ih* ImVec2ih_ImVec2ih_short(short _x,short _y); +CIMGUI_API ImVec2ih* ImVec2ih_ImVec2ih_Vec2(const ImVec2 rhs); +CIMGUI_API ImRect* ImRect_ImRect_Nil(void); +CIMGUI_API void ImRect_destroy(ImRect* self); +CIMGUI_API ImRect* ImRect_ImRect_Vec2(const ImVec2 min,const ImVec2 max); +CIMGUI_API ImRect* ImRect_ImRect_Vec4(const ImVec4 v); +CIMGUI_API ImRect* ImRect_ImRect_Float(float x1,float y1,float x2,float y2); +CIMGUI_API void ImRect_GetCenter(ImVec2 *pOut,ImRect* self); +CIMGUI_API void ImRect_GetSize(ImVec2 *pOut,ImRect* self); +CIMGUI_API float ImRect_GetWidth(ImRect* self); +CIMGUI_API float ImRect_GetHeight(ImRect* self); +CIMGUI_API float ImRect_GetArea(ImRect* self); +CIMGUI_API void ImRect_GetTL(ImVec2 *pOut,ImRect* self); +CIMGUI_API void ImRect_GetTR(ImVec2 *pOut,ImRect* self); +CIMGUI_API void ImRect_GetBL(ImVec2 *pOut,ImRect* self); +CIMGUI_API void ImRect_GetBR(ImVec2 *pOut,ImRect* self); +CIMGUI_API bool ImRect_Contains_Vec2(ImRect* self,const ImVec2 p); +CIMGUI_API bool ImRect_Contains_Rect(ImRect* self,const ImRect r); +CIMGUI_API bool ImRect_ContainsWithPad(ImRect* self,const ImVec2 p,const ImVec2 pad); +CIMGUI_API bool ImRect_Overlaps(ImRect* self,const ImRect r); +CIMGUI_API void ImRect_Add_Vec2(ImRect* self,const ImVec2 p); +CIMGUI_API void ImRect_Add_Rect(ImRect* self,const ImRect r); +CIMGUI_API void ImRect_Expand_Float(ImRect* self,const float amount); +CIMGUI_API void ImRect_Expand_Vec2(ImRect* self,const ImVec2 amount); +CIMGUI_API void ImRect_Translate(ImRect* self,const ImVec2 d); +CIMGUI_API void ImRect_TranslateX(ImRect* self,float dx); +CIMGUI_API void ImRect_TranslateY(ImRect* self,float dy); +CIMGUI_API void ImRect_ClipWith(ImRect* self,const ImRect r); +CIMGUI_API void ImRect_ClipWithFull(ImRect* self,const ImRect r); +CIMGUI_API void ImRect_Floor(ImRect* self); +CIMGUI_API bool ImRect_IsInverted(ImRect* self); +CIMGUI_API void ImRect_ToVec4(ImVec4 *pOut,ImRect* self); +CIMGUI_API size_t igImBitArrayGetStorageSizeInBytes(int bitcount); +CIMGUI_API void igImBitArrayClearAllBits(ImU32* arr,int bitcount); +CIMGUI_API bool igImBitArrayTestBit(const ImU32* arr,int n); +CIMGUI_API void igImBitArrayClearBit(ImU32* arr,int n); +CIMGUI_API void igImBitArraySetBit(ImU32* arr,int n); +CIMGUI_API void igImBitArraySetBitRange(ImU32* arr,int n,int n2); +CIMGUI_API void ImBitVector_Create(ImBitVector* self,int sz); +CIMGUI_API void ImBitVector_Clear(ImBitVector* self); +CIMGUI_API bool ImBitVector_TestBit(ImBitVector* self,int n); +CIMGUI_API void ImBitVector_SetBit(ImBitVector* self,int n); +CIMGUI_API void ImBitVector_ClearBit(ImBitVector* self,int n); +CIMGUI_API void ImGuiTextIndex_clear(ImGuiTextIndex* self); +CIMGUI_API int ImGuiTextIndex_size(ImGuiTextIndex* self); +CIMGUI_API const char* ImGuiTextIndex_get_line_begin(ImGuiTextIndex* self,const char* base,int n); +CIMGUI_API const char* ImGuiTextIndex_get_line_end(ImGuiTextIndex* self,const char* base,int n); +CIMGUI_API void ImGuiTextIndex_append(ImGuiTextIndex* self,const char* base,int old_size,int new_size); +CIMGUI_API ImGuiStoragePair* igImLowerBound(ImGuiStoragePair* in_begin,ImGuiStoragePair* in_end,ImGuiID key); +CIMGUI_API ImDrawListSharedData* ImDrawListSharedData_ImDrawListSharedData(void); +CIMGUI_API void ImDrawListSharedData_destroy(ImDrawListSharedData* self); +CIMGUI_API void ImDrawListSharedData_SetCircleTessellationMaxError(ImDrawListSharedData* self,float max_error); +CIMGUI_API ImDrawDataBuilder* ImDrawDataBuilder_ImDrawDataBuilder(void); +CIMGUI_API void ImDrawDataBuilder_destroy(ImDrawDataBuilder* self); +CIMGUI_API void* ImGuiStyleVarInfo_GetVarPtr(ImGuiStyleVarInfo* self,void* parent); +CIMGUI_API ImGuiStyleMod* ImGuiStyleMod_ImGuiStyleMod_Int(ImGuiStyleVar idx,int v); +CIMGUI_API void ImGuiStyleMod_destroy(ImGuiStyleMod* self); +CIMGUI_API ImGuiStyleMod* ImGuiStyleMod_ImGuiStyleMod_Float(ImGuiStyleVar idx,float v); +CIMGUI_API ImGuiStyleMod* ImGuiStyleMod_ImGuiStyleMod_Vec2(ImGuiStyleVar idx,ImVec2 v); +CIMGUI_API ImGuiComboPreviewData* ImGuiComboPreviewData_ImGuiComboPreviewData(void); +CIMGUI_API void ImGuiComboPreviewData_destroy(ImGuiComboPreviewData* self); +CIMGUI_API ImGuiMenuColumns* ImGuiMenuColumns_ImGuiMenuColumns(void); +CIMGUI_API void ImGuiMenuColumns_destroy(ImGuiMenuColumns* self); +CIMGUI_API void ImGuiMenuColumns_Update(ImGuiMenuColumns* self,float spacing,bool window_reappearing); +CIMGUI_API float ImGuiMenuColumns_DeclColumns(ImGuiMenuColumns* self,float w_icon,float w_label,float w_shortcut,float w_mark); +CIMGUI_API void ImGuiMenuColumns_CalcNextTotalWidth(ImGuiMenuColumns* self,bool update_offsets); +CIMGUI_API ImGuiInputTextDeactivatedState* ImGuiInputTextDeactivatedState_ImGuiInputTextDeactivatedState(void); +CIMGUI_API void ImGuiInputTextDeactivatedState_destroy(ImGuiInputTextDeactivatedState* self); +CIMGUI_API void ImGuiInputTextDeactivatedState_ClearFreeMemory(ImGuiInputTextDeactivatedState* self); +CIMGUI_API ImGuiInputTextState* ImGuiInputTextState_ImGuiInputTextState(void); +CIMGUI_API void ImGuiInputTextState_destroy(ImGuiInputTextState* self); +CIMGUI_API void ImGuiInputTextState_ClearText(ImGuiInputTextState* self); +CIMGUI_API void ImGuiInputTextState_ClearFreeMemory(ImGuiInputTextState* self); +CIMGUI_API void ImGuiInputTextState_OnKeyPressed(ImGuiInputTextState* self,int key); +CIMGUI_API void ImGuiInputTextState_OnCharPressed(ImGuiInputTextState* self,unsigned int c); +CIMGUI_API void ImGuiInputTextState_CursorAnimReset(ImGuiInputTextState* self); +CIMGUI_API void ImGuiInputTextState_CursorClamp(ImGuiInputTextState* self); +CIMGUI_API bool ImGuiInputTextState_HasSelection(ImGuiInputTextState* self); +CIMGUI_API void ImGuiInputTextState_ClearSelection(ImGuiInputTextState* self); +CIMGUI_API int ImGuiInputTextState_GetCursorPos(ImGuiInputTextState* self); +CIMGUI_API int ImGuiInputTextState_GetSelectionStart(ImGuiInputTextState* self); +CIMGUI_API int ImGuiInputTextState_GetSelectionEnd(ImGuiInputTextState* self); +CIMGUI_API void ImGuiInputTextState_SelectAll(ImGuiInputTextState* self); +CIMGUI_API void ImGuiInputTextState_ReloadUserBufAndSelectAll(ImGuiInputTextState* self); +CIMGUI_API void ImGuiInputTextState_ReloadUserBufAndKeepSelection(ImGuiInputTextState* self); +CIMGUI_API void ImGuiInputTextState_ReloadUserBufAndMoveToEnd(ImGuiInputTextState* self); +CIMGUI_API ImGuiNextWindowData* ImGuiNextWindowData_ImGuiNextWindowData(void); +CIMGUI_API void ImGuiNextWindowData_destroy(ImGuiNextWindowData* self); +CIMGUI_API void ImGuiNextWindowData_ClearFlags(ImGuiNextWindowData* self); +CIMGUI_API ImGuiNextItemData* ImGuiNextItemData_ImGuiNextItemData(void); +CIMGUI_API void ImGuiNextItemData_destroy(ImGuiNextItemData* self); +CIMGUI_API void ImGuiNextItemData_ClearFlags(ImGuiNextItemData* self); +CIMGUI_API ImGuiLastItemData* ImGuiLastItemData_ImGuiLastItemData(void); +CIMGUI_API void ImGuiLastItemData_destroy(ImGuiLastItemData* self); +CIMGUI_API ImGuiErrorRecoveryState* ImGuiErrorRecoveryState_ImGuiErrorRecoveryState(void); +CIMGUI_API void ImGuiErrorRecoveryState_destroy(ImGuiErrorRecoveryState* self); +CIMGUI_API ImGuiPtrOrIndex* ImGuiPtrOrIndex_ImGuiPtrOrIndex_Ptr(void* ptr); +CIMGUI_API void ImGuiPtrOrIndex_destroy(ImGuiPtrOrIndex* self); +CIMGUI_API ImGuiPtrOrIndex* ImGuiPtrOrIndex_ImGuiPtrOrIndex_Int(int index); +CIMGUI_API ImGuiPopupData* ImGuiPopupData_ImGuiPopupData(void); +CIMGUI_API void ImGuiPopupData_destroy(ImGuiPopupData* self); +CIMGUI_API ImGuiInputEvent* ImGuiInputEvent_ImGuiInputEvent(void); +CIMGUI_API void ImGuiInputEvent_destroy(ImGuiInputEvent* self); +CIMGUI_API ImGuiKeyRoutingData* ImGuiKeyRoutingData_ImGuiKeyRoutingData(void); +CIMGUI_API void ImGuiKeyRoutingData_destroy(ImGuiKeyRoutingData* self); +CIMGUI_API ImGuiKeyRoutingTable* ImGuiKeyRoutingTable_ImGuiKeyRoutingTable(void); +CIMGUI_API void ImGuiKeyRoutingTable_destroy(ImGuiKeyRoutingTable* self); +CIMGUI_API void ImGuiKeyRoutingTable_Clear(ImGuiKeyRoutingTable* self); +CIMGUI_API ImGuiKeyOwnerData* ImGuiKeyOwnerData_ImGuiKeyOwnerData(void); +CIMGUI_API void ImGuiKeyOwnerData_destroy(ImGuiKeyOwnerData* self); +CIMGUI_API ImGuiListClipperRange ImGuiListClipperRange_FromIndices(int min,int max); +CIMGUI_API ImGuiListClipperRange ImGuiListClipperRange_FromPositions(float y1,float y2,int off_min,int off_max); +CIMGUI_API ImGuiListClipperData* ImGuiListClipperData_ImGuiListClipperData(void); +CIMGUI_API void ImGuiListClipperData_destroy(ImGuiListClipperData* self); +CIMGUI_API void ImGuiListClipperData_Reset(ImGuiListClipperData* self,ImGuiListClipper* clipper); +CIMGUI_API ImGuiNavItemData* ImGuiNavItemData_ImGuiNavItemData(void); +CIMGUI_API void ImGuiNavItemData_destroy(ImGuiNavItemData* self); +CIMGUI_API void ImGuiNavItemData_Clear(ImGuiNavItemData* self); +CIMGUI_API ImGuiTypingSelectState* ImGuiTypingSelectState_ImGuiTypingSelectState(void); +CIMGUI_API void ImGuiTypingSelectState_destroy(ImGuiTypingSelectState* self); +CIMGUI_API void ImGuiTypingSelectState_Clear(ImGuiTypingSelectState* self); +CIMGUI_API ImGuiOldColumnData* ImGuiOldColumnData_ImGuiOldColumnData(void); +CIMGUI_API void ImGuiOldColumnData_destroy(ImGuiOldColumnData* self); +CIMGUI_API ImGuiOldColumns* ImGuiOldColumns_ImGuiOldColumns(void); +CIMGUI_API void ImGuiOldColumns_destroy(ImGuiOldColumns* self); +CIMGUI_API ImGuiBoxSelectState* ImGuiBoxSelectState_ImGuiBoxSelectState(void); +CIMGUI_API void ImGuiBoxSelectState_destroy(ImGuiBoxSelectState* self); +CIMGUI_API ImGuiMultiSelectTempData* ImGuiMultiSelectTempData_ImGuiMultiSelectTempData(void); +CIMGUI_API void ImGuiMultiSelectTempData_destroy(ImGuiMultiSelectTempData* self); +CIMGUI_API void ImGuiMultiSelectTempData_Clear(ImGuiMultiSelectTempData* self); +CIMGUI_API void ImGuiMultiSelectTempData_ClearIO(ImGuiMultiSelectTempData* self); +CIMGUI_API ImGuiMultiSelectState* ImGuiMultiSelectState_ImGuiMultiSelectState(void); +CIMGUI_API void ImGuiMultiSelectState_destroy(ImGuiMultiSelectState* self); +CIMGUI_API ImGuiDockNode* ImGuiDockNode_ImGuiDockNode(ImGuiID id); +CIMGUI_API void ImGuiDockNode_destroy(ImGuiDockNode* self); +CIMGUI_API bool ImGuiDockNode_IsRootNode(ImGuiDockNode* self); +CIMGUI_API bool ImGuiDockNode_IsDockSpace(ImGuiDockNode* self); +CIMGUI_API bool ImGuiDockNode_IsFloatingNode(ImGuiDockNode* self); +CIMGUI_API bool ImGuiDockNode_IsCentralNode(ImGuiDockNode* self); +CIMGUI_API bool ImGuiDockNode_IsHiddenTabBar(ImGuiDockNode* self); +CIMGUI_API bool ImGuiDockNode_IsNoTabBar(ImGuiDockNode* self); +CIMGUI_API bool ImGuiDockNode_IsSplitNode(ImGuiDockNode* self); +CIMGUI_API bool ImGuiDockNode_IsLeafNode(ImGuiDockNode* self); +CIMGUI_API bool ImGuiDockNode_IsEmpty(ImGuiDockNode* self); +CIMGUI_API void ImGuiDockNode_Rect(ImRect *pOut,ImGuiDockNode* self); +CIMGUI_API void ImGuiDockNode_SetLocalFlags(ImGuiDockNode* self,ImGuiDockNodeFlags flags); +CIMGUI_API void ImGuiDockNode_UpdateMergedFlags(ImGuiDockNode* self); +CIMGUI_API ImGuiDockContext* ImGuiDockContext_ImGuiDockContext(void); +CIMGUI_API void ImGuiDockContext_destroy(ImGuiDockContext* self); +CIMGUI_API ImGuiViewportP* ImGuiViewportP_ImGuiViewportP(void); +CIMGUI_API void ImGuiViewportP_destroy(ImGuiViewportP* self); +CIMGUI_API void ImGuiViewportP_ClearRequestFlags(ImGuiViewportP* self); +CIMGUI_API void ImGuiViewportP_CalcWorkRectPos(ImVec2 *pOut,ImGuiViewportP* self,const ImVec2 inset_min); +CIMGUI_API void ImGuiViewportP_CalcWorkRectSize(ImVec2 *pOut,ImGuiViewportP* self,const ImVec2 inset_min,const ImVec2 inset_max); +CIMGUI_API void ImGuiViewportP_UpdateWorkRect(ImGuiViewportP* self); +CIMGUI_API void ImGuiViewportP_GetMainRect(ImRect *pOut,ImGuiViewportP* self); +CIMGUI_API void ImGuiViewportP_GetWorkRect(ImRect *pOut,ImGuiViewportP* self); +CIMGUI_API void ImGuiViewportP_GetBuildWorkRect(ImRect *pOut,ImGuiViewportP* self); +CIMGUI_API ImGuiWindowSettings* ImGuiWindowSettings_ImGuiWindowSettings(void); +CIMGUI_API void ImGuiWindowSettings_destroy(ImGuiWindowSettings* self); +CIMGUI_API char* ImGuiWindowSettings_GetName(ImGuiWindowSettings* self); +CIMGUI_API ImGuiSettingsHandler* ImGuiSettingsHandler_ImGuiSettingsHandler(void); +CIMGUI_API void ImGuiSettingsHandler_destroy(ImGuiSettingsHandler* self); +CIMGUI_API ImGuiDebugAllocInfo* ImGuiDebugAllocInfo_ImGuiDebugAllocInfo(void); +CIMGUI_API void ImGuiDebugAllocInfo_destroy(ImGuiDebugAllocInfo* self); +CIMGUI_API ImGuiStackLevelInfo* ImGuiStackLevelInfo_ImGuiStackLevelInfo(void); +CIMGUI_API void ImGuiStackLevelInfo_destroy(ImGuiStackLevelInfo* self); +CIMGUI_API ImGuiIDStackTool* ImGuiIDStackTool_ImGuiIDStackTool(void); +CIMGUI_API void ImGuiIDStackTool_destroy(ImGuiIDStackTool* self); +CIMGUI_API ImGuiContextHook* ImGuiContextHook_ImGuiContextHook(void); +CIMGUI_API void ImGuiContextHook_destroy(ImGuiContextHook* self); +CIMGUI_API ImGuiContext* ImGuiContext_ImGuiContext(ImFontAtlas* shared_font_atlas); +CIMGUI_API void ImGuiContext_destroy(ImGuiContext* self); +CIMGUI_API ImGuiWindow* ImGuiWindow_ImGuiWindow(ImGuiContext* context,const char* name); +CIMGUI_API void ImGuiWindow_destroy(ImGuiWindow* self); +CIMGUI_API ImGuiID ImGuiWindow_GetID_Str(ImGuiWindow* self,const char* str,const char* str_end); +CIMGUI_API ImGuiID ImGuiWindow_GetID_Ptr(ImGuiWindow* self,const void* ptr); +CIMGUI_API ImGuiID ImGuiWindow_GetID_Int(ImGuiWindow* self,int n); +CIMGUI_API ImGuiID ImGuiWindow_GetIDFromPos(ImGuiWindow* self,const ImVec2 p_abs); +CIMGUI_API ImGuiID ImGuiWindow_GetIDFromRectangle(ImGuiWindow* self,const ImRect r_abs); +CIMGUI_API void ImGuiWindow_Rect(ImRect *pOut,ImGuiWindow* self); +CIMGUI_API float ImGuiWindow_CalcFontSize(ImGuiWindow* self); +CIMGUI_API void ImGuiWindow_TitleBarRect(ImRect *pOut,ImGuiWindow* self); +CIMGUI_API void ImGuiWindow_MenuBarRect(ImRect *pOut,ImGuiWindow* self); +CIMGUI_API ImGuiTabItem* ImGuiTabItem_ImGuiTabItem(void); +CIMGUI_API void ImGuiTabItem_destroy(ImGuiTabItem* self); +CIMGUI_API ImGuiTabBar* ImGuiTabBar_ImGuiTabBar(void); +CIMGUI_API void ImGuiTabBar_destroy(ImGuiTabBar* self); +CIMGUI_API ImGuiTableColumn* ImGuiTableColumn_ImGuiTableColumn(void); +CIMGUI_API void ImGuiTableColumn_destroy(ImGuiTableColumn* self); +CIMGUI_API ImGuiTableInstanceData* ImGuiTableInstanceData_ImGuiTableInstanceData(void); +CIMGUI_API void ImGuiTableInstanceData_destroy(ImGuiTableInstanceData* self); +CIMGUI_API ImGuiTable* ImGuiTable_ImGuiTable(void); +CIMGUI_API void ImGuiTable_destroy(ImGuiTable* self); +CIMGUI_API ImGuiTableTempData* ImGuiTableTempData_ImGuiTableTempData(void); +CIMGUI_API void ImGuiTableTempData_destroy(ImGuiTableTempData* self); +CIMGUI_API ImGuiTableColumnSettings* ImGuiTableColumnSettings_ImGuiTableColumnSettings(void); +CIMGUI_API void ImGuiTableColumnSettings_destroy(ImGuiTableColumnSettings* self); +CIMGUI_API ImGuiTableSettings* ImGuiTableSettings_ImGuiTableSettings(void); +CIMGUI_API void ImGuiTableSettings_destroy(ImGuiTableSettings* self); +CIMGUI_API ImGuiTableColumnSettings* ImGuiTableSettings_GetColumnSettings(ImGuiTableSettings* self); +CIMGUI_API ImGuiIO* igGetIO_ContextPtr(ImGuiContext* ctx); +CIMGUI_API ImGuiPlatformIO* igGetPlatformIO_ContextPtr(ImGuiContext* ctx); +CIMGUI_API ImGuiWindow* igGetCurrentWindowRead(void); +CIMGUI_API ImGuiWindow* igGetCurrentWindow(void); +CIMGUI_API ImGuiWindow* igFindWindowByID(ImGuiID id); +CIMGUI_API ImGuiWindow* igFindWindowByName(const char* name); +CIMGUI_API void igUpdateWindowParentAndRootLinks(ImGuiWindow* window,ImGuiWindowFlags flags,ImGuiWindow* parent_window); +CIMGUI_API void igUpdateWindowSkipRefresh(ImGuiWindow* window); +CIMGUI_API void igCalcWindowNextAutoFitSize(ImVec2 *pOut,ImGuiWindow* window); +CIMGUI_API bool igIsWindowChildOf(ImGuiWindow* window,ImGuiWindow* potential_parent,bool popup_hierarchy,bool dock_hierarchy); +CIMGUI_API bool igIsWindowWithinBeginStackOf(ImGuiWindow* window,ImGuiWindow* potential_parent); +CIMGUI_API bool igIsWindowAbove(ImGuiWindow* potential_above,ImGuiWindow* potential_below); +CIMGUI_API bool igIsWindowNavFocusable(ImGuiWindow* window); +CIMGUI_API void igSetWindowPos_WindowPtr(ImGuiWindow* window,const ImVec2 pos,ImGuiCond cond); +CIMGUI_API void igSetWindowSize_WindowPtr(ImGuiWindow* window,const ImVec2 size,ImGuiCond cond); +CIMGUI_API void igSetWindowCollapsed_WindowPtr(ImGuiWindow* window,bool collapsed,ImGuiCond cond); +CIMGUI_API void igSetWindowHitTestHole(ImGuiWindow* window,const ImVec2 pos,const ImVec2 size); +CIMGUI_API void igSetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window); +CIMGUI_API void igSetWindowParentWindowForFocusRoute(ImGuiWindow* window,ImGuiWindow* parent_window); +CIMGUI_API void igWindowRectAbsToRel(ImRect *pOut,ImGuiWindow* window,const ImRect r); +CIMGUI_API void igWindowRectRelToAbs(ImRect *pOut,ImGuiWindow* window,const ImRect r); +CIMGUI_API void igWindowPosAbsToRel(ImVec2 *pOut,ImGuiWindow* window,const ImVec2 p); +CIMGUI_API void igWindowPosRelToAbs(ImVec2 *pOut,ImGuiWindow* window,const ImVec2 p); +CIMGUI_API void igFocusWindow(ImGuiWindow* window,ImGuiFocusRequestFlags flags); +CIMGUI_API void igFocusTopMostWindowUnderOne(ImGuiWindow* under_this_window,ImGuiWindow* ignore_window,ImGuiViewport* filter_viewport,ImGuiFocusRequestFlags flags); +CIMGUI_API void igBringWindowToFocusFront(ImGuiWindow* window); +CIMGUI_API void igBringWindowToDisplayFront(ImGuiWindow* window); +CIMGUI_API void igBringWindowToDisplayBack(ImGuiWindow* window); +CIMGUI_API void igBringWindowToDisplayBehind(ImGuiWindow* window,ImGuiWindow* above_window); +CIMGUI_API int igFindWindowDisplayIndex(ImGuiWindow* window); +CIMGUI_API ImGuiWindow* igFindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* window); +CIMGUI_API void igSetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags); +CIMGUI_API void igSetCurrentFont(ImFont* font); +CIMGUI_API ImFont* igGetDefaultFont(void); +CIMGUI_API void igPushPasswordFont(void); +CIMGUI_API ImDrawList* igGetForegroundDrawList_WindowPtr(ImGuiWindow* window); +CIMGUI_API void igAddDrawListToDrawDataEx(ImDrawData* draw_data,ImVector_ImDrawListPtr* out_list,ImDrawList* draw_list); +CIMGUI_API void igInitialize(void); +CIMGUI_API void igShutdown(void); +CIMGUI_API void igUpdateInputEvents(bool trickle_fast_inputs); +CIMGUI_API void igUpdateHoveredWindowAndCaptureFlags(void); +CIMGUI_API void igFindHoveredWindowEx(const ImVec2 pos,bool find_first_and_in_any_viewport,ImGuiWindow** out_hovered_window,ImGuiWindow** out_hovered_window_under_moving_window); +CIMGUI_API void igStartMouseMovingWindow(ImGuiWindow* window); +CIMGUI_API void igStartMouseMovingWindowOrNode(ImGuiWindow* window,ImGuiDockNode* node,bool undock); +CIMGUI_API void igUpdateMouseMovingWindowNewFrame(void); +CIMGUI_API void igUpdateMouseMovingWindowEndFrame(void); +CIMGUI_API ImGuiID igAddContextHook(ImGuiContext* context,const ImGuiContextHook* hook); +CIMGUI_API void igRemoveContextHook(ImGuiContext* context,ImGuiID hook_to_remove); +CIMGUI_API void igCallContextHooks(ImGuiContext* context,ImGuiContextHookType type); +CIMGUI_API void igTranslateWindowsInViewport(ImGuiViewportP* viewport,const ImVec2 old_pos,const ImVec2 new_pos,const ImVec2 old_size,const ImVec2 new_size); +CIMGUI_API void igScaleWindowsInViewport(ImGuiViewportP* viewport,float scale); +CIMGUI_API void igDestroyPlatformWindow(ImGuiViewportP* viewport); +CIMGUI_API void igSetWindowViewport(ImGuiWindow* window,ImGuiViewportP* viewport); +CIMGUI_API void igSetCurrentViewport(ImGuiWindow* window,ImGuiViewportP* viewport); +CIMGUI_API const ImGuiPlatformMonitor* igGetViewportPlatformMonitor(ImGuiViewport* viewport); +CIMGUI_API ImGuiViewportP* igFindHoveredViewportFromPlatformWindowStack(const ImVec2 mouse_platform_pos); +CIMGUI_API void igMarkIniSettingsDirty_Nil(void); +CIMGUI_API void igMarkIniSettingsDirty_WindowPtr(ImGuiWindow* window); +CIMGUI_API void igClearIniSettings(void); +CIMGUI_API void igAddSettingsHandler(const ImGuiSettingsHandler* handler); +CIMGUI_API void igRemoveSettingsHandler(const char* type_name); +CIMGUI_API ImGuiSettingsHandler* igFindSettingsHandler(const char* type_name); +CIMGUI_API ImGuiWindowSettings* igCreateNewWindowSettings(const char* name); +CIMGUI_API ImGuiWindowSettings* igFindWindowSettingsByID(ImGuiID id); +CIMGUI_API ImGuiWindowSettings* igFindWindowSettingsByWindow(ImGuiWindow* window); +CIMGUI_API void igClearWindowSettings(const char* name); +CIMGUI_API void igLocalizeRegisterEntries(const ImGuiLocEntry* entries,int count); +CIMGUI_API const char* igLocalizeGetMsg(ImGuiLocKey key); +CIMGUI_API void igSetScrollX_WindowPtr(ImGuiWindow* window,float scroll_x); +CIMGUI_API void igSetScrollY_WindowPtr(ImGuiWindow* window,float scroll_y); +CIMGUI_API void igSetScrollFromPosX_WindowPtr(ImGuiWindow* window,float local_x,float center_x_ratio); +CIMGUI_API void igSetScrollFromPosY_WindowPtr(ImGuiWindow* window,float local_y,float center_y_ratio); +CIMGUI_API void igScrollToItem(ImGuiScrollFlags flags); +CIMGUI_API void igScrollToRect(ImGuiWindow* window,const ImRect rect,ImGuiScrollFlags flags); +CIMGUI_API void igScrollToRectEx(ImVec2 *pOut,ImGuiWindow* window,const ImRect rect,ImGuiScrollFlags flags); +CIMGUI_API void igScrollToBringRectIntoView(ImGuiWindow* window,const ImRect rect); +CIMGUI_API ImGuiItemStatusFlags igGetItemStatusFlags(void); +CIMGUI_API ImGuiItemFlags igGetItemFlags(void); +CIMGUI_API ImGuiID igGetActiveID(void); +CIMGUI_API ImGuiID igGetFocusID(void); +CIMGUI_API void igSetActiveID(ImGuiID id,ImGuiWindow* window); +CIMGUI_API void igSetFocusID(ImGuiID id,ImGuiWindow* window); +CIMGUI_API void igClearActiveID(void); +CIMGUI_API ImGuiID igGetHoveredID(void); +CIMGUI_API void igSetHoveredID(ImGuiID id); +CIMGUI_API void igKeepAliveID(ImGuiID id); +CIMGUI_API void igMarkItemEdited(ImGuiID id); +CIMGUI_API void igPushOverrideID(ImGuiID id); +CIMGUI_API ImGuiID igGetIDWithSeed_Str(const char* str_id_begin,const char* str_id_end,ImGuiID seed); +CIMGUI_API ImGuiID igGetIDWithSeed_Int(int n,ImGuiID seed); +CIMGUI_API void igItemSize_Vec2(const ImVec2 size,float text_baseline_y); +CIMGUI_API void igItemSize_Rect(const ImRect bb,float text_baseline_y); +CIMGUI_API bool igItemAdd(const ImRect bb,ImGuiID id,const ImRect* nav_bb,ImGuiItemFlags extra_flags); +CIMGUI_API bool igItemHoverable(const ImRect bb,ImGuiID id,ImGuiItemFlags item_flags); +CIMGUI_API bool igIsWindowContentHoverable(ImGuiWindow* window,ImGuiHoveredFlags flags); +CIMGUI_API bool igIsClippedEx(const ImRect bb,ImGuiID id); +CIMGUI_API void igSetLastItemData(ImGuiID item_id,ImGuiItemFlags item_flags,ImGuiItemStatusFlags status_flags,const ImRect item_rect); +CIMGUI_API void igCalcItemSize(ImVec2 *pOut,ImVec2 size,float default_w,float default_h); +CIMGUI_API float igCalcWrapWidthForPos(const ImVec2 pos,float wrap_pos_x); +CIMGUI_API void igPushMultiItemsWidths(int components,float width_full); +CIMGUI_API void igShrinkWidths(ImGuiShrinkWidthItem* items,int count,float width_excess); +CIMGUI_API const ImGuiStyleVarInfo* igGetStyleVarInfo(ImGuiStyleVar idx); +CIMGUI_API void igBeginDisabledOverrideReenable(void); +CIMGUI_API void igEndDisabledOverrideReenable(void); +CIMGUI_API void igLogBegin(ImGuiLogFlags flags,int auto_open_depth); +CIMGUI_API void igLogToBuffer(int auto_open_depth); +CIMGUI_API void igLogRenderedText(const ImVec2* ref_pos,const char* text,const char* text_end); +CIMGUI_API void igLogSetNextTextDecoration(const char* prefix,const char* suffix); +CIMGUI_API bool igBeginChildEx(const char* name,ImGuiID id,const ImVec2 size_arg,ImGuiChildFlags child_flags,ImGuiWindowFlags window_flags); +CIMGUI_API bool igBeginPopupEx(ImGuiID id,ImGuiWindowFlags extra_window_flags); +CIMGUI_API bool igBeginPopupMenuEx(ImGuiID id,const char* label,ImGuiWindowFlags extra_window_flags); +CIMGUI_API void igOpenPopupEx(ImGuiID id,ImGuiPopupFlags popup_flags); +CIMGUI_API void igClosePopupToLevel(int remaining,bool restore_focus_to_window_under_popup); +CIMGUI_API void igClosePopupsOverWindow(ImGuiWindow* ref_window,bool restore_focus_to_window_under_popup); +CIMGUI_API void igClosePopupsExceptModals(void); +CIMGUI_API bool igIsPopupOpen_ID(ImGuiID id,ImGuiPopupFlags popup_flags); +CIMGUI_API void igGetPopupAllowedExtentRect(ImRect *pOut,ImGuiWindow* window); +CIMGUI_API ImGuiWindow* igGetTopMostPopupModal(void); +CIMGUI_API ImGuiWindow* igGetTopMostAndVisiblePopupModal(void); +CIMGUI_API ImGuiWindow* igFindBlockingModal(ImGuiWindow* window); +CIMGUI_API void igFindBestWindowPosForPopup(ImVec2 *pOut,ImGuiWindow* window); +CIMGUI_API void igFindBestWindowPosForPopupEx(ImVec2 *pOut,const ImVec2 ref_pos,const ImVec2 size,ImGuiDir* last_dir,const ImRect r_outer,const ImRect r_avoid,ImGuiPopupPositionPolicy policy); +CIMGUI_API bool igBeginTooltipEx(ImGuiTooltipFlags tooltip_flags,ImGuiWindowFlags extra_window_flags); +CIMGUI_API bool igBeginTooltipHidden(void); +CIMGUI_API bool igBeginViewportSideBar(const char* name,ImGuiViewport* viewport,ImGuiDir dir,float size,ImGuiWindowFlags window_flags); +CIMGUI_API bool igBeginMenuEx(const char* label,const char* icon,bool enabled); +CIMGUI_API bool igMenuItemEx(const char* label,const char* icon,const char* shortcut,bool selected,bool enabled); +CIMGUI_API bool igBeginComboPopup(ImGuiID popup_id,const ImRect bb,ImGuiComboFlags flags); +CIMGUI_API bool igBeginComboPreview(void); +CIMGUI_API void igEndComboPreview(void); +CIMGUI_API void igNavInitWindow(ImGuiWindow* window,bool force_reinit); +CIMGUI_API void igNavInitRequestApplyResult(void); +CIMGUI_API bool igNavMoveRequestButNoResultYet(void); +CIMGUI_API void igNavMoveRequestSubmit(ImGuiDir move_dir,ImGuiDir clip_dir,ImGuiNavMoveFlags move_flags,ImGuiScrollFlags scroll_flags); +CIMGUI_API void igNavMoveRequestForward(ImGuiDir move_dir,ImGuiDir clip_dir,ImGuiNavMoveFlags move_flags,ImGuiScrollFlags scroll_flags); +CIMGUI_API void igNavMoveRequestResolveWithLastItem(ImGuiNavItemData* result); +CIMGUI_API void igNavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result,ImGuiTreeNodeStackData* tree_node_data); +CIMGUI_API void igNavMoveRequestCancel(void); +CIMGUI_API void igNavMoveRequestApplyResult(void); +CIMGUI_API void igNavMoveRequestTryWrapping(ImGuiWindow* window,ImGuiNavMoveFlags move_flags); +CIMGUI_API void igNavHighlightActivated(ImGuiID id); +CIMGUI_API void igNavClearPreferredPosForAxis(ImGuiAxis axis); +CIMGUI_API void igSetNavCursorVisibleAfterMove(void); +CIMGUI_API void igNavUpdateCurrentWindowIsScrollPushableX(void); +CIMGUI_API void igSetNavWindow(ImGuiWindow* window); +CIMGUI_API void igSetNavID(ImGuiID id,ImGuiNavLayer nav_layer,ImGuiID focus_scope_id,const ImRect rect_rel); +CIMGUI_API void igSetNavFocusScope(ImGuiID focus_scope_id); +CIMGUI_API void igFocusItem(void); +CIMGUI_API void igActivateItemByID(ImGuiID id); +CIMGUI_API bool igIsNamedKey(ImGuiKey key); +CIMGUI_API bool igIsNamedKeyOrMod(ImGuiKey key); +CIMGUI_API bool igIsLegacyKey(ImGuiKey key); +CIMGUI_API bool igIsKeyboardKey(ImGuiKey key); +CIMGUI_API bool igIsGamepadKey(ImGuiKey key); +CIMGUI_API bool igIsMouseKey(ImGuiKey key); +CIMGUI_API bool igIsAliasKey(ImGuiKey key); +CIMGUI_API bool igIsLRModKey(ImGuiKey key); +CIMGUI_API ImGuiKeyChord igFixupKeyChord(ImGuiKeyChord key_chord); +CIMGUI_API ImGuiKey igConvertSingleModFlagToKey(ImGuiKey key); +CIMGUI_API ImGuiKeyData* igGetKeyData_ContextPtr(ImGuiContext* ctx,ImGuiKey key); +CIMGUI_API ImGuiKeyData* igGetKeyData_Key(ImGuiKey key); +CIMGUI_API const char* igGetKeyChordName(ImGuiKeyChord key_chord); +CIMGUI_API ImGuiKey igMouseButtonToKey(ImGuiMouseButton button); +CIMGUI_API bool igIsMouseDragPastThreshold(ImGuiMouseButton button,float lock_threshold); +CIMGUI_API void igGetKeyMagnitude2d(ImVec2 *pOut,ImGuiKey key_left,ImGuiKey key_right,ImGuiKey key_up,ImGuiKey key_down); +CIMGUI_API float igGetNavTweakPressedAmount(ImGuiAxis axis); +CIMGUI_API int igCalcTypematicRepeatAmount(float t0,float t1,float repeat_delay,float repeat_rate); +CIMGUI_API void igGetTypematicRepeatRate(ImGuiInputFlags flags,float* repeat_delay,float* repeat_rate); +CIMGUI_API void igTeleportMousePos(const ImVec2 pos); +CIMGUI_API void igSetActiveIdUsingAllKeyboardKeys(void); +CIMGUI_API bool igIsActiveIdUsingNavDir(ImGuiDir dir); +CIMGUI_API ImGuiID igGetKeyOwner(ImGuiKey key); +CIMGUI_API void igSetKeyOwner(ImGuiKey key,ImGuiID owner_id,ImGuiInputFlags flags); +CIMGUI_API void igSetKeyOwnersForKeyChord(ImGuiKeyChord key,ImGuiID owner_id,ImGuiInputFlags flags); +CIMGUI_API void igSetItemKeyOwner_InputFlags(ImGuiKey key,ImGuiInputFlags flags); +CIMGUI_API bool igTestKeyOwner(ImGuiKey key,ImGuiID owner_id); +CIMGUI_API ImGuiKeyOwnerData* igGetKeyOwnerData(ImGuiContext* ctx,ImGuiKey key); +CIMGUI_API bool igIsKeyDown_ID(ImGuiKey key,ImGuiID owner_id); +CIMGUI_API bool igIsKeyPressed_InputFlags(ImGuiKey key,ImGuiInputFlags flags,ImGuiID owner_id); +CIMGUI_API bool igIsKeyReleased_ID(ImGuiKey key,ImGuiID owner_id); +CIMGUI_API bool igIsKeyChordPressed_InputFlags(ImGuiKeyChord key_chord,ImGuiInputFlags flags,ImGuiID owner_id); +CIMGUI_API bool igIsMouseDown_ID(ImGuiMouseButton button,ImGuiID owner_id); +CIMGUI_API bool igIsMouseClicked_InputFlags(ImGuiMouseButton button,ImGuiInputFlags flags,ImGuiID owner_id); +CIMGUI_API bool igIsMouseReleased_ID(ImGuiMouseButton button,ImGuiID owner_id); +CIMGUI_API bool igIsMouseDoubleClicked_ID(ImGuiMouseButton button,ImGuiID owner_id); +CIMGUI_API bool igShortcut_ID(ImGuiKeyChord key_chord,ImGuiInputFlags flags,ImGuiID owner_id); +CIMGUI_API bool igSetShortcutRouting(ImGuiKeyChord key_chord,ImGuiInputFlags flags,ImGuiID owner_id); +CIMGUI_API bool igTestShortcutRouting(ImGuiKeyChord key_chord,ImGuiID owner_id); +CIMGUI_API ImGuiKeyRoutingData* igGetShortcutRoutingData(ImGuiKeyChord key_chord); +CIMGUI_API void igDockContextInitialize(ImGuiContext* ctx); +CIMGUI_API void igDockContextShutdown(ImGuiContext* ctx); +CIMGUI_API void igDockContextClearNodes(ImGuiContext* ctx,ImGuiID root_id,bool clear_settings_refs); +CIMGUI_API void igDockContextRebuildNodes(ImGuiContext* ctx); +CIMGUI_API void igDockContextNewFrameUpdateUndocking(ImGuiContext* ctx); +CIMGUI_API void igDockContextNewFrameUpdateDocking(ImGuiContext* ctx); +CIMGUI_API void igDockContextEndFrame(ImGuiContext* ctx); +CIMGUI_API ImGuiID igDockContextGenNodeID(ImGuiContext* ctx); +CIMGUI_API void igDockContextQueueDock(ImGuiContext* ctx,ImGuiWindow* target,ImGuiDockNode* target_node,ImGuiWindow* payload,ImGuiDir split_dir,float split_ratio,bool split_outer); +CIMGUI_API void igDockContextQueueUndockWindow(ImGuiContext* ctx,ImGuiWindow* window); +CIMGUI_API void igDockContextQueueUndockNode(ImGuiContext* ctx,ImGuiDockNode* node); +CIMGUI_API void igDockContextProcessUndockWindow(ImGuiContext* ctx,ImGuiWindow* window,bool clear_persistent_docking_ref); +CIMGUI_API void igDockContextProcessUndockNode(ImGuiContext* ctx,ImGuiDockNode* node); +CIMGUI_API bool igDockContextCalcDropPosForDocking(ImGuiWindow* target,ImGuiDockNode* target_node,ImGuiWindow* payload_window,ImGuiDockNode* payload_node,ImGuiDir split_dir,bool split_outer,ImVec2* out_pos); +CIMGUI_API ImGuiDockNode* igDockContextFindNodeByID(ImGuiContext* ctx,ImGuiID id); +CIMGUI_API void igDockNodeWindowMenuHandler_Default(ImGuiContext* ctx,ImGuiDockNode* node,ImGuiTabBar* tab_bar); +CIMGUI_API bool igDockNodeBeginAmendTabBar(ImGuiDockNode* node); +CIMGUI_API void igDockNodeEndAmendTabBar(void); +CIMGUI_API ImGuiDockNode* igDockNodeGetRootNode(ImGuiDockNode* node); +CIMGUI_API bool igDockNodeIsInHierarchyOf(ImGuiDockNode* node,ImGuiDockNode* parent); +CIMGUI_API int igDockNodeGetDepth(const ImGuiDockNode* node); +CIMGUI_API ImGuiID igDockNodeGetWindowMenuButtonId(const ImGuiDockNode* node); +CIMGUI_API ImGuiDockNode* igGetWindowDockNode(void); +CIMGUI_API bool igGetWindowAlwaysWantOwnTabBar(ImGuiWindow* window); +CIMGUI_API void igBeginDocked(ImGuiWindow* window,bool* p_open); +CIMGUI_API void igBeginDockableDragDropSource(ImGuiWindow* window); +CIMGUI_API void igBeginDockableDragDropTarget(ImGuiWindow* window); +CIMGUI_API void igSetWindowDock(ImGuiWindow* window,ImGuiID dock_id,ImGuiCond cond); +CIMGUI_API void igDockBuilderDockWindow(const char* window_name,ImGuiID node_id); +CIMGUI_API ImGuiDockNode* igDockBuilderGetNode(ImGuiID node_id); +CIMGUI_API ImGuiDockNode* igDockBuilderGetCentralNode(ImGuiID node_id); +CIMGUI_API ImGuiID igDockBuilderAddNode(ImGuiID node_id,ImGuiDockNodeFlags flags); +CIMGUI_API void igDockBuilderRemoveNode(ImGuiID node_id); +CIMGUI_API void igDockBuilderRemoveNodeDockedWindows(ImGuiID node_id,bool clear_settings_refs); +CIMGUI_API void igDockBuilderRemoveNodeChildNodes(ImGuiID node_id); +CIMGUI_API void igDockBuilderSetNodePos(ImGuiID node_id,ImVec2 pos); +CIMGUI_API void igDockBuilderSetNodeSize(ImGuiID node_id,ImVec2 size); +CIMGUI_API ImGuiID igDockBuilderSplitNode(ImGuiID node_id,ImGuiDir split_dir,float size_ratio_for_node_at_dir,ImGuiID* out_id_at_dir,ImGuiID* out_id_at_opposite_dir); +CIMGUI_API void igDockBuilderCopyDockSpace(ImGuiID src_dockspace_id,ImGuiID dst_dockspace_id,ImVector_const_charPtr* in_window_remap_pairs); +CIMGUI_API void igDockBuilderCopyNode(ImGuiID src_node_id,ImGuiID dst_node_id,ImVector_ImGuiID* out_node_remap_pairs); +CIMGUI_API void igDockBuilderCopyWindowSettings(const char* src_name,const char* dst_name); +CIMGUI_API void igDockBuilderFinish(ImGuiID node_id); +CIMGUI_API void igPushFocusScope(ImGuiID id); +CIMGUI_API void igPopFocusScope(void); +CIMGUI_API ImGuiID igGetCurrentFocusScope(void); +CIMGUI_API bool igIsDragDropActive(void); +CIMGUI_API bool igBeginDragDropTargetCustom(const ImRect bb,ImGuiID id); +CIMGUI_API void igClearDragDrop(void); +CIMGUI_API bool igIsDragDropPayloadBeingAccepted(void); +CIMGUI_API void igRenderDragDropTargetRect(const ImRect bb,const ImRect item_clip_rect); +CIMGUI_API ImGuiTypingSelectRequest* igGetTypingSelectRequest(ImGuiTypingSelectFlags flags); +CIMGUI_API int igTypingSelectFindMatch(ImGuiTypingSelectRequest* req,int items_count,const char*(*get_item_name_func)(void*,int),void* user_data,int nav_item_idx); +CIMGUI_API int igTypingSelectFindNextSingleCharMatch(ImGuiTypingSelectRequest* req,int items_count,const char*(*get_item_name_func)(void*,int),void* user_data,int nav_item_idx); +CIMGUI_API int igTypingSelectFindBestLeadingMatch(ImGuiTypingSelectRequest* req,int items_count,const char*(*get_item_name_func)(void*,int),void* user_data); +CIMGUI_API bool igBeginBoxSelect(const ImRect scope_rect,ImGuiWindow* window,ImGuiID box_select_id,ImGuiMultiSelectFlags ms_flags); +CIMGUI_API void igEndBoxSelect(const ImRect scope_rect,ImGuiMultiSelectFlags ms_flags); +CIMGUI_API void igMultiSelectItemHeader(ImGuiID id,bool* p_selected,ImGuiButtonFlags* p_button_flags); +CIMGUI_API void igMultiSelectItemFooter(ImGuiID id,bool* p_selected,bool* p_pressed); +CIMGUI_API void igMultiSelectAddSetAll(ImGuiMultiSelectTempData* ms,bool selected); +CIMGUI_API void igMultiSelectAddSetRange(ImGuiMultiSelectTempData* ms,bool selected,int range_dir,ImGuiSelectionUserData first_item,ImGuiSelectionUserData last_item); +CIMGUI_API ImGuiBoxSelectState* igGetBoxSelectState(ImGuiID id); +CIMGUI_API ImGuiMultiSelectState* igGetMultiSelectState(ImGuiID id); +CIMGUI_API void igSetWindowClipRectBeforeSetChannel(ImGuiWindow* window,const ImRect clip_rect); +CIMGUI_API void igBeginColumns(const char* str_id,int count,ImGuiOldColumnFlags flags); +CIMGUI_API void igEndColumns(void); +CIMGUI_API void igPushColumnClipRect(int column_index); +CIMGUI_API void igPushColumnsBackground(void); +CIMGUI_API void igPopColumnsBackground(void); +CIMGUI_API ImGuiID igGetColumnsID(const char* str_id,int count); +CIMGUI_API ImGuiOldColumns* igFindOrCreateColumns(ImGuiWindow* window,ImGuiID id); +CIMGUI_API float igGetColumnOffsetFromNorm(const ImGuiOldColumns* columns,float offset_norm); +CIMGUI_API float igGetColumnNormFromOffset(const ImGuiOldColumns* columns,float offset); +CIMGUI_API void igTableOpenContextMenu(int column_n); +CIMGUI_API void igTableSetColumnWidth(int column_n,float width); +CIMGUI_API void igTableSetColumnSortDirection(int column_n,ImGuiSortDirection sort_direction,bool append_to_sort_specs); +CIMGUI_API int igTableGetHoveredRow(void); +CIMGUI_API float igTableGetHeaderRowHeight(void); +CIMGUI_API float igTableGetHeaderAngledMaxLabelWidth(void); +CIMGUI_API void igTablePushBackgroundChannel(void); +CIMGUI_API void igTablePopBackgroundChannel(void); +CIMGUI_API void igTableAngledHeadersRowEx(ImGuiID row_id,float angle,float max_label_width,const ImGuiTableHeaderData* data,int data_count); +CIMGUI_API ImGuiTable* igGetCurrentTable(void); +CIMGUI_API ImGuiTable* igTableFindByID(ImGuiID id); +CIMGUI_API bool igBeginTableEx(const char* name,ImGuiID id,int columns_count,ImGuiTableFlags flags,const ImVec2 outer_size,float inner_width); +CIMGUI_API void igTableBeginInitMemory(ImGuiTable* table,int columns_count); +CIMGUI_API void igTableBeginApplyRequests(ImGuiTable* table); +CIMGUI_API void igTableSetupDrawChannels(ImGuiTable* table); +CIMGUI_API void igTableUpdateLayout(ImGuiTable* table); +CIMGUI_API void igTableUpdateBorders(ImGuiTable* table); +CIMGUI_API void igTableUpdateColumnsWeightFromWidth(ImGuiTable* table); +CIMGUI_API void igTableDrawBorders(ImGuiTable* table); +CIMGUI_API void igTableDrawDefaultContextMenu(ImGuiTable* table,ImGuiTableFlags flags_for_section_to_display); +CIMGUI_API bool igTableBeginContextMenuPopup(ImGuiTable* table); +CIMGUI_API void igTableMergeDrawChannels(ImGuiTable* table); +CIMGUI_API ImGuiTableInstanceData* igTableGetInstanceData(ImGuiTable* table,int instance_no); +CIMGUI_API ImGuiID igTableGetInstanceID(ImGuiTable* table,int instance_no); +CIMGUI_API void igTableSortSpecsSanitize(ImGuiTable* table); +CIMGUI_API void igTableSortSpecsBuild(ImGuiTable* table); +CIMGUI_API ImGuiSortDirection igTableGetColumnNextSortDirection(ImGuiTableColumn* column); +CIMGUI_API void igTableFixColumnSortDirection(ImGuiTable* table,ImGuiTableColumn* column); +CIMGUI_API float igTableGetColumnWidthAuto(ImGuiTable* table,ImGuiTableColumn* column); +CIMGUI_API void igTableBeginRow(ImGuiTable* table); +CIMGUI_API void igTableEndRow(ImGuiTable* table); +CIMGUI_API void igTableBeginCell(ImGuiTable* table,int column_n); +CIMGUI_API void igTableEndCell(ImGuiTable* table); +CIMGUI_API void igTableGetCellBgRect(ImRect *pOut,const ImGuiTable* table,int column_n); +CIMGUI_API const char* igTableGetColumnName_TablePtr(const ImGuiTable* table,int column_n); +CIMGUI_API ImGuiID igTableGetColumnResizeID(ImGuiTable* table,int column_n,int instance_no); +CIMGUI_API float igTableCalcMaxColumnWidth(const ImGuiTable* table,int column_n); +CIMGUI_API void igTableSetColumnWidthAutoSingle(ImGuiTable* table,int column_n); +CIMGUI_API void igTableSetColumnWidthAutoAll(ImGuiTable* table); +CIMGUI_API void igTableRemove(ImGuiTable* table); +CIMGUI_API void igTableGcCompactTransientBuffers_TablePtr(ImGuiTable* table); +CIMGUI_API void igTableGcCompactTransientBuffers_TableTempDataPtr(ImGuiTableTempData* table); +CIMGUI_API void igTableGcCompactSettings(void); +CIMGUI_API void igTableLoadSettings(ImGuiTable* table); +CIMGUI_API void igTableSaveSettings(ImGuiTable* table); +CIMGUI_API void igTableResetSettings(ImGuiTable* table); +CIMGUI_API ImGuiTableSettings* igTableGetBoundSettings(ImGuiTable* table); +CIMGUI_API void igTableSettingsAddSettingsHandler(void); +CIMGUI_API ImGuiTableSettings* igTableSettingsCreate(ImGuiID id,int columns_count); +CIMGUI_API ImGuiTableSettings* igTableSettingsFindByID(ImGuiID id); +CIMGUI_API ImGuiTabBar* igGetCurrentTabBar(void); +CIMGUI_API bool igBeginTabBarEx(ImGuiTabBar* tab_bar,const ImRect bb,ImGuiTabBarFlags flags); +CIMGUI_API ImGuiTabItem* igTabBarFindTabByID(ImGuiTabBar* tab_bar,ImGuiID tab_id); +CIMGUI_API ImGuiTabItem* igTabBarFindTabByOrder(ImGuiTabBar* tab_bar,int order); +CIMGUI_API ImGuiTabItem* igTabBarFindMostRecentlySelectedTabForActiveWindow(ImGuiTabBar* tab_bar); +CIMGUI_API ImGuiTabItem* igTabBarGetCurrentTab(ImGuiTabBar* tab_bar); +CIMGUI_API int igTabBarGetTabOrder(ImGuiTabBar* tab_bar,ImGuiTabItem* tab); +CIMGUI_API const char* igTabBarGetTabName(ImGuiTabBar* tab_bar,ImGuiTabItem* tab); +CIMGUI_API void igTabBarAddTab(ImGuiTabBar* tab_bar,ImGuiTabItemFlags tab_flags,ImGuiWindow* window); +CIMGUI_API void igTabBarRemoveTab(ImGuiTabBar* tab_bar,ImGuiID tab_id); +CIMGUI_API void igTabBarCloseTab(ImGuiTabBar* tab_bar,ImGuiTabItem* tab); +CIMGUI_API void igTabBarQueueFocus_TabItemPtr(ImGuiTabBar* tab_bar,ImGuiTabItem* tab); +CIMGUI_API void igTabBarQueueFocus_Str(ImGuiTabBar* tab_bar,const char* tab_name); +CIMGUI_API void igTabBarQueueReorder(ImGuiTabBar* tab_bar,ImGuiTabItem* tab,int offset); +CIMGUI_API void igTabBarQueueReorderFromMousePos(ImGuiTabBar* tab_bar,ImGuiTabItem* tab,ImVec2 mouse_pos); +CIMGUI_API bool igTabBarProcessReorder(ImGuiTabBar* tab_bar); +CIMGUI_API bool igTabItemEx(ImGuiTabBar* tab_bar,const char* label,bool* p_open,ImGuiTabItemFlags flags,ImGuiWindow* docked_window); +CIMGUI_API void igTabItemSpacing(const char* str_id,ImGuiTabItemFlags flags,float width); +CIMGUI_API void igTabItemCalcSize_Str(ImVec2 *pOut,const char* label,bool has_close_button_or_unsaved_marker); +CIMGUI_API void igTabItemCalcSize_WindowPtr(ImVec2 *pOut,ImGuiWindow* window); +CIMGUI_API void igTabItemBackground(ImDrawList* draw_list,const ImRect bb,ImGuiTabItemFlags flags,ImU32 col); +CIMGUI_API void igTabItemLabelAndCloseButton(ImDrawList* draw_list,const ImRect bb,ImGuiTabItemFlags flags,ImVec2 frame_padding,const char* label,ImGuiID tab_id,ImGuiID close_button_id,bool is_contents_visible,bool* out_just_closed,bool* out_text_clipped); +CIMGUI_API void igRenderText(ImVec2 pos,const char* text,const char* text_end,bool hide_text_after_hash); +CIMGUI_API void igRenderTextWrapped(ImVec2 pos,const char* text,const char* text_end,float wrap_width); +CIMGUI_API void igRenderTextClipped(const ImVec2 pos_min,const ImVec2 pos_max,const char* text,const char* text_end,const ImVec2* text_size_if_known,const ImVec2 align,const ImRect* clip_rect); +CIMGUI_API void igRenderTextClippedEx(ImDrawList* draw_list,const ImVec2 pos_min,const ImVec2 pos_max,const char* text,const char* text_end,const ImVec2* text_size_if_known,const ImVec2 align,const ImRect* clip_rect); +CIMGUI_API void igRenderTextEllipsis(ImDrawList* draw_list,const ImVec2 pos_min,const ImVec2 pos_max,float clip_max_x,float ellipsis_max_x,const char* text,const char* text_end,const ImVec2* text_size_if_known); +CIMGUI_API void igRenderFrame(ImVec2 p_min,ImVec2 p_max,ImU32 fill_col,bool borders,float rounding); +CIMGUI_API void igRenderFrameBorder(ImVec2 p_min,ImVec2 p_max,float rounding); +CIMGUI_API void igRenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list,ImVec2 p_min,ImVec2 p_max,ImU32 fill_col,float grid_step,ImVec2 grid_off,float rounding,ImDrawFlags flags); +CIMGUI_API void igRenderNavCursor(const ImRect bb,ImGuiID id,ImGuiNavRenderCursorFlags flags); +CIMGUI_API const char* igFindRenderedTextEnd(const char* text,const char* text_end); +CIMGUI_API void igRenderMouseCursor(ImVec2 pos,float scale,ImGuiMouseCursor mouse_cursor,ImU32 col_fill,ImU32 col_border,ImU32 col_shadow); +CIMGUI_API void igRenderArrow(ImDrawList* draw_list,ImVec2 pos,ImU32 col,ImGuiDir dir,float scale); +CIMGUI_API void igRenderBullet(ImDrawList* draw_list,ImVec2 pos,ImU32 col); +CIMGUI_API void igRenderCheckMark(ImDrawList* draw_list,ImVec2 pos,ImU32 col,float sz); +CIMGUI_API void igRenderArrowPointingAt(ImDrawList* draw_list,ImVec2 pos,ImVec2 half_sz,ImGuiDir direction,ImU32 col); +CIMGUI_API void igRenderArrowDockMenu(ImDrawList* draw_list,ImVec2 p_min,float sz,ImU32 col); +CIMGUI_API void igRenderRectFilledRangeH(ImDrawList* draw_list,const ImRect rect,ImU32 col,float x_start_norm,float x_end_norm,float rounding); +CIMGUI_API void igRenderRectFilledWithHole(ImDrawList* draw_list,const ImRect outer,const ImRect inner,ImU32 col,float rounding); +CIMGUI_API ImDrawFlags igCalcRoundingFlagsForRectInRect(const ImRect r_in,const ImRect r_outer,float threshold); +CIMGUI_API void igTextEx(const char* text,const char* text_end,ImGuiTextFlags flags); +CIMGUI_API bool igButtonEx(const char* label,const ImVec2 size_arg,ImGuiButtonFlags flags); +CIMGUI_API bool igArrowButtonEx(const char* str_id,ImGuiDir dir,ImVec2 size_arg,ImGuiButtonFlags flags); +CIMGUI_API bool igImageButtonEx(ImGuiID id,ImTextureID user_texture_id,const ImVec2 image_size,const ImVec2 uv0,const ImVec2 uv1,const ImVec4 bg_col,const ImVec4 tint_col,ImGuiButtonFlags flags); +CIMGUI_API void igSeparatorEx(ImGuiSeparatorFlags flags,float thickness); +CIMGUI_API void igSeparatorTextEx(ImGuiID id,const char* label,const char* label_end,float extra_width); +CIMGUI_API bool igCheckboxFlags_S64Ptr(const char* label,ImS64* flags,ImS64 flags_value); +CIMGUI_API bool igCheckboxFlags_U64Ptr(const char* label,ImU64* flags,ImU64 flags_value); +CIMGUI_API bool igCloseButton(ImGuiID id,const ImVec2 pos); +CIMGUI_API bool igCollapseButton(ImGuiID id,const ImVec2 pos,ImGuiDockNode* dock_node); +CIMGUI_API void igScrollbar(ImGuiAxis axis); +CIMGUI_API bool igScrollbarEx(const ImRect bb,ImGuiID id,ImGuiAxis axis,ImS64* p_scroll_v,ImS64 avail_v,ImS64 contents_v,ImDrawFlags draw_rounding_flags); +CIMGUI_API void igGetWindowScrollbarRect(ImRect *pOut,ImGuiWindow* window,ImGuiAxis axis); +CIMGUI_API ImGuiID igGetWindowScrollbarID(ImGuiWindow* window,ImGuiAxis axis); +CIMGUI_API ImGuiID igGetWindowResizeCornerID(ImGuiWindow* window,int n); +CIMGUI_API ImGuiID igGetWindowResizeBorderID(ImGuiWindow* window,ImGuiDir dir); +CIMGUI_API bool igButtonBehavior(const ImRect bb,ImGuiID id,bool* out_hovered,bool* out_held,ImGuiButtonFlags flags); +CIMGUI_API bool igDragBehavior(ImGuiID id,ImGuiDataType data_type,void* p_v,float v_speed,const void* p_min,const void* p_max,const char* format,ImGuiSliderFlags flags); +CIMGUI_API bool igSliderBehavior(const ImRect bb,ImGuiID id,ImGuiDataType data_type,void* p_v,const void* p_min,const void* p_max,const char* format,ImGuiSliderFlags flags,ImRect* out_grab_bb); +CIMGUI_API bool igSplitterBehavior(const ImRect bb,ImGuiID id,ImGuiAxis axis,float* size1,float* size2,float min_size1,float min_size2,float hover_extend,float hover_visibility_delay,ImU32 bg_col); +CIMGUI_API bool igTreeNodeBehavior(ImGuiID id,ImGuiTreeNodeFlags flags,const char* label,const char* label_end); +CIMGUI_API void igTreePushOverrideID(ImGuiID id); +CIMGUI_API bool igTreeNodeGetOpen(ImGuiID storage_id); +CIMGUI_API void igTreeNodeSetOpen(ImGuiID storage_id,bool open); +CIMGUI_API bool igTreeNodeUpdateNextOpen(ImGuiID storage_id,ImGuiTreeNodeFlags flags); +CIMGUI_API const ImGuiDataTypeInfo* igDataTypeGetInfo(ImGuiDataType data_type); +CIMGUI_API int igDataTypeFormatString(char* buf,int buf_size,ImGuiDataType data_type,const void* p_data,const char* format); +CIMGUI_API void igDataTypeApplyOp(ImGuiDataType data_type,int op,void* output,const void* arg_1,const void* arg_2); +CIMGUI_API bool igDataTypeApplyFromText(const char* buf,ImGuiDataType data_type,void* p_data,const char* format,void* p_data_when_empty); +CIMGUI_API int igDataTypeCompare(ImGuiDataType data_type,const void* arg_1,const void* arg_2); +CIMGUI_API bool igDataTypeClamp(ImGuiDataType data_type,void* p_data,const void* p_min,const void* p_max); +CIMGUI_API bool igDataTypeIsZero(ImGuiDataType data_type,const void* p_data); +CIMGUI_API bool igInputTextEx(const char* label,const char* hint,char* buf,int buf_size,const ImVec2 size_arg,ImGuiInputTextFlags flags,ImGuiInputTextCallback callback,void* user_data); +CIMGUI_API void igInputTextDeactivateHook(ImGuiID id); +CIMGUI_API bool igTempInputText(const ImRect bb,ImGuiID id,const char* label,char* buf,int buf_size,ImGuiInputTextFlags flags); +CIMGUI_API bool igTempInputScalar(const ImRect bb,ImGuiID id,const char* label,ImGuiDataType data_type,void* p_data,const char* format,const void* p_clamp_min,const void* p_clamp_max); +CIMGUI_API bool igTempInputIsActive(ImGuiID id); +CIMGUI_API ImGuiInputTextState* igGetInputTextState(ImGuiID id); +CIMGUI_API void igSetNextItemRefVal(ImGuiDataType data_type,void* p_data); +CIMGUI_API bool igIsItemActiveAsInputText(void); +CIMGUI_API void igColorTooltip(const char* text,const float* col,ImGuiColorEditFlags flags); +CIMGUI_API void igColorEditOptionsPopup(const float* col,ImGuiColorEditFlags flags); +CIMGUI_API void igColorPickerOptionsPopup(const float* ref_col,ImGuiColorEditFlags flags); +CIMGUI_API int igPlotEx(ImGuiPlotType plot_type,const char* label,float(*values_getter)(void* data,int idx),void* data,int values_count,int values_offset,const char* overlay_text,float scale_min,float scale_max,const ImVec2 size_arg); +CIMGUI_API void igShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list,int vert_start_idx,int vert_end_idx,ImVec2 gradient_p0,ImVec2 gradient_p1,ImU32 col0,ImU32 col1); +CIMGUI_API void igShadeVertsLinearUV(ImDrawList* draw_list,int vert_start_idx,int vert_end_idx,const ImVec2 a,const ImVec2 b,const ImVec2 uv_a,const ImVec2 uv_b,bool clamp); +CIMGUI_API void igShadeVertsTransformPos(ImDrawList* draw_list,int vert_start_idx,int vert_end_idx,const ImVec2 pivot_in,float cos_a,float sin_a,const ImVec2 pivot_out); +CIMGUI_API void igGcCompactTransientMiscBuffers(void); +CIMGUI_API void igGcCompactTransientWindowBuffers(ImGuiWindow* window); +CIMGUI_API void igGcAwakeTransientWindowBuffers(ImGuiWindow* window); +CIMGUI_API bool igErrorLog(const char* msg); +CIMGUI_API void igErrorRecoveryStoreState(ImGuiErrorRecoveryState* state_out); +CIMGUI_API void igErrorRecoveryTryToRecoverState(const ImGuiErrorRecoveryState* state_in); +CIMGUI_API void igErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryState* state_in); +CIMGUI_API void igErrorCheckUsingSetCursorPosToExtendParentBoundaries(void); +CIMGUI_API void igErrorCheckEndFrameFinalizeErrorTooltip(void); +CIMGUI_API bool igBeginErrorTooltip(void); +CIMGUI_API void igEndErrorTooltip(void); +CIMGUI_API void igDebugAllocHook(ImGuiDebugAllocInfo* info,int frame_count,void* ptr,size_t size); +CIMGUI_API void igDebugDrawCursorPos(ImU32 col); +CIMGUI_API void igDebugDrawLineExtents(ImU32 col); +CIMGUI_API void igDebugDrawItemRect(ImU32 col); +CIMGUI_API void igDebugTextUnformattedWithLocateItem(const char* line_begin,const char* line_end); +CIMGUI_API void igDebugLocateItem(ImGuiID target_id); +CIMGUI_API void igDebugLocateItemOnHover(ImGuiID target_id); +CIMGUI_API void igDebugLocateItemResolveWithLastItem(void); +CIMGUI_API void igDebugBreakClearData(void); +CIMGUI_API bool igDebugBreakButton(const char* label,const char* description_of_location); +CIMGUI_API void igDebugBreakButtonTooltip(bool keyboard_only,const char* description_of_location); +CIMGUI_API void igShowFontAtlas(ImFontAtlas* atlas); +CIMGUI_API void igDebugHookIdInfo(ImGuiID id,ImGuiDataType data_type,const void* data_id,const void* data_id_end); +CIMGUI_API void igDebugNodeColumns(ImGuiOldColumns* columns); +CIMGUI_API void igDebugNodeDockNode(ImGuiDockNode* node,const char* label); +CIMGUI_API void igDebugNodeDrawList(ImGuiWindow* window,ImGuiViewportP* viewport,const ImDrawList* draw_list,const char* label); +CIMGUI_API void igDebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list,const ImDrawList* draw_list,const ImDrawCmd* draw_cmd,bool show_mesh,bool show_aabb); +CIMGUI_API void igDebugNodeFont(ImFont* font); +CIMGUI_API void igDebugNodeFontGlyph(ImFont* font,const ImFontGlyph* glyph); +CIMGUI_API void igDebugNodeStorage(ImGuiStorage* storage,const char* label); +CIMGUI_API void igDebugNodeTabBar(ImGuiTabBar* tab_bar,const char* label); +CIMGUI_API void igDebugNodeTable(ImGuiTable* table); +CIMGUI_API void igDebugNodeTableSettings(ImGuiTableSettings* settings); +CIMGUI_API void igDebugNodeInputTextState(ImGuiInputTextState* state); +CIMGUI_API void igDebugNodeTypingSelectState(ImGuiTypingSelectState* state); +CIMGUI_API void igDebugNodeMultiSelectState(ImGuiMultiSelectState* state); +CIMGUI_API void igDebugNodeWindow(ImGuiWindow* window,const char* label); +CIMGUI_API void igDebugNodeWindowSettings(ImGuiWindowSettings* settings); +CIMGUI_API void igDebugNodeWindowsList(ImVector_ImGuiWindowPtr* windows,const char* label); +CIMGUI_API void igDebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows,int windows_size,ImGuiWindow* parent_in_begin_stack); +CIMGUI_API void igDebugNodeViewport(ImGuiViewportP* viewport); +CIMGUI_API void igDebugNodePlatformMonitor(ImGuiPlatformMonitor* monitor,const char* label,int idx); +CIMGUI_API void igDebugRenderKeyboardPreview(ImDrawList* draw_list); +CIMGUI_API void igDebugRenderViewportThumbnail(ImDrawList* draw_list,ImGuiViewportP* viewport,const ImRect bb); +CIMGUI_API const ImFontBuilderIO* igImFontAtlasGetBuilderForStbTruetype(void); +CIMGUI_API void igImFontAtlasUpdateSourcesPointers(ImFontAtlas* atlas); +CIMGUI_API void igImFontAtlasBuildInit(ImFontAtlas* atlas); +CIMGUI_API void igImFontAtlasBuildSetupFont(ImFontAtlas* atlas,ImFont* font,ImFontConfig* src,float ascent,float descent); +CIMGUI_API void igImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas,void* stbrp_context_opaque); +CIMGUI_API void igImFontAtlasBuildFinish(ImFontAtlas* atlas); +CIMGUI_API void igImFontAtlasBuildRender8bppRectFromString(ImFontAtlas* atlas,int x,int y,int w,int h,const char* in_str,char in_marker_char,unsigned char in_marker_pixel_value); +CIMGUI_API void igImFontAtlasBuildRender32bppRectFromString(ImFontAtlas* atlas,int x,int y,int w,int h,const char* in_str,char in_marker_char,unsigned int in_marker_pixel_value); +CIMGUI_API void igImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256],float in_multiply_factor); +CIMGUI_API void igImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256],unsigned char* pixels,int x,int y,int w,int h,int stride); +CIMGUI_API void igImFontAtlasBuildGetOversampleFactors(const ImFontConfig* src,int* out_oversample_h,int* out_oversample_v); +CIMGUI_API bool igImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas,ImGuiMouseCursor cursor_type,ImVec2* out_offset,ImVec2* out_size,ImVec2 out_uv_border[2],ImVec2 out_uv_fill[2]); +#ifdef IMGUI_ENABLE_FREETYPE +CIMGUI_API const ImFontBuilderIO* ImGuiFreeType_GetBuilderForFreeType(void); +CIMGUI_API void ImGuiFreeType_SetAllocatorFunctions(void*(*alloc_func)(size_t sz,void* user_data),void(*free_func)(void* ptr,void* user_data),void* user_data); +#endif + + +/////////////////////////hand written functions +//no LogTextV +CIMGUI_API void igLogText(const char *fmt, ...); +//no appendfV +CIMGUI_API void ImGuiTextBuffer_appendf(ImGuiTextBuffer *self, const char *fmt, ...); +//for getting FLT_MAX in bindings +CIMGUI_API float igGET_FLT_MAX(void); +//for getting FLT_MIN in bindings +CIMGUI_API float igGET_FLT_MIN(void); + + +CIMGUI_API ImVector_ImWchar* ImVector_ImWchar_create(void); +CIMGUI_API void ImVector_ImWchar_destroy(ImVector_ImWchar* self); +CIMGUI_API void ImVector_ImWchar_Init(ImVector_ImWchar* p); +CIMGUI_API void ImVector_ImWchar_UnInit(ImVector_ImWchar* p); + +#ifdef IMGUI_HAS_DOCK +CIMGUI_API void ImGuiPlatformIO_Set_Platform_GetWindowPos(ImGuiPlatformIO* platform_io, void(*user_callback)(ImGuiViewport* vp, ImVec2* out_pos)); +CIMGUI_API void ImGuiPlatformIO_Set_Platform_GetWindowSize(ImGuiPlatformIO* platform_io, void(*user_callback)(ImGuiViewport* vp, ImVec2* out_size)); +#endif + +#endif //CIMGUI_INCLUDED + + + + diff --git a/workspace/template/include/mod.h b/workspace/template/include/mod.h new file mode 100644 index 000000000..c720faf0c --- /dev/null +++ b/workspace/template/include/mod.h @@ -0,0 +1,18 @@ +#pragma once + +#if defined(_WIN32) || defined(__CYGWIN__) + #define HM_API __declspec(dllexport) +#else + #define HM_API __attribute__((visibility("default"))) +#endif + +#define MOD_INIT HM_API void ModInit +#define MOD_EXIT HM_API void ModExit + +extern void* ScriptGetFunction(const char* module, const char* function); + +#define CALL_FUNC(mod, func, ...) ((func##Func)ScriptGetFunction(mod, func##Symbol))(__VA_ARGS__) + +// STD-Replacements +#define malloc(size) GameEngine_Malloc(size) +#define free(ptr) GameEngine_Free(ptr) \ No newline at end of file diff --git a/workspace/template/manifest.json b/workspace/template/manifest.json new file mode 100644 index 000000000..1a3bb5c7f --- /dev/null +++ b/workspace/template/manifest.json @@ -0,0 +1,10 @@ +{ + "name": "Demo Mod", + "main": "build.gen", + "version": "1.0.0", + "website": "https://example.com", + "description": "A simple demo mod for testing purposes.", + "author": "Your Name", + "license": "MIT", + "code-version": 1 +} \ No newline at end of file diff --git a/workspace/template/src/demo.c b/workspace/template/src/demo.c new file mode 100644 index 000000000..f9d93a6e2 --- /dev/null +++ b/workspace/template/src/demo.c @@ -0,0 +1,37 @@ +#include "mod.h" + +#define CIMGUI_DEFINE_ENUMS_AND_STRUCTS +#include "cimgui.h" + +#include "port/hooks/Events.h" +#include "port/api/UIWidgets_Bridge.h" +#include + +ListenerID gFrameUpdateListenerID; +ListenerID gUIRenderListenerID; + +void OnFrameUpdate(IEvent* event) { + gHitCount = 99; + + RCP_SetupDL(&gMasterDisp, SETUPDL_83); + gDPSetPrimColor(gMasterDisp++, 0, 0, 255, 255, 0, 255); + if(CVarGetInteger("gSayHello", 0)) { + Graphics_DisplayLargeText(20, 20, 1.0f, 1.0f, "MOD HELLO"); + } +} + +void OnUIRender(IEvent* event) { + if(UIWidgets_BeginMenu("Demo Menu", 10, 10, 200, 100)) { + UIWidgets_CVarCheckbox("Demo Checkbox", "gSayHello", NULL); + igEndMenu(); + } +} + +MOD_INIT() { + gUIRenderListenerID = REGISTER_LISTENER(EngineRenderModsEvent, EVENT_PRIORITY_NORMAL, OnUIRender); + gFrameUpdateListenerID = REGISTER_LISTENER(GamePostUpdateEvent, EVENT_PRIORITY_NORMAL, OnFrameUpdate); +} + +MOD_EXIT() { + UNREGISTER_LISTENER(GamePostUpdateEvent, gFrameUpdateListenerID); +} \ No newline at end of file